gpt4 book ai didi

python - Python 中的并行 while 循环

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:45 26 4
gpt4 key购买 nike

我对 Python 和一般编程还很陌生,我正在为我的小妹妹创建一个虚拟宠物风格的游戏。

是否可以在 python 中并行运行 2 个 while 循环?例如:

while 1:
input_event_1 = gui.buttonbox(
msg = 'Hello, what would you like to do with your Potato Head?',
title = 'Main Screen',
choices = ('Check Stats', 'Feed', 'Exercise', 'Teach', 'Play', 'Go to Doctor', 'Sleep', 'Change Favourite Thing', 'Get New Toy', 'Quit'))
if input_event_1 == 'Check Stats':
myPotatoHead.check_p_h_stats()
elif input_event_1 == 'Feed':
myPotatoHead.feed_potato_head()
elif input_event_1 == 'Exercise':
myPotatoHead.exercise_potato_head()
elif input_event_1 == 'Teach':
myPotatoHead.teach_potato_head(myPotatoHead)
elif input_event_1 == 'Play':
myPotatoHead.play_with_toy()
elif input_event_1 == 'Sleep':
myPotatoHead.put_p_h_asleep()
elif input_event_1 == 'Go to Doctor':
myPotatoHead.doctor_check_up()
elif input_event_1 == 'Change Favourite Thing':
myPotatoHead.change_favourite_thing()
elif input_event_1 == 'Quit':
input_quit = gui.ynbox(
msg = 'Are you sure you want to quit?',
title = 'Confirm quit',
choices = ('Quit', 'Cancel'))
if input_quit == 1:
sys.exit(0)

while 1:
time.sleep(20)
myPotatoHead.hunger = str(float(myPotatoHead.hunger) + 1.0)
myPotatoHead.happiness = str(float(myPotatoHead.happiness) - 1.0)
myPotatoHead.tiredness = str(float(myPotatoHead.tiredness) + 1.0)

如果没有,有什么方法可以将其变成一个循环吗?我希望第二个循环中的内容每 20 秒发生一次,但第一个循环中的内容不断发生。

感谢您的帮助

最佳答案

看看Threading.Timer .

有一个code recipe here to schedule a function to run every 5 seconds .

import thread
import threading

class Operation(threading._Timer):
def __init__(self, *args, **kwargs):
threading._Timer.__init__(self, *args, **kwargs)
self.setDaemon(True)

def run(self):
while True:
self.finished.clear()
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
else:
return
self.finished.set()

class Manager(object):

ops = []

def add_operation(self, operation, interval, args=[], kwargs={}):
op = Operation(interval, operation, args, kwargs)
self.ops.append(op)
thread.start_new_thread(op.run, ())

def stop(self):
for op in self.ops:
op.cancel()
self._event.set()

if __name__ == '__main__':
# Print "Hello World!" every 5 seconds

import time

def hello():
print "Hello World!"

timer = Manager()
timer.add_operation(hello, 5)

while True:
time.sleep(.1)

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

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