Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
The file Best.txt holds one line: 120.
DECLARE NewScore : INTEGER
DECLARE OldScore : INTEGER
OPENFILE "Best.txt" FOR READ
READFILE "Best.txt", OldScore
CLOSEFILE "Best.txt"
INPUT NewScore
IF NewScore > OldScore
THEN
OPENFILE "Best.txt" FOR WRITE
WRITEFILE "Best.txt", NewScore
CLOSEFILE "Best.txt"
OUTPUT "New high score"
ELSE
OUTPUT "The best is still ", OldScore
ENDIFWhat is output, and what does Best.txt hold afterwards, when the input is 95? And when it is 140?
OPENFILE <name> FOR READ or FOR WRITE (WRITE makes a new file and loses the old data), then READFILE <name>, <variable> to read the next line, or WRITEFILE <name>, <value> to write one, then CLOSEFILE <name>. Files keep data after the program stops.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Input 95. 95 is not greater than 120, so the ELSE branch runs. The output is The best is still 120, and the file is not opened for writing, so it still holds 120.
Input 140. 140 is greater, so the file is opened FOR WRITE. That makes a new file, and 140 is written. The output is New high score, and the file holds 140.
Why a file. The best score must still be there the next time the game starts, after the program has stopped.
Log in to join the discussion.
Loading…