python - python pygame - 多人游戏
问题描述
我正在尝试为来自不同计算机的至少三个参与者创建一个“Draw Something”游戏。
我有一个适用于两个玩家的代码。有谁知道我怎样才能做到三个或更多?
..................................................... ......
这是我的服务器代码:
..................................................... ......
server = ""
port = 5555
games = {}
idCount = 0
currentPlayer = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((server, port))
s.listen()
print("Waiting for a connection, Server Started")
class Game:
def __init__(self, id):
self.connected = False
players = [Player(0), Player(1)]
def threaded_client(conn, player, gameId):
global idCount
conn.send(pickle.dumps(players[player]))
reply = ""
while True:
try:
data = pickle.loads(conn.recv(2048))
players[player] = data
if gameId in games:
game = games[gameId]
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = players[0]
else:
reply = players[1]
conn.sendall(pickle.dumps(reply))
except:
break
print("Lost connection")
try:
del games[gameId]
print("Closing game", gameId)
except:
pass
idCount -= 1
conn.close()
while True:
conn, addr = s.accept()
print("Connected to:", addr)
idCount += 1
p = 0
gameId = (idCount - 1) // 2
if idCount % 2 == 1:
games[gameId] = Game(gameId)
players[0].connected = True
print("Creating a new game")
print("Waiting for another player")
else:
games[gameId].connected = True
p = 1
players[1].connected = True
print("Game is available")
start_new_thread(threaded_client, (conn, currentPlayer, gameId))
currentPlayer += 1
..................................................... ......
谢谢 :) :) :) :)
..................................................... ......
解决方案
您可以做的是,当一个游戏与 2 名玩家一起运行并且第 3 名玩家加入时向他们显示等待更多玩家屏幕,然后当第 4 名玩家加入时运行一个新线程/实例并让服务器处理新实例
但是使用功能强大的电脑来运行服务器,因为如果很多人加入服务器会由于过载而崩溃+你运行服务器的电脑可能会滞后
推荐阅读
- node.js - 在 sequelize 模型中处理关系的正确方法
- php - 如何在 alpine 映像中安装 php-amqplib?
- reactjs - 如何在声明式组件中制作 onChange 事件监听器?
- javascript - 如何设置 Stripe 支付给我们市场上的供应商
- python - 如何访问画布中的颜色列表?基维
- sql - TSQL - 将每条记录的行转换为列
- javascript - 如何从 JavaScript 的控制台输出中去掉“name”和“count”中的双引号?
- google-apps-script - 选中复选框时自动发送电子邮件 - Google 表格
- python - 无法使用 Python 的 playsound 播放音频文件
- hyperledger-fabric - 对等生命周期链码approvalformyorg 错误:发送交易失败:出现意外状态:NOT_FOUND -- 通道不存在