In: Computer Science
TheMathGame
Develop a program in PYTHON that will teach children the basic math facts of addition. The program generates random math problems for students to answer. User statistics need to be kept in RAM as the user is playing the game and recorded in a text file so that they may be loaded back into the program when the student returns to play the game again. In addition, the youngster should be allowed to see how (s)he is doing at any time while (s)he is playing the game.
PROGRAM REQUIREMENTS
1. Generate simple addition problems
a. the total must be an integer > 0
b. the addends must be randomly generated
c. the addends must range in value from 1 to 10, inclusive
2. Validate user input at every opportunity.
3. The program should keep track of the following statistics while the user is playing the game: 1. The total correct answers 2. The total wrong answers
4. A separate text file must be created for every user:
a. Statistics are read from the file at the start of the game (if the user chooses to “Read Stats from file”).
b. Statistics are recorded at the end of every game (if the user chooses to “Write Stats to file”).
5. The program must be developed using the following functions: displayMenu(),promptUser(),generateAddition(),readFromFile(),writeToFile(), and validateUserAnswer(). However, you may add your own functions as necessary. Read below for a detailed description of each function.
6. The displayMenu() function must display the following menu: 1. Generate Addition Problem 2. Read Stats from file 3. Write Stats to file 4. Display Stats 5. End
7. The promptUser() function must prompt the user for a menu option AND validate it; only positive integers from 1-5 should be allowed. This function must return the validated user choice to the caller.
8. The generateAddition() function must generate and display an addition problem with integer addends ranging in value from 1 – 10 inclusive. This function should also compute the correct answer to the problem and return it to the caller.
9. The readFromFile() function must prompt the user for a name and if the text file exists, then read the totalCorrect and totalWrong stats from the file and return to the caller BOTH the totalCorrect, totalWrong values. If the file does not exist, then a message indicating that it does not exist must be displayed to the user.
10. The writeToFile() function must take two parameters; the totalCorrect and the totalWrong and save the stats to a text file. It is important that the text file created MUST have the same name as the user.
11. The validateUserAnswer() function is responsible for validating the user response/answer to the addition problem. This function needs to ENSURE that user input is valid; i.e., an integer and return the validated integer.
12. The main() function puts it all together.
Restrictions: 1. No Global variables 2. No labels or go-to statements 3. No infinite loops in your programs; these are loops that do not have a definite logical expression of other condition to signal when the loops ought to terminate. 4. No break statements to exit loops. 5. The program must not crash for any reason.
Raw_code:
def displayMenu():
print("1. Generate Addition Problem")
print("2. Read Stats from file")
print("3. Write Stats to file")
print("4. Display Stats")
print("5. End")
def promptUser():
option = int(input("Enter an option from 1 to 5: "))
# while loop for input error checking
while(option < 1 or option > 5):
print("Invalid option")
option = int(input("Enter an option from 1 to 5: "))
else:
return option
def generateAddition():
# importing random module
import random
#generating random integer b/w 1 and 10 inclusively
addend1 = random.randint(1, 10)
addend2 = random.randint(1, 10)
print(f"{addend1:1d} + {addend2:1d} = ")
return addend1 + addend2
def readFromFile():
name = input("Enter your name: ")
file_name = name + ".txt"
# using try block to find whether the file exists or not
try:
with open(file_name, "rt") as file:
data = file.read().split()
(totalCorrect, totalWrong) = tuple(data)
return (int(totalCorrect), int(totalWrong))
except FileNotFoundError as err:
print("It does not exist!")
def writeToFile(totalCorrect, totalWrong):
name = input("Enter your name: ")
with open(name + ".txt", "wt") as file:
file.write(str(totalCorrect) + " " + str(totalWrong))
def validateUserAnswer():
# using try statement for user input validation
try:
answer = int(input("Enter an answer: "))
except ValueError as err:
print("It is not an integer!")
answer = validateUserAnswer()
finally:
return answer
# main function
def main():
option = 0
answer = 0
totalCorrect = 0
totalWrong = 0
# initially creating a file with name as username,
# since user first option may 2 (read stats from file)
writeToFile(totalCorrect, totalWrong)
# while loop runs until user end the game
while(option != 5):
# calling displayMenu() function
displayMenu()
# calling promptUser() function
option = promptUser()
# checking user option
if option == 1:
# calling generateAddition function
answer = generateAddition()
# and validating the user answer
if answer == validateUserAnswer():
# if user answer correct, incrementing totalCorrect by 1
totalCorrect += 1
else:
# if user answer is wrong, incrementing totalWrong by 1
totalWrong += 1
elif option == 2:
#note: calling readFromFile always returns the totalCorrect and
totalWrong stored
# at the start of game, by calling writeToFile() will update the
data
totalCorrect, totalWrong = readFromFile()
elif option == 3:
writeToFile(totalCorrect, totalWrong)
elif option == 4:
print("Total Correct = {0:1d}; Total Wrong =
{1:1d}".format(totalCorrect, totalWrong))
print()
#calling function
main()
# file name is taken in writeToFile() function because there is no way to write to a file without knowing the required file name