【发布时间】:2014-02-11 14:07:38
【问题描述】:
我正在尝试为像井字游戏或跳棋/国际象棋这样的游戏编写游戏管理器/控制器:
Game Arbiter:控制游戏的玩法并将对手的动作传递给每个玩家。还确定移动是否合法
GamePlayer.py
- 会在仲裁者询问时下棋
GameArbiter.py
- 将决定哪个玩家先行
- 将决定移动是否合法
- 将保留对两位玩家的引用
- 将要求正确的玩家移动并提供当前游戏状态
我的问题是仲裁者将如何与玩家沟通?我想使用 PIPE.communicate() 但似乎只有在播放器在每个 .communicate() 请求后终止时才有效。我的代码是这样的:
GameArbiter.py:
import subprocess
import sys
player1 = subprocess.Popen([sys.executable, "GamePlayer.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
instruction = "GetMove"
out, _ = player1.communicate(instruction.encode())
print(out.decode()) # process input from player
# do some stuff
instruction = "GetMove"
out, _ = player1.communicate(instruction.encode())
print(out.decode()) # process input from player
GamePlayer.py:
instruction = input()
if(instruction == "GetMove"):
print("Bc4xc5")
else:
print("InvalidInstruction")
当然,在第二个 .communicate() python 崩溃后,因为 player1 不再是打开的文件
我的问题是我将如何(在 python 中)编写一个可以主动与多个孩子异步来回交谈的委托?
【问题讨论】:
标签: python multithreading