python联机猜拳的代码
时间: 2023-03-28 07:01:12 浏览: 76
以下是一个简单的 Python 联机猜拳游戏的代码:
```
import random
import socket
# 创建一个 TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定 socket 到一个端口
server_address = ('localhost', 10000)
print('启动服务器 {} 的端口 {}'.format(*server_address))
sock.bind(server_address)
# 监听 incoming connections
sock.listen(1)
while True:
# 等待连接
print('等待连接...')
connection, client_address = sock.accept()
try:
print('客户端连接:', client_address)
# 发送欢迎消息
connection.sendall(b'欢迎来到猜拳游戏!')
# 等待客户端做出选择
while True:
data = connection.recv(16)
print('收到: {!r}'.format(data))
if data:
# 生成服务器的选择
choices = ['石头', '剪刀', '布']
server_choice = random.choice(choices)
# 判断胜负
client_choice = data.decode('utf-8')
if client_choice == server_choice:
result = '平局'
elif (client_choice == '石头' and server_choice == '剪刀') or \
(client_choice == '剪刀' and server_choice == '布') or \
(client_choice == '布' and server_choice == '石头'):
result = '你赢了!'
else:
result = '你输了!'
# 发送结果
message = '你选择了 {},服务器选择了 {},结果是:{}'.format(
client_choice, server_choice, result)
connection.sendall(message.encode('utf-8'))
else:
print('客户端关闭')
break
finally:
# 清理连接
connection.close()
```
注意:这只是一个简单的示例代码,实际应用中可能需要更多的错误处理和安全措施。