I’ve made a Farkle Jabber game bot using Python SleekXMPP library.
In multiplayer mode, a user plays against a user by turns. I’m trying to make a timeout duration so that if your opponent didn’t respond in 1 minute for example, you win.
Here’s what I’ve tried:
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()
The problem with the code above is that it will freeze the whole class until the 1 minute passes. How can I avoid that? I tried putting the timeout funcion outside the class, but nothing’s changed.
If you must wait for something, it is best to use time.sleep() instead of busy waiting. You should rewrite your timeout like this:
As you see, you must somehow keep track of whether a move has been received on time.
Therefore an easier solution might be to set an alarm using
threading.Timer. You must then set a handler to handle the timeout. E.g.