2017-11-29 17 views
-1

私はPythonにはかなり新しく、質問/回答用のtxtファイルにリンクして高得点を保存するトリビアクイズを作成しました。私のゲームと並行してPythonでカウントダウンタイマーを実行するにはどうすればよいですか?

EDIT私はたとえば1分間、回答する質問の制限時間を設定したいと思いますpygameの

を使用していません。私はカウントダウンにタイマを取得することができたが、それはカウントダウンし、その後、私のゲームに進みます。

一緒に走らせる方法はありますか? 、あなたがしたい場合

import linecache 
import sys 
import pickle 
import time 

def countdown(): 
    t = 60 
    while t: 
     mins, secs = divmod(t, 60) 
     timeformat = '{:02d}:{:02d}'.format(mins, secs) 
     print(timeformat, end='\r') 
     time.sleep(1) 
     t -= 1 
    print('You're out of time!\n') 

def travel(): 
    i = 0 
    countdown() 
    name = input("What is your name: ") 
    q1 = linecache.getline("travel.txt", 1) 
    a1 = linecache.getline("travel.txt", 2) 
    b1 = linecache.getline("travel.txt", 3) 
    c1 = linecache.getline("travel.txt", 4) 
    print("\n", q1, a1, b1, c1) 
    q = input("Answer: ") 
    if q == "b": 
     print("Correct! You've scored 1 point.") 
     i += 1 
    else: 
     print("Wrong answer buddy, 0 points.") 
+0

あなたは 'Thread'モジュールを使うことができます – AJ123

+0

どのように動作しますか? –

+0

私はそれがバックグラウンドで手順を実行すると思うが、私はそれほど確かではない。それはあまり使わなかった。 – AJ123

答えて

1

:ここに私のコード(だけでなく、トップビット)です

...私は、whileループを考えたが、それはちょうどので、私はそれが間違っていた推測している、それを台無しにこの機能を使用するにはthreading.Threadを使用できます。

注次のコード:main_game()が開始された後に、この例では

import threading 
import time  

def countdown(): 
    t = 60 
    while t: 
     mins, secs = divmod(t, 60) 
     timeformat = '{:02d}:{:02d}'.format(mins, secs) 
     print(timeformat, end='\r') 
     time.sleep(1) 
     t -= 1 
    print("You're out of time!\n") 
    # add some function which stops the game, for example by changing a variable to false (which the main thread always checks) 
    # or some other method like by checking count_thread.is_alive() 

def main_game(): 
    count_thread = threading.Thread(None, countdown) 
    # do game things 

は、print("You're out of time")は60秒が起こるのだろうが、同時に# do game thingsでコードが実行されます。実装する必要があるのは、count_thread自体がゲームを終了させる方法であるか、スレッドがまだ生きているかどうかを確認し、そうでない場合は終了させる方法です。

関連する問題