我用pythonsleekxmpp库制作了一个FarkleJabber游戏机器人。 在多人游戏模式下,一个用户轮流和一个用户玩。我试着设定一个暂停时间,这样如果你的对手在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
函数放在类之外,但是没有任何改变。在
如果你一定要等什么,最好用时间。睡觉()而不是忙着等待。您应该这样重写超时:
正如你所看到的,你必须以某种方式跟踪一个移动是否被及时接收。在
因此,更简单的解决方案可能是使用
^{pr2}$threading.Timer
设置警报。然后必须设置一个处理程序来处理超时。E、 g相关问题 更多 >
编程相关推荐