Question

In: Computer Science

TheMathGame Develop a program in PYTHON that will teach children the basic math facts of addition....

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.

Solutions

Expert Solution

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


Related Solutions

Look online- find a website that inspires you to teach children about math and science. Post...
Look online- find a website that inspires you to teach children about math and science. Post the URL address in your response and then tell us what kind of activities this site inspires. What would be one activity you would do with young children to support their math and/or science development?
Need a program in java that creates a random addition math quiz The program should ask...
Need a program in java that creates a random addition math quiz The program should ask the user to enter the following The smallest and largest positive numbers to be used when generating the questions - The total number of questions to be generated per quiz - The total number of the quiz's to create from then the program should generate a random math (Just addition) quiz from what the user entered
Write a program in python language, which accepts 2 numbers and a + sign (for addition)...
Write a program in python language, which accepts 2 numbers and a + sign (for addition) A sign - (for subtraction) A sign * (for multiplication), / (for division) Then calculate and to display the result of the operation he chose with the two numbers. Displaying the appropriate message
create a program that asks user math questions and keeps track of answers... Python Allow the...
create a program that asks user math questions and keeps track of answers... Python Allow the user to decide whether or not to keep playing after each math challenge. Ensure the user’s answer to each math problem is greater than or equal to zero. Keep track of how many math problems have been asked and how many have been answered correctly. When finished, inform the user how they did by displaying the total number of math problems, the number they...
Answer as soon as possible!!! Code must be done with Python Develop a basic File Transfer...
Answer as soon as possible!!! Code must be done with Python Develop a basic File Transfer Protocol (FTP) application that transmits files between a client and a server using Python. Your programs should implement four FTP commands: (1) change directory (cd), (2) list directory content (ls), (3) copy a file from client to a server (put) and (4) copy a file from a server to a client (get). Implement two versions of the program: one that uses stock TCP for...
Write a Python program that will perform various calculations (addition, subtraction, multiplication, division, and average). The...
Write a Python program that will perform various calculations (addition, subtraction, multiplication, division, and average). The program will add, subtract, multiply, or divide 2 numbers and provide the average of multiple numbers inputted from the user. You need to define a function named performCalculation which takes 1 parameter. The parameter will be the operation being performed (+,-,*,/). This function will perform the given prompt from the user for 2 numbers then perform the expected operation depending on the parameter that’s...
Please fix all the errors in this Python program. import math def solve(a, b, c): """...
Please fix all the errors in this Python program. import math def solve(a, b, c): """ Calculate solution to quadratic equation and return @param coefficients a,b,class @return either 2 roots, 1 root, or None """ #@TODO - Fix this code to handle special cases d = b ** 2 - 4 * a * c disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) return root1, root2 if...
Hello! Working with python This program asks user math questions and keeps track of answers... Allow...
Hello! Working with python This program asks user math questions and keeps track of answers... Allow the user to decide whether or not to keep playing after each math challenge. Ensure the user’s answer to each math problem is greater than or equal to zero. Keep track of how many math problems have been asked and how many have been answered correctly. When finished, inform the user how they did by displaying the total number of math problems, the number...
Develop a python program to create a quiz with limited time and attempts!!! Add comments and...
Develop a python program to create a quiz with limited time and attempts!!! Add comments and screenshot of running the program quiz could be of anything like , what's the sum of 2&2. There should be number of attempts(limited) suppose if the answer is wrong.
Develop a program using python to demonstrate data exchange using USB protocol.
Develop a program using python to demonstrate data exchange using USB protocol.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT