@@ -11,30 +11,46 @@ import random
11
11
def play_guessing_game():
12
12
# Generate a random number between 1 and 50
13
13
secret_number = random.randint(1, 50)
14
+ # Set the maximum number of attempts to 10
14
15
max_attempts = 10
16
+ # Initialize the number of attempts made by the player
15
17
attempts = 0
16
18
19
+ # Welcome message for the player
17
20
print("Welcome to the Number Guessing Game!")
18
- print(f"I'm thinking of a number between 1 and 100. Can you guess it?")
21
+ # Informing the player about the range of the secret number
22
+ print(f"I'm thinking of a number between 1 and 50. Can you guess it?")
19
23
24
+ # Loop until the player runs out of attempts or guesses the number
20
25
while attempts < max_attempts:
21
26
try:
27
+ # Prompt the player to enter their guess
22
28
guess = int(input("Enter your guess: "))
29
+ # Increment the number of attempts
23
30
attempts += 1
24
31
32
+ # Check if the player's guess is correct
25
33
if guess == secret_number:
34
+ # Congratulate the player and break the loop if the guess is correct
26
35
print(f"Congratulations! You guessed it right in {attempts} attempts.")
27
36
break
37
+ # Provide a hint if the guess is lower than the secret number
28
38
elif guess < secret_number:
29
39
print("Try a higher number.")
40
+ # Provide a hint if the guess is higher than the secret number
30
41
else:
31
42
print("Try a lower number.")
32
43
44
+ # Handle non-integer inputs and prompt the player to enter a valid integer
33
45
except ValueError:
34
46
print("Invalid input. Please enter a valid integer.")
35
47
48
+ # Inform the player if they have used all their attempts without guessing correctly
36
49
if attempts == max_attempts:
37
50
print(f"Sorry, you've reached the maximum number of attempts. The secret number was {secret_number}.")
38
51
52
+ # Check if the script is run directly (not imported)
39
53
if __name__ == "__main__":
54
+ # Start the game if the script is run directly
40
55
play_guessing_game()
56
+
0 commit comments