[英]Running a live timer concurrently with a quiz game in Python
第一次在 Stackoverflow 上發帖。 我目前正在學習 python 並且正在嘗試制作一個簡單的游戲,玩家將看到一個隨機的小數點后 2 位數字並且必須加起來為 10。我希望游戲只持續 30 秒,因此我添加了一個時鍾 function 為出色地。
但是,我在同時運行時鍾和游戲時遇到了一些麻煩。 我嘗試過使用線程,但遺憾的是它沒有成功。 感謝我能得到的所有幫助!
import random
import time
import threading
number = 10.0
print("Sum up to 10!")
def game():
global score
score = 0
while True:
question = round(random.uniform(0.01, 9.99), 2)
while True:
print("\nYour number is: " + str(question))
try:
answer = float(input("\nAnswer: "))
if question + answer != number:
print("\nWrong answer! Try again!")
elif answer + question == number:
score += 1
print("\nCorrect!")
break
except ValueError:
print("Please key in a number(2 decimals)!")
def clock(countdown=0):
while countdown > 0:
time.sleep(1)
countdown -= 1
print("\rTime Left: " + str(countdown), end="")
if countdown == 0:
print("Final score: " + str(score))
quit()
clock_thread = threading.Thread(target=clock(31))
game_thread = threading.Thread(target=game())
clock_thread.start()
game_thread.start()
你的問題可能就在那條線上
clock_thread = threading.Thread(target=clock(31))
你現在正在做的是使用參數 31 啟動 function cloack,你要做的是給 function 鎖的指針,然后給參數 31
所以你需要做這樣的事情:
clock_thread = threading.Thread(target=clock, args=(31,))
args 是一個與目標相同的關鍵字,通向 arguments 你想給函數(注意它必須是一個元組,因為我寫了(31,)),並注意我沒有放“()”時鍾后,因為我給出了指向 function 時鍾的指針,而不是啟動 function 時鍾
同樣, game_thread = threading.Thread(target=game())
變為: game_thread = threading.Thread(target=game)
出於同樣的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.