# Clear global environment rm(list = ls()) # Set highscore = 0 before the quiz highscore <- 0 # User inputs: # max.number = maximum number for calculations (e.g. if max.number = 10, you will calculate with numbers from 1 to 10) # questions.number = number of questions per quiz QUIZ <- function(max.number, questions.number) { # Introduction print("=== Hello, welcome to the Math Quiz! ===", quote = F) cat("\n") # Set points to 0 before each quiz counter <- 0 # Produces multiple questions (based on questions.number) for (i in 1:questions.number) { # Chose random number for x and y x <- sample(1:max.number, 1) y <- sample(1:max.number, 1) # Chose either 1 for plus or 2 for minus randomly operator.chooser <- sample(1:2, 1) # Print the question, wait for user input and check if it is correct if (operator.chooser == 1) { print(c(x, "+", y), quote = F) answer <- readline(prompt = "Answer:") if (answer == x + y) { print("Correct") # + 1 point if answer was correct counter <- counter + 1 } else { print ("Wrong") } } # Same for substractions else { print(c(x, "-", y), quote = F) answer <- readline(prompt = "Answer:") if (answer == x - y) { print("Correct!", quote = F) counter <- counter + 1 } else { print ("Wrong!", quote = F) } } # Print the current number of points print(c("Points:", counter), quote = F) } # In the end: Print the final number of points cat("\n") print(c("Finished! Your final points: ", counter), quote = F) # Keep track of your highscore if(counter > highscore) { # Saves highscore outside of function, so it's valid for all runs of the function highscore <<- counter print(c("Congratulations, you beat the highscore! New highscore: ", highscore), quote = F) } else { print(c("The highscore is", highscore), quote = F) } }