High scores
Save the scores from a guessing game in a file, so they are still there next time you play.
Start here: open pygwide. On the home page, choose Tutorials, then Python Toolkit, then Lesson 5: High scores.
This lesson takes about an hour. The extensions take about 30 minutes more.
What you will learn
- How to write to a file, and read it back.
- How to save lists and dictionaries in a file with
json. - How to cope with a file that isn't there yet, with
tryandexcept.
What you need from before
- Lists and
.append(), from Lesson 1. - Functions with
return, from Lesson 2. - Dictionaries, from Lesson 4.
- Guess the number, from Python Basics, Lesson 5.
Step 1: Write a file
Variables are forgotten when a program ends. A file is kept. Type this and run it:
with open("hello.txt", "w") as file:
file.write("Hello from my program!\n")
Look in the Files panel: there's a new file called hello.txt! Open
it to see what your program wrote. It's part of your project now, and goes
in your zip when you export.
open("hello.txt", "w") opens the file for writing. with closes the
file again when its indented lines are done. \n starts a new line.
Step 2: Read it back
Replace your code with this, which opens the file for reading:
with open("hello.txt") as file:
print(file.read())
Step 3: Save a list
A file holds text, but you want to save a list of scores. The json
module turns lists and dictionaries into text and back:
import json
scores = [{"name": "Sam", "guesses": 6}]
with open("scores.json", "w") as file:
json.dump(scores, file)
with open("scores.json") as file:
print(json.load(file))
Open scores.json in the Files panel. Does it look like your list?
Step 4: When there's no file yet
The very first time the game runs, there are no scores saved. Opening a
file that isn't there is an error. try lets you try something, and
except says what to do if that error happens.
Replace your code with two functions, one to load the scores and one to save them:
import json
SCORES_FILE = "scores.json"
def load_scores():
try:
with open(SCORES_FILE) as file:
return json.load(file)
except FileNotFoundError:
return []
def save_scores(scores):
with open(SCORES_FILE, "w") as file:
json.dump(scores, file)
If there's no file, load_scores() gives back an empty list.
Step 5: The game
Add import random at the top, then add the guessing game as a function
that returns how many guesses it took:
def play():
secret = random.randint(1, 50)
guesses = 0
guess = 0
print("I am thinking of a number between 1 and 50.")
while guess != secret:
guess = int(input("Your guess: "))
guesses = guesses + 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print(f"You got it in {guesses} guesses!")
return guesses
Step 6: Keep the scores
Last of all, load the scores, play, add the new score, and save them all again:
scores = load_scores()
name = input("What is your name? ")
guesses = play()
scores.append({"name": name, "guesses": guesses})
save_scores(scores)
print()
print("High scores:")
for score in scores:
print(f"{score['name']}: {score['guesses']} guesses")
Inside an f-string that uses ", use ' for the keys, as in
score['name'].
Play a few times. Every score is kept!
Check your code
# Guess the number, with high scores kept in a file
import json
import random
SCORES_FILE = "scores.json"
def load_scores():
try:
with open(SCORES_FILE) as file:
return json.load(file)
except FileNotFoundError:
return []
def save_scores(scores):
with open(SCORES_FILE, "w") as file:
json.dump(scores, file)
def play():
secret = random.randint(1, 50)
guesses = 0
guess = 0
print("I am thinking of a number between 1 and 50.")
while guess != secret:
guess = int(input("Your guess: "))
guesses = guesses + 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print(f"You got it in {guesses} guesses!")
return guesses
scores = load_scores()
name = input("What is your name? ")
guesses = play()
scores.append({"name": name, "guesses": guesses})
save_scores(scores)
print()
print("High scores:")
for score in scores:
print(f"{score['name']}: {score['guesses']} guesses")
Extensions
The top five
Sort the scores so the fewest guesses come first, and keep only the best five.
.sort(key=by_guesses) sorts a list using a function you write, which
returns what to sort by. scores[:5] gives the first five things in a
list.
One way to do it
# Guess the number, keeping the top five scores in order
import json
import random
SCORES_FILE = "scores.json"
def load_scores():
try:
with open(SCORES_FILE) as file:
return json.load(file)
except FileNotFoundError:
return []
def save_scores(scores):
with open(SCORES_FILE, "w") as file:
json.dump(scores, file)
def play():
secret = random.randint(1, 50)
guesses = 0
guess = 0
print("I am thinking of a number between 1 and 50.")
while guess != secret:
guess = int(input("Your guess: "))
guesses = guesses + 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print(f"You got it in {guesses} guesses!")
return guesses
def by_guesses(score):
return score["guesses"]
scores = load_scores()
name = input("What is your name? ")
guesses = play()
scores.append({"name": name, "guesses": guesses})
scores.sort(key=by_guesses)
scores = scores[:5]
save_scores(scores)
print()
print("Top five:")
place = 1
for score in scores:
print(f"{place}. {score['name']}: {score['guesses']} guesses")
place = place + 1
A broken scores file
Open scores.json in pygwide, delete the last ], and run your game
again. It stops with a JSONDecodeError, because the file is no longer
JSON that Python can read.
A try can have more than one except. Add a second one to
load_scores(), for json.JSONDecodeError, that tells the player the file
was broken and starts a new table. Your game will then cope with a broken
file, though the old scores in it are lost.
One way to do it
# Guess the number, with high scores kept in a file
import json
import random
SCORES_FILE = "scores.json"
def load_scores():
try:
with open(SCORES_FILE) as file:
return json.load(file)
except FileNotFoundError:
return []
except json.JSONDecodeError:
print("Your scores file was broken, so I have started a new one.")
return []
def save_scores(scores):
with open(SCORES_FILE, "w") as file:
json.dump(scores, file)
def play():
secret = random.randint(1, 50)
guesses = 0
guess = 0
print("I am thinking of a number between 1 and 50.")
while guess != secret:
guess = int(input("Your guess: "))
guesses = guesses + 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print(f"You got it in {guesses} guesses!")
return guesses
scores = load_scores()
name = input("What is your name? ")
guesses = play()
scores.append({"name": name, "guesses": guesses})
save_scores(scores)
print()
print("High scores:")
for score in scores:
print(f"{score['name']}: {score['guesses']} guesses")
A diary
Write a diary program. Each time it runs, it shows every entry so far, then asks "What happened today?" and saves your answer with the others.
Extra bits
Did you know?
JSON stands for JavaScript Object Notation. Lots of programs and websites use it to save and send information, because almost every programming language can read it.
Export your project
pygwide keeps your work in this web browser, but club computers can forget it. Press ⇩ Export to save your project as a zip file. Keep it somewhere safe, such as a USB stick or your school drive. Your scores file goes in the zip too.
Next time, choose ⇪ Import a project on the home page to carry on with it.