gpt4 book ai didi

python - While 循环问题 - Python

转载 作者:行者123 更新时间:2023-12-01 05:40:41 29 4
gpt4 key购买 nike

我用 Python 创建了一个简单的基于文本的游戏,将其与 libPd(纯数据的包装器)结合使用。所有游戏代码都是在音频实现之前编写的,并且按预期工作;同样,libPd 脚本本身也可以完美运行。然而,让他们一起愉快地玩耍是很棘手的。

我认为这与 while 循环和我对它们的使用有关。

以下是游戏代码的摘录 -

    while True:

command = raw_input().lower()

if command == "commands":
print '"look around"'
print '"explore"'
print '"inventory"'
print '"examine"'
print '"take"'
print '"combine"'
print '"quit"'
elif command == "look" or command == "look around":
char.look()

...等等......等等...

虽然 libPd 脚本本身如下 -

    while True:

if not ch.get_queue():
for x in range(BUFFERSIZE):
if x % BLOCKSIZE == 0:
outbuf = m.process(inbuf)
samples[selector][x][0] = outbuf[(x % BLOCKSIZE) * 2]
samples[selector][x][1] = outbuf[(x % BLOCKSIZE) * 2 + 1]
ch.queue(sounds[selector])
selector = int(not selector)
libpd_release()

我最初尝试在 libPd 部分中缩进整个游戏代码,但这导致音频仅在键入命令后播放,在返回打印消息后停止。

我如何将两者结合起来,以便音乐保持不变,同时玩家可以自由地运行其余的命令/游戏?

最佳答案

您的问题是您必须等待 raw_input() 返回,但同时您必须在音频消息进入后立即继续处理队列中的音频消息。如何你可以同时做这两件事吗?

<小时/>

首先,您今天使用的是事件循环样式。

如果您可以编写一个等待输入或音频消息的函数(以先到者为准),您可以围绕等待该函数的循环重写程序。这一般来说是很难做到的。 (GUI 框架和网络服务器框架可以提供帮助,但对于您的文本游戏来说,这两种框架都有点愚蠢。)

您可以通过仅在每一行等待较短的时间来伪造它,例如,通过在 sys.stdin 上使用 select.select 并设置较短的超时时间。但这是一项艰巨的工作,并且很难通过这样的设计来平衡响应能力和性能。

<小时/>

或者,您可以使用线程。它看起来像这样:

def play_music():
while True:
if not ch.get_queue():
for x in range(BUFFERSIZE):
if x % BLOCKSIZE == 0:
outbuf = m.process(inbuf)
samples[selector][x][0] = outbuf[(x % BLOCKSIZE) * 2]
samples[selector][x][1] = outbuf[(x % BLOCKSIZE) * 2 + 1]
ch.queue(sounds[selector])
selector = int(not selector)
libpd_release()

play_music_thread = threading.Thread(target=play_music)
play_music_thread.daemon = True
play_music_thread.start()

while True:
command = raw_input().lower()

if command == "commands":
print '"look around"'
print '"explore"'
print '"inventory"'
print '"examine"'
print '"take"'
print '"combine"'
print '"quit"'
elif command == "look" or command == "look around":
char.look()

如果您希望能够干净地关闭,而不是在退出时让音乐线程在它正在执行的任何操作中间被杀死,那就有点复杂了……但也没有那么复杂。基本上,使用 ConditionEventQueue 或只是一个 bool 变量和 Lock,您可以轻松地构建一种从主线程向背景音乐线程发出信号的方法。

关于python - While 循环问题 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17623245/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com