Kickstart your coding journey with our Python Code Assistant. An AI-powered assistant that's always ready to help. Don't miss out!
In this tutorial, we will make a simple maths game on the console with the PyInputPlus module. The main features of this simple game are adding points (like a score), multiple equation types (such as addition, subtraction, multiplication, and division), and the ability to stop the game.
To get started, since PyInputPlus is not a built-in module, we have to install it:
$ pip install PyInputPlus
Importing PyInputPlus and random:
# Imports
import pyinputplus as pyip
from random import choice
Related: How to Make a Hangman Game in Python.
We continue by setting up some variables to use later.
The questionTypes
list holds the operators which can be used in the equations; keep in mind that they have to be valid Python operators. You could add the modulo (%)
or any other valid Python operator to the list to enable these operators in the game. These will be randomly chosen with the random.choice()
function.
Next, we define a list called numberRange
which holds all numbers that can appear in the equations. We can do this in one line.
Last but not least, we define a points variable, which starts with 0.
# Variables
questionTypes = ['+', '-', '*', '/', '**']
numbersRange = [num for num in range(1, 20)]
points = 0
To ensure that the user knows what he has to do, we print some hints about the game.
Later we will round Solutions because equations like 7 / 4
are impossible to write out.
We will also enable the user to stop the game after every question. That's why we mention it here.
# Hints
print('Round down to one Number after the Comma.')
print('When asked to press enter to continue, type stop to stop.\n')
We now enter the game loop, where we start by deciding on a question type. This is done with the random.choice()
method from the random module. This will return one of the items from the questionTypes
.
Then we build the equation where we also use the random.choice()
to choose random items from the numbersRange
list and insert them in this string.
After that, we used Python's great eval()
function. It takes a string and evaluates it, and returns the solution. We save this to the solution variable; we later test this against what the user has written.
# Game Loop
while True:
# Deciding and generating question
currenType = choice(questionTypes)
promptEquation = str(choice(numbersRange)) + ' ' + currenType + ' ' + str(choice(numbersRange))
solution = round(eval(promptEquation), 1)
Next, we use the inputNum()
method from the PyInputPlus Module. This function will test if the input was a number, and if not, it will ask again. We fill out its prompt parameter with our prompt string; keep in mind to add ' = '
so it makes sense for the user. We could not have done this before the eval()
function because it would work that way.
# Getting answer from User
answer = pyip.inputNum(prompt=promptEquation + ' = ')
After we receive the user input, we test it against the solution returned by the eval()
function. If they match, we raise the points by one and print out a nice comment and the new point number.
If it's wrong, we lower the points by one and print out the right solution.
# Feedback and Points
if answer == solution:
points += 1
print('Correct!\nPoints: ',points)
else:
points -= 1
print('Wrong!\nSolution: '+str(solution)+'\nPoints: ',points)
Last but not least, we halt the game after every question. If the user presses enter, it continues. For that to work, we have to set blank
to True
but if the user types stop
, the game will stop.
# Stopping the Game
if pyip.inputStr('Press "Enter" to continue', blank=True) == 'stop':
break
# Some Padding
print('\n\n')
Let's run it:
$ python simple_math_game.py
Round down to one Number after the Comma.
When asked to press enter to continue, type stop to stop.
5 ** 4 = 625
Correct!
Points: 1
Press "Enter" to continue
9 ** 18 = 190
Wrong!
Solution: 150094635296999121
Points: 0
Press "Enter" to continue
7 - 17 = -10
Correct!
Points: 1
Press "Enter" to continue
stop
Awesome! Now you know how to make a simple console math game with PyInputPlus. You can get the complete code here.
Learn also: How to Generate Random Data in Python
Happy coding ♥
Liked what you read? You'll love what you can learn from our AI-powered Code Explainer. Check it out!
View Full Code Understand My Code
Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!