#!/usr/bin/env python3 # # file: maths-game2.py # # run on a Raspberry PI: # chmod u+x maths-game2.py # ./maths-game2.py import sys try: # print the current highscore data with open("highscore2.txt", "r") as f: print("The 10 highest scores previously were") highscore = f.read() print(highscore) except: # ups - highscore file doesn't exist, so we create a new empty file print("Creating a new highscore file (highscore2.txt)") with open('highscore2.txt', 'w') as f: pass name = '' while name == '': # we need a name for the highscore name = input("Your name (or q to quit the game):>> ") if name == 'q': sys.exit(0) resp = "y" while resp == str("y") or resp == str(""): # we use 2 arrays: 1 for the score and one for the name # this to arrays are related by the index # score[0] and names[0] address the first (highest score) entry # in the highscore scores = [] names = [] with open("highscore2.txt", 'r') as file: for line in file: line = line.strip("\n") line = line.split(" ") names.append(line[0]) scores.append(int(line[1])) score = 0 print("Welcome to the Maths Quiz") print("Can you answer three questions and score maximum points?") print("Question 1: What is the product of 2x2x2?") answer = int(input("Your answer :>> ")) if answer == 8: print("Correct") score = score + 1 print("Your score is ", score) else: print("Incorrect, the answer is 8") print("Your score is ", score) print("Question 2: What is the product of 6x7?") answer = int(input("Your answer :>> ")) if answer == 42: print("Correct") score = score + 1 print("Your score is ", score) else: print("Incorrect, the answer is 42") print("Your score is ", score) print("Question 3: What is the product of 17+4?") answer = int(input("Your answer :>> ")) if answer == 21: print("Correct") score = score + 1 print("Your score is ", score) else: print("Incorrect, the answer is 21") print("Your score is ", score) # this round of the game is finished # now we compare the current score with the # available highscore data position = 0 for compare_score in scores: if score <= compare_score: position = position + 1 scores.insert(position, score) names.insert(position, name) scores = scores[:10] names = names[:10] print("HIGHSCORES") with open("highscore2.txt", 'w') as file: for i in range(len(scores)): file.write(names[i] + " " + str(scores[i]) + "\n") print(names[i] + " " + str(scores[i])) print("\n") resp = input("New try ? [y/n]:>> ")