Sure, I'll guide you through creating a simple text-based game in Python. Let's create a simple "Guess the Number" game where the player has to guess a randomly generated number between 1 and 100.
Here's a complete code for the game:
python
import random
def guess_the_number():
print("Welcome to 'Guess the Number'!")
print("I have selected a random number between 1 and 100.")
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
guess = input("Please enter your guess (or type 'exit' to quit): ")
if guess.lower() == 'exit':
print("Thanks for playing! Goodbye.")
break
try:
guess_number = int(guess)
except ValueError:
print("Invalid input. Please enter a number between 1 and 100 or 'exit' to quit.")
continue
attempts += 1
if guess_number < 1 or guess_number > 100:
print("Please guess a number within the range of 1 to 100.")
elif guess_number < number_to_guess:
print("Too low! Try again.")
elif guess_number > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You've guessed the number in {attempts} attempts.")
break
if __name__ == "__main__":
guess_the_number()
Here's a step-by-step explanation of how the code works:
Imports: The random module is imported to generate a random number.
Function Definition: A function guess_the_number() is defined to encapsulate the game logic.
Game Introduction: The game welcomes the player and explains the rules.
Random Number Generation: A random number between 1 and 100 is generated using random.randint(1, 100) and stored in number_to_guess.
Attempts Counter: An attempts counter is initialized to zero to keep track of the number of guesses.
Game Loop: A while True loop is used to repeatedly prompt the player for input until they guess the number or type 'exit' to quit.
Player Input: The player is prompted to enter their guess or 'exit' to quit the game.
Exit Condition: If the player types 'exit', the game thanks them and breaks out of the loop.
Input Validation: The code checks if the input is a valid integer; if not, it prompts the player to enter a valid input.
Range Check: The code checks if the guessed number is within the range of 1 to 100.
Hints: Depending on whether the guess is too low, too high, or correct, appropriate feedback is provided.
Success Condition: If the player guesses the correct number, they are congratulated, and the game ends.
Main Block: The game is started by calling guess_the_number() if the script is executed as the main program.
You can run this code in any Python environment, and it will prompt you to guess the number, providing feedback until you guess correctly or choose to exit.