-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeedMathGame.py
More file actions
54 lines (50 loc) · 1.92 KB
/
speedMathGame.py
File metadata and controls
54 lines (50 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Import modules
import random
import time
# Init variables
EXPRESSION_LIST = ["+", "-", "*", "/"]
mathEquation = {
"integer1": 0,
"integer2": 0,
"operator": "",
"solution": 0
}
def generateExpression():
global mathEquation
# Setup math equation
mathEquation["integer1"] = random.randint(0, 10)
mathEquation["integer2"] = random.randint(0, 10)
mathEquation["operator"] = random.choice(EXPRESSION_LIST)
# Calculate solution
operator = mathEquation["operator"]
if operator == "+":
mathEquation["solution"] = mathEquation["integer1"] + mathEquation["integer2"]
elif operator == "-":
mathEquation["solution"] = mathEquation["integer1"] - mathEquation["integer2"]
elif operator == "*":
mathEquation["solution"] = mathEquation["integer1"] * mathEquation["integer2"]
elif operator == "/":
# Avoid division by zero
while mathEquation["integer2"] == 0:
mathEquation["integer2"] = random.randint(0, 10)
mathEquation["solution"] = round(mathEquation["integer1"] / mathEquation["integer2"], 2)
def gameLoop():
index = 0
startTime = time.time()
while index < 10:
generateExpression()
userAnswer = input(f"{mathEquation['integer1']} {mathEquation['operator']} {mathEquation['integer2']} = ")
if not userAnswer == "" and float(userAnswer) == mathEquation["solution"]:
print("Correct, " + str(9 - index) + " remain.")
index += 1
else:
print("Incorrect.")
endTime = time.time()
totalTime = endTime - startTime
print("You win! Time: " + str(round(totalTime, 2)) + " seconds.")
input("Press Enter to play again. ")
gameLoop()
print("Answer 10 math expressions as quickly as possible.")
print("Note: For division, round your answer to 2 decimal places.")
input("Press Enter to begin the game. ")
gameLoop()