Skip to content
Home » Posts » How to write simple game with python

How to write simple game with python

  • by

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:

  1. Imports: We import the random module to generate random numbers.
  2. Welcome Message: A friendly welcome message is displayed to the player.
  3. Generate a Random Number: We use random.randint(1, 100) to generate a random number between 1 and 100.
  4. Set Maximum Attempts: We define the maximum number of attempts allowed in the game.
  5. Main Game Loop: The game runs in a loop until the player guesses the correct number or runs out of attempts.
  6. Player’s Guess: The player is prompted to enter their guess, and we convert the input to an integer.
  7. Check Guess: We compare the player’s guess with the secret number and provide feedback (too low, too high, or correct).
  8. 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.
  9. 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.
  10. Function Call: The guess_the_number() function is called to start the game when the script is run.

Photo by Nikita on Unsplash