0

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機能をクラスの外に出してみましたが、何も変わりませんでした。

4

1 に答える 1

1

何かを待つ必要がある場合は、ビジーウェイトではなく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"
于 2012-09-15T16:55:11.057 に答える