Sign InNuggetsCoursesCodePadCheatsheet

Saving Scores in Shooting Game

You may want to use a file to record your score record. First, create a constant called SCORE_FILE = "score.txt" to represent the score file name. Then create a new boolean variable score_saved to indicate if you have saved your score. Because you only want to save the score once. When the game is over, open the score record file and add the new score. Finally, display the high record along with your current score.

def find_high_score(scores): hs = 0 for s in scores: score = int(s[:-1]) if score > hs: hs = score return hs
if not score_saved: # Load score file and update score record with open(os.path.join(dir, SCORE_FILE), "a+") as score_file: score_file.write(str(score) + "\n") with open(os.path.join(dir, SCORE_FILE), "r") as score_file: score_record = score_file.readlines() high_score = find_high_score(score_record) score_saved = True display_text(screen, "Record High: " + str(high_score) + " points", 30, WHITE, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
© CS Wonders·Home·About·Contact·Classes·Gallery·Glossary·Fun Facts