我已经用Farkle SleekXMPP库做了一个Python游戏机器人。在多人模式下,用户轮流与用户对战。我正在尝试设置一个暂停时间,这样如果你的对手在1分钟内没有回应,你就赢了。
这是我尝试过的:
import sleekxmpp
...
time_received={}
class FarkleBot(sleekxmpp.ClientXMPP):
...
def timeout(self, msg, opp):
while True:
if time.time() - time_received[opp] >= 60:
print "Timeout!"
#stuff
break
def messages(self, msg):
global time_received
time_received[user] = time.time()
...
if msg['body'].split()[0] == 'duel':
opp=msg['body'].split()[1] #the opponent
... #do stuff and send "Let's duel!" to the opponent.
checktime=threading.Thread(target=self.timeout(self, msg, opp))
checktime.start()上面代码的问题是,它将冻结整个类,直到1分钟过去。我该如何避免这种情况呢?我试着把timeout函数放在类之外,但是什么都没有改变。
发布于 2012-09-16 00:55:11
如果必须等待,最好使用time.sleep(),而不是忙于等待。你应该像这样重写你的超时:
def timeout(self, msg, opp, turn):
time.sleep(60)
if not turn_is_already_done:
print "Timeout"正如您所看到的,您必须以某种方式跟踪是否已按时收到移动。
因此,更简单的解决方案可能是使用threading.Timer设置警报。然后,您必须设置一个处理程序来处理超时。例如。
def messages(self, msg):
timer = threading.Timer(60, self.handle_timeout)
# do other stuff
# if a move is received in time you can cancel the alarm using:
timer.cancel()
def handle_timeout(self):
print "you lose"https://stackoverflow.com/questions/12439249
复制相似问题