Python Code for a Simple "Guess the Number" Game

Answered using GPT 40 by GPT40

Question:

give me python codes for creating a simple game

Answer:

Sure! Let's create a simple text-based game in Python. We'll make a basic "Guess the Number" game where the computer randomly selects a number between 1 and 100, and the player has to guess it. The game will provide feedback on whether the guess is too high, too low, or correct.

Here's the code for the game:

import random

def guess_the_number():
    # Generate a random number between 1 and 100
    number_to_guess = random.randint(1, 100)
    attempts = 0
    guessed = False

    print("Welcome to 'Guess the Number'!")
    print("I have selected a number between 1 and 100. Can you guess it?")

    while not guessed:
        try:
            # Get the player's guess
            player_guess = int(input("Enter your guess: "))
            attempts += 1

            # Check if the guess is correct
            if player_guess < number_to_guess:
                print("Too low! Try again.")
            elif player_guess > number_to_guess:
                print("Too high! Try again.")
            else:
                guessed = True
                print(f"Congratulations! You've guessed the number in {attempts} attempts.")
        except ValueError:
            print("Invalid input. Please enter a valid number.")

if __name__ == "__main__":
    guess_the_number()

How to Run the Game

  1. Copy the code into a Python file, for example, guess_the_number.py.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Run the game by typing python guess_the_number.py and pressing Enter.

How the Game Works

  1. The game starts by generating a random number between 1 and 100.
  2. The player is prompted to guess the number.
  3. The game provides feedback on whether the guess is too high, too low, or correct.
  4. The game continues until the player guesses the correct number.
  5. The game then displays the number of attempts it took to guess the number correctly.

Feel free to modify and expand the game to add more features or make it more complex!