并行在Python中循环 [英] Parallel while Loops in Python

查看:125
本文介绍了并行在Python中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很熟悉Python,而且一般编程,我为我的小妹妹创建了一个虚拟的宠物样式游戏。



是否可以运行而 在python中相互平行?
例如:

  while 1:
input_event_1 = gui.buttonbox(
msg =你好,你想用Potato Head做什么?'
title ='Main Screen',
choices =('Check Stats','Feed','Exercise','Teach' 玩,去医生,睡眠,改变喜欢的事物,获取新玩具,退出))
如果input_event_1 ==检查统计:
myPotatoHead。 check_p_h_stats()
elif input_event_1 =='Feed':
myPotatoHead.feed_potato_head()
elif input_event_1 =='运动':
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 =='睡眠'
myPotatoHead.put_p_h_asleep()
elif input_event_1 ==去医生:
myPotatoHead.doctor_check_up()
elif input_event_1 =='更改喜欢的事物':
myPotatoHead.change_favourite_thing()
elif input_event_1 =='退出':
input_quit = gui
msg ='您确定要退出吗?'
title ='确认退出',
choices =('退出','取消'))
如果input_quit == 1:
sys.exit(0)

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

如果没有,有没有办法把它变成一个循环?
我希望第二个循环中的东西每20秒发生一次,但是第一个循环中的东西不断发生。



感谢任何帮助

解决方案

看看 Threading.Timer



这里有一个代码食谱每5秒运行一次的功能

 导入线程
导入线程

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。间隔)
如果不是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 =操作(interval,operation,args,kwargs)
self.ops.appen d(op)
thread.start_new_thread(op.run,())

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

如果__name__ =='__main__':
#打印Hello World!每5秒

导入时间

def hello():
打印Hello World!

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

while True:
time.sleep(.1)


I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister.

Is it possible to run 2 while loops parallel to each other in python? eg:

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)

If not, is there some way that I can turn this into one loop? I want the stuff in the second loop to happen every 20 seconds, but the stuff in the first loop to by constantly happening.

Thanks for any help

解决方案

Have a look at Threading.Timer.

There is a 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中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆