give me python codes for creating a simple game
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()
guess_the_number.py
.python guess_the_number.py
and pressing Enter.Feel free to modify and expand the game to add more features or make it more complex!