From 61ad650f8f1321e0679fd9d77590c0431cfd631a Mon Sep 17 00:00:00 2001 From: harsh sharma Date: Sun, 6 Aug 2023 13:37:57 +0530 Subject: [PATCH 1/2] added finite number of attempts in the number guessing game --- Number Guessing Game/main.py | 38 +++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/Number Guessing Game/main.py b/Number Guessing Game/main.py index 00af59d2..06a6ceaa 100644 --- a/Number Guessing Game/main.py +++ b/Number Guessing Game/main.py @@ -6,12 +6,20 @@ def start(): global magic_number magic_number = random.randint(1, 100) + print(magic_number) global attempts attempts = 0 + global total_attempts + total_attempts = 5 #total number of attempts that player have + + global attempts_left + attempts_left = total_attempts-attempts + print('---------------------------') print('Guess a number between 1 and 100') + # Function that checks if player won, if it won, returns True def check_win(player_guess): @@ -22,22 +30,34 @@ def check_win(player_guess): elif player_guess == magic_number: return True + +# function that restarts or end the game according to the user's input +def keep_playing(): + keep_playing = input('Keep playing?(y\\n)') + # If player want to keep the game, reset the number of attempts + if keep_playing == 'y': + attempts = 0 + start() + # If player don't want to keep playing, quit the game + elif keep_playing == 'n': + print("Thanks for playing!!") + quit() + start() # Game loop while True: - # Take the player input + # Take the player input\ + print("attempts left:",attempts_left) guess = int(input()) attempts += 1 + attempts_left = total_attempts-attempts if check_win(guess): print('You won! - Number of attempts: ' + str(attempts)) + keep_playing() + if (attempts_left==0): + print("you lost :(") + keep_playing() - keep_playing = input('Keep playing?(y\\n)') - # If player want to keep the game, reset the number of attempts - if keep_playing == 'y': - attempts = 0 - start() - # If player don't want to keep playing, quit the game - elif keep_playing == 'n': - quit() + From 520112a424b77d56d39936b180bb0872a6ad3c9a Mon Sep 17 00:00:00 2001 From: Harsh sharma Date: Sun, 6 Aug 2023 14:18:10 +0530 Subject: [PATCH 2/2] Update main.py --- Number Guessing Game/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Number Guessing Game/main.py b/Number Guessing Game/main.py index 06a6ceaa..c08ebda1 100644 --- a/Number Guessing Game/main.py +++ b/Number Guessing Game/main.py @@ -6,7 +6,7 @@ def start(): global magic_number magic_number = random.randint(1, 100) - print(magic_number) + global attempts attempts = 0