How to Create a Guess My Number Game in Python
Submitted by Yorkiebar on Tuesday, March 11, 2014 - 08:23.
Introduction:
This tutorial is on how to make a guess my number game in Python.
The Game:
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).
The Imports:
First we need to import the random module to let the computer choose a random number...
The Variables:
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.
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...
The Ending:
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...
- import random;
- GUESS = random.randint(0, 100);
- lives = 5;
- player = int(input("Enter your guess...\n"));
- while (player is not GUESS and lives > 0):
- if (player < GUESS):
- print("Wrong, too low.");
- else:
- print("Wrong, too high.");
- lives -= 1;
- player = int(input("\n"+str(lives+1)+" lives left.\nEnter your guess...\n"));
- if (lives > -1):
- print("Correct!");
- else:
- print("You ran out of lives. The correct answer was " + str(GUESS));
Add new comment
- 22 views