简体   繁体   中英

Running a live timer concurrently with a quiz game in Python

first time posting here on Stackoverflow. I am currently learning python and am trying to make a simple game where the player will be shown a random 2 decimal place number and have to add up to 10. I want the game to only last 30 seconds, hence I added a clock function as well.

However, I am facing some troubles running both the clock and the game together at the same time. I have tried using threading but sadly it didn't work out. Appreciate all the help I can get!

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()

Your problem is probably on that line

clock_thread = threading.Thread(target=clock(31))

What you are doing right now is launching the function cloack with the argument 31, what you want to do is give a pointer to the function lock, and then give the argument 31

so you'd need to do something like that:

clock_thread = threading.Thread(target=clock, args=(31,))

args is a keyword same as target leading to the arguments you wanna give to the function(note that it has to be a tuple, ence why I wrote (31,)), and note that I didn't put the "()" after clock because I'm giving a pointer to the function clock, not launching the function clock

same, game_thread = threading.Thread(target=game()) becomes: game_thread = threading.Thread(target=game) for the same reasons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM