Question

i don't understand what i did wrong

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

Submit an answer


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!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
February 27, 2024

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:

First Version

  1. 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.

  2. 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.

  3. 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.

Second Version

  1. 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.

  2. 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,).

  3. 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.

Bobby Iliev
Site Moderator
Site Moderator badge
February 27, 2024

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:

  1. Global Variable Access: The variables 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.
  2. Comparison vs Assignment: In the world function, a == True is a comparison, not an assignment. You should use a single = to assign True to a.
  3. Variable Type Mismatch: 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:

  1. Global Variable Modification: The variable a needs to be declared as global within your functions if you intend to modify the global variable.
  2. Argument Type for 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.
  3. Consistent State Management: Your logic for winning or losing the game based on the 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:

  • Global Variable Management: Clearly declaring and modifying global variables within functions.
  • Simplified Logic: Streamlining the game logic to focus on the core functionality.
  • Thread Synchronization: Ensuring the main thread waits for both threads to complete using 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

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel