Writing a simple game in Python is a great way to practice programming and have some fun. Here, I’ll guide you through creating a basic “Guess the Number” game. This game will generate a random number, and the player has to guess it within a certain number of attempts.
# Guess the Number Game in Python
# Import the 'random' module to generate random numbers
import random
# Function to play the Guess the Number game
def guess_the_number():
# Display a welcome message
print("Welcome to Guess the Number!")
print("I'm thinking of a number between 1 and 100.")
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)
# Set the maximum number of attempts
max_attempts = 10
attempts = 0
# Main game loop
while attempts < max_attempts:
# Get the player's guess
guess = int(input("Enter your guess: "))
# Increment the number of attempts
attempts += 1
# Check if the guess is correct
if guess == secret_number:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif guess < secret_number:
print("Too low. Try again.")
else:
print("Too high. Try again.")
# Check if the player ran out of attempts
if attempts == max_attempts:
print(f"Sorry, you've run out of attempts. The correct number was {secret_number}.")
# Check if the script is being run as the main program
if __name__ == "__main__":
# Call the 'guess_the_number' function to start the game
guess_the_number()
Explanation:
- Imports: We import the
random
module to generate random numbers. - Welcome Message: A friendly welcome message is displayed to the player.
- Generate a Random Number: We use
random.randint(1, 100)
to generate a random number between 1 and 100. - Set Maximum Attempts: We define the maximum number of attempts allowed in the game.
- Main Game Loop: The game runs in a loop until the player guesses the correct number or runs out of attempts.
- Player’s Guess: The player is prompted to enter their guess, and we convert the input to an integer.
- Check Guess: We compare the player’s guess with the secret number and provide feedback (too low, too high, or correct).
- End of Game: The game ends with a congratulatory message if the player guesses correctly within the allowed attempts. If not, a message reveals the correct number.
- Main Program Check: The
if __name__ == "__main__":
block ensures that the game starts only if the script is run directly, not if it’s imported as a module. - Function Call: The
guess_the_number()
function is called to start the game when the script is run.