Saving Scratch game states to cloud data

Page content

How do I allow users to save a game state in online Scratch?

One of our Code Club kids asked this question last week. So I worked out a simple way to do this. In order for this method to work, you will need to have been upgraded from a New Scratch member to a Scratcher. This will allow you to create up to 10 cloud variables, with each able to contain 10,240 digits.

During a game, we use variables to keep track of things like:

  • the player’s score
  • what level the player is up to
  • objects or trophies that the user might have grabbed during the game

There’s also some variables that are automatically set when another Scratcher plays your game, such as username. The idea would be as follows: when the game is run, the cloud data is loaded from the Scratch servers, and stored in a list. When the player hits a specific key during the game, the score, level, and other information at that point, is added to the list. Later, the list is written back to the cloud data variables, and so on.

This was done pretty quickly, and made it as simple as possible to demonstrate the idea. You can look up two more complex examples at the Scratch cloud data documentation page. It’s also possible grab various variables such as username from the Scratcher’s profile, or encode data stored. I’ve left these, and apply this to a full game, as an exercise for the reader. For this tutorial, I’ve used just two single-digit variables, but it’s not a huge leap to store multi-digit or alphabetic data fields as well.

Required functions

I’ve set up the following actions (functions):

  • intialize: set the pointers, counters, and cloud variables to empty values
  • load: load the data, from the cloud data variables, into a list
  • save: overwrite the cloud variables with data from our list
  • input: allow the user to enter 20 pairs of digits to be stored as cloud data (you could also input to the list, and then use the save action to write to cloud data)

For all except the input function, I’ve use a custom block that is set to run in turbo mode. This makes things a bit quicker. Then custom block is called when an assigned key is pressed.

turbo mode

This is the initalize code (the player presses i):

init

This is the load code (the player presses l):

load

This is the save code (the player presses s):

save

This is the input code (the player is prompted for single digits - this is only for the tutorial, since normally this would be generated by the game):

input 20 items of 2 digits each

Add these scripts and blocks to a single sprite and run it!