Code me a game?
Sure! Below is a simple text-based number guessing game written in Python. The player has to guess a randomly generated number between 1 and 100. The game gives hints if the guess is too high or too low.
You can copy and run this code in your local Python environment:
import random
def number_guessing_game():
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Randomly generate a number between 1 and 100
secret_number = random.randint(1, 100)
attempts = 0
guessed = False
while not guessed:
try:
# Prompt the player to enter a guess
guess = int(input("Please enter your guess: "))
attempts += 1
# Check the guess against the secret number
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You've guessed the number {secret_number} in {attempts} attempts!")
guessed = True
except ValueError:
print("Invalid input! Please enter a number between 1 and 100.")
# Run the game
if __name__ == "__main__":
number_guessing_game()
How to Play:
- Copy the code into a Python file (e.g.,
number_guessing_game.py). - Run the script using Python in your terminal or command prompt.
- Follow the prompts to guess the number!
Feel free to modify the game, such as changing the number range or adding features like a scoring system or difficulty levels! Enjoy coding!