How to Create a Guess My Number Game in Python
This tutorial is on how to make a guess my number game in Python.
This is a simple game where the computer chooses a random number, then the player has a certain amount of guesses to guess the correct number by following the feedback (too high, or too low).
First we need to import the random module to let the computer choose a random number...
- import random;
Next we want to create the variables that will be used throughout the game. We need the current player lives count, the number to guess, and the current player guess. The number (computers) to guess is in caps because it is a constant and will not change.
- GUESS = random.randint(0, 100);
- lives = 5;
- player = int(input("Enter your guess...\n"));
The Game Loop:
Now we perform the real game loop. While the player has lives left, and the players current guess is not the correct number, we output whether their current guess is too high, or too low, remove one life, and ask for another number guess...
- while (player is not GUESS and lives > 0):
- if (player < GUESS):
- print("Wrong, too low.");
- print("Wrong, too high.");
- lives -= 1;
- player = int(input("\n"+str(lives+1)+" lives left.\nEnter your guess...\n"));
Finally we come out of the while loop and check if the player has any lives left (they can play on 0, so we check if lives is equal to 0 or higher), if they do they won so we say "Correct!". If they haven't won, we tell them the correct number...
- if (lives > -1):
- print("You ran out of lives. The correct answer was " + str(GUESS));