Python脚本通讯

2024-06-26 02:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为Tic Tac Toe或checkers/chess这样的游戏编写一个游戏管理器/控制器:

游戏仲裁者:控制游戏的游戏性,并将对手的移动传递给每个玩家。还确定移动是否合法

你知道吗游戏玩家.py你知道吗

  • 当仲裁者要求时,他将采取行动

你知道吗游戏仲裁者.py你知道吗

  • 将决定哪个选手先上场
  • 将决定此举是否合法
  • 将保留两名球员的参考资料
  • 将要求正确的玩家移动并提供当前游戏状态

我的问题是,仲裁员将如何与球员沟通?我想用管道.通讯()但似乎只有在每次.communicate()请求后播放器终止时才有效。我的代码如下:

你知道吗游戏仲裁者.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

你知道吗游戏玩家.py地址:

instruction = input()
if(instruction == "GetMove"):
    print("Bc4xc5")
else:
    print("InvalidInstruction")

当然,在第二个.communicate()之后,python崩溃了,因为player1不再是一个打开的文件

我的问题是如何(在python中)编写一个能够主动地与多个子级异步地来回交谈的委托?你知道吗


Tags: py游戏input地址玩家outsubprocessprint
3条回答

为什么不让GamePlayer成为一个函数,让get被无限调用呢?你知道吗

或者更好的是,一个类,游戏中的每个玩家都将继承它。你知道吗

如果所有这些都发生在一台机器上,那么我想知道您是否需要有单独的进程。你知道吗

如果目标是将player进程移动到不同的机器上,那么我建议您在典型的客户机-服务器模型中使用进程之间的网络通信。在这种情况下,我推荐Twisted

What is Twisted?

Twisted is an event-driven networking engine written in Python and licensed under the open source MIT license.

communicate是位于player1.stdin.writeplayer1.stdout.read之上的高级函数。有一种方法可以实现您正在尝试做的事情,但是这会给您的代码带来很多复杂性(您需要生成单独的线程来读取另一个进程的stdout、flushing等)。如果您想浏览所有内容,可以查看communicate函数的源代码。你知道吗

更标准的解决方案是使用客户机-服务器体系结构通过网络进行通信

相关问题 更多 >