[英]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.