Saving your game
A game remembers things between one time it’s played and the next: the high score, how far you got, which keys you like. It keeps them in files, in the game’s own folder.
Crash-tan’s Tip: Here in the book, a game’s files live in the page, and they’re gone when you reload it. In a real game they’re kept: on a PC in the game’s folder, in a browser in its storage, on a phone in the app’s.
A file of text
SAVETEXT saves some text as a file, in place of whatever was there, and
loadtext reads it back. fileexists says whether there’s a file to read.
SCREEN 320, 240
IF fileexists("best.txt")
PRINT "best so far:", loadtext("best.txt")
ELSE
PRINT "no best yet"
END IF
SAVETEXT "best.txt", "1200"
PRINT "best so far:", loadtext("best.txt")
no best yet
best so far: 1200
Now press Run again: this time there’s a best.txt from the run before,
so there’s a best to read straight away.
Saving everything at once
A game’s state is usually more than one number. Put it in a map, and
serialize turns the whole thing into text (JSON, which other programs can
read too), and deserialize turns it back.
SCREEN 320, 240
player = {name: "Ada", level: 3, items: ["key", "lamp"]}
SAVETEXT "save.json", serialize(player)
back = deserialize(loadtext("save.json"))
PRINT back.name, "is on level", back.level, "with", back.items
Ada is on level 3 with [key, lamp]
A line at a time
For a file that grows, like a log or a list of scores, open it and write
lines into it. OPEN gives you the file: !! output starts it empty,
!! append adds to the end, and without either it’s opened to read. WRITE
writes one line, and CLOSE finishes, which is when it’s saved.
SCREEN 320, 240
scores = OPEN("scores.txt") !! output
WRITE scores, "Ada", 1200
WRITE scores, "Bob", 900
CLOSE scores
scores = OPEN("scores.txt") !! append
WRITE scores, "Cy", 1500
CLOSE scores
scores = OPEN("scores.txt")
WHILE NOT eof(scores)
PRINT READLINE(scores)
WEND
CLOSE scores
Ada 1200
Bob 900
Cy 1500
From 1.x: A file is a value now, so there’s no
#1to keep track of. Keep it in a variable like anything else.