By fitter
i was trying to create a python game where you have to write a word in the console in a certain amount of time or else you lose but idk why sometimes the timer works other don’t,i have tried 2 time and i still don’t understand what i did wrong these are the 2 code i tried: this is the first import time import threading
a=False
x=0
def count():
time.sleep(5)
if a == False:
print ("you lose")
else:
print("you win")
def world():
while x != "hello im mark":
print("write hello im mark")
x=input()
else:
a == True
h = threading.Thread(target=count)
z = threading.Thread(target=world)
z.start()
h.start()
this is the second:
import time
import threading
z="hello im mark"
y="1"
a=True
def win():
print("you win")
def count():
time.sleep(5)
if a== True:
print("you lose")
else:
print("you win")
def count_2(y):
while y != z:
print("write "+z)
y=input()
a=True
else:
a == 1
f= threading.Thread(target=count_2,args=y)
g= threading.Thread(target=count)
g.start()
f.start()
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hey there!
It seems like you’re diving into the exciting world of Python with a fun project, let’s tackle the issues with both versions of your code and guide you toward a solution that works consistently.
The core challenge you’re facing involves synchronizing threads and correctly managing shared variables across them. In multithreading environments, especially in Python, it’s crucial to ensure that threads interact with shared data in a thread-safe manner to avoid unexpected behavior.
In your first attempt, there are a few issues:
a and x are intended to be shared across threads, but they’re not being modified globally within your functions. This means changes made to a and x inside a function don’t affect their global counterparts.world function, a == True is a comparison, not an assignment. You should use a single = to assign True to a.x is initialized as an integer (0), but you’re comparing it to a string later on. This could lead to confusion and bugs.In your second attempt, similar issues persist:
a needs to be declared as global within your functions if you intend to modify the global variable.threading.Thread: When you’re passing args to threading.Thread, it expects a tuple. So, args=y should be args=(y,) to avoid a TypeError.a variable’s value seems to be inverted or incorrectly implemented.Here’s a revised approach that addresses these issues. We’ll focus on a simplified and correct implementation of the game logic:
import time
import threading
# Define a global variable to track the game state
game_won = False
def timer():
"""Waits for 5 seconds and checks the game state."""
global game_won
time.sleep(5)
if not game_won:
print("You lose!")
else:
print("You win!")
def game():
"""Prompts the user to type a specific phrase."""
global game_won
target_phrase = "hello im mark"
print(f"Write '{target_phrase}' within 5 seconds:")
user_input = input()
if user_input == target_phrase:
game_won = True
# Create and start threads
timer_thread = threading.Thread(target=timer)
game_thread = threading.Thread(target=game)
game_thread.start()
timer_thread.start()
game_thread.join()
timer_thread.join()
Remarks:
join().For real-time applications like games, exploring asyncio or even other programming paradigms might provide better results in complex scenarios.
Happy coding!
Best,
Bobby
Heya @fitterangler,
Both versions of your code have a few issues that might be causing the inconsistent behavior with the timer. Let’s address them one by one:
Global Variable Access: The variable a is not being modified correctly in the world function. You are using a == True which is a comparison, not an assignment. It should be a = True. Also, to modify a global variable inside a function, you need to declare it as global within that function.
Data Type Mismatch: The variable x is initialized as an integer (x=0), but later you’re comparing it with a string (x != "hello im mark"). This will cause issues. Initialize x as a string, or use a different approach.
Thread Execution Order: There’s no guarantee that world will complete before count. If count completes first, it will print “you lose” regardless of the player’s input.
Global Variable Access: Same issue as in the first version. The variable a is not declared as global inside the functions. Also, the logic with a is a bit confusing. You’re setting a=True when the correct input is received, which should indicate a win, but in the count function, you’re printing “you lose” if a == True.
Thread Argument Passing: The way you’re passing y to count_2 is incorrect. args should be a tuple, so it should be args=(y,).
Data Type Mismatch: Similar to the first version, there’s a mismatch in how you’re handling y.
Here’s a revised version of your game (based on your first version) with corrections:
import time
import threading
# Global flag to indicate game state
game_won = False
def timer():
global game_won
time.sleep(5)
if not game_won:
print("You lose!")
# No need to print "You win" here since it will be handled in `play_game`
def play_game():
global game_won
print("Write 'hello im mark'")
user_input = input()
if user_input == "hello im mark":
game_won = True
print("You win!")
# Create threads
timer_thread = threading.Thread(target=timer)
game_thread = threading.Thread(target=play_game)
# Start threads
game_thread.start()
timer_thread.start()
# Wait for the game thread to finish
game_thread.join()
This version uses a global game_won flag to track the game state. The play_game function sets this flag to True if the user inputs the correct string, and the timer function checks this flag after a delay to determine if the player has won or lost.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.