我想用服务器和客户端编写一个gomoku游戏,终端版本运行良好,但是pygame版本被阻止并且无法破解任何东西
这是游戏执行功能
首先启动套接字连接
self._running = True
在init
中,从服务器获取的数据包就像{"grid":GRID(strings with 0 and 1), "x":X, "y":Y, "player":LAST_PLAYER, "next_player":CURRENT_PLAYER, "gameover":IS_GAMEOVER}
在循环中:
on_event
并让用户移动(我怀疑此步骤是错误的,因此parse软件包步骤阻塞了主线程?但是我应该如何解决此问题 ),然后将新的移动包发送到服务器这就像循环
while self._running:
data = self.client_thread.reply_q.get(True)
if data:
self.last_player = data["player"]
self.grid = self.grid_str_2_matrix(data["grid"])
self.lastPosition = [data["x"], data["y"]]
self.gomoku_board_init()
if data["gameover"] == -1:
if data["next_player"] != self.player:
self.client_thread.cmd_q.put(ClientCommand(ClientCommand.SEND, {"wait": True}))
print("waiting")
else:
for event in pygame.event.get():
self.on_event(event)
print("new move")
else:
print("game over")
self._running = False
if data["gameover"] == 0:
self.winner = 0
else:
self.winner = data["player"]
self.client_thread.cmd_q.put(ClientCommand(ClientCommand.CLOSE))
break
self.on_render()
self.on_cleanup()
和on_event
函数在中间被调用以加快用户的下一步行动
if data["gameover"] == -1:
if data["next_player"] != self.player:
...
else:
for event in pygame.event.get():
self.on_event(event)
此代码
def on_event(self, event):
print(event.type == pygame.MOUSEBUTTONUP)
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
r = (pos[0] - PADDING + WIDTH // 2) // (WIDTH + MARGIN)
c = (pos[1] - PADDING + WIDTH // 2) // (WIDTH + MARGIN)
print(r, c)
if 0 <= r < self.board_row and 0 <= c < self.board_column and self.grid[r][c] == 0:
self.grid[r][c] = self.player
data = {"grid":self.grid, "x":r, "y":c, "player":self.player}
self.client_thread.cmd_q.put(ClientCommand(ClientCommand.SEND, data))
我在on_event
print(event.type == pygame.MOUSEBUTTONUP)
中添加了打印件,当然MOUSEBUTTONUP
从未发生过(但我想知道为什么吗?)
所以我决定只是使用随机输入跳过此
代码如下
#for event in pygame.event.get():
# self.on_event(event)
x, y = self.random_position()
self.grid[x][y] = self.player
data = {"grid":self.grid, "x":x, "y":y, "player":self.player}
self.client_thread.cmd_q.put(ClientCommand(ClientCommand.SEND, data))
结果是程序包可以正常运行但 GUI仍处于阻塞状态,即使我在while循环中添加了sleep
,它也只有在gameover
我是python多线程以及带有套接字的pygame的新手,我写了一个pygame的一部分,它很好用,terminal + socket也是如此。