Thursday 17 September 2015

Program without code using Scratch

Program without code using Scratch

After overcoming some initial scepticism, Kevin Partner discovers that drag-and-drop programming isn’t just for kids

The graphical Scratch system (scratch.mit.edu) is a great introduction to programming. One of its strengths is that it teaches the principles of structure separately from any commands or syntax. Understanding how to divide code into large-scale blocks is a huge help when it comes to learning other languages: Google can show you how to put together a while loop in (for example) Python once you know that’s the structure you want to use. And with the release of Scratch version 2, which adds custom functions, cloning and extensions, it’s no longer just for kids.


Scratch is browser-based, so it works across Windows, Mac, Linux and Chrome OS. However, version 2 is based on Flash, which doesn’t work on the Raspberry Pi, so that platform is stuck with version 1.4.

Let’s look at how it works. As an example of a Scratch 2 application, I spent a few hours creating a “Speedy Maths Brain Exerciser” which you can find at pcpro.link/253scratch. Click the blue square icon to make it full-screen, then give it a go. Once you’ve finished the game (tweet your best score with me @kevpartner) and returned to the main URL, click the See Inside button to launch the Scratch Editor and follow along. I recommend you register with Scratch, as this allows you to copy public projects and make your own modifications using the Remix button.

Scratch Editor has four main sections: a menu bar at the top, a preview and editing window at the top left, the sprite library at the bottom left and the block editor on the right. Within the block editor, the block library is on the left, with categories such as Motion, Events and Sensing. You create programs by dragging blocks from the library to the area on the right-hand side.

If you’ve just loaded the game in the editor, you’ll see that the first sprite (the addition/multiplication button) is selected in the sprite pane, and three groups of blocks are shown on the right – these are the blocks attached to that sprite. A sprite is a graphical element containing one or more “costumes”, which you can think of as animation frames. My addition/multiplication button has two costumes – one that shows the addition button active and multiplication greyed out and the second showing the opposite. Click the Costumes tab at the top centre to see the images.

The blocks attached to the addition/multiplication button are triggered by an event. The first activates when it receives a message saying that the main menu is to be loaded, at which point it sets the buttons to their default state and shows them. The second hides the buttons when the game starts. The third toggles between the two graphics when the user clicks them, and sets the game type accordingly. What’s wonderful about Scratch is that you can understand all this simply by looking at the blocks – you don’t need any knowledge of programming syntax.

In a Scratch program, almost all the code is attached to sprites – the code for beginning the game, for example, is attached to the Go sprite rather than in a main script. This can make it hard to work out how someone else’s project works unless they’ve structured it very carefully or added comments. But it introduces the idea of compartmentalising code, which is invaluable if you want to go on to learn object-oriented programming.

In this case, the bulk of the code is contained in the sprite called “digit”. This is because most of it relates to the display of numbers and symbols: click this sprite and the right-hand panel will fill with groups of blocks. It looks complicated, but for now you only need to think about the group labelled “Main Loop” , which is the main sequence of the game.

The first block says “when I receive start game”. This is what’s called an event listener: the “start game” event is broadcast by the Go button when clicked. Below the event listener is a purple block called setupScreen. This is an example of a custom block – if you click More Blocks under the Scripts tab in the middle of the page, you’ll see the complete set of custom functions I’ve created for this sprite. By creating custom functions, you can group blocks so they make sense to you – I suspect you’ll immediately recognise the purpose of each of mine. You can also use them to create standard modules, which you can use in different sprites by copying them to the Backpack at the bottom of the Edit page.

Costume change


In our program, you’ll see a group of blocks directly below the main loop that defines what the setupScreen function does. It’s pretty simple - it changes the background graphic to the one used for the game and then switches the costume of the digit sprite to a blank one, making it invisible. The digit sprite can also be set to a numeral 0-9, along with a decimal point and mathematical operator symbols: you can see these by clicking the Costumes tab when digit is selected. (I’ve set it up this way because Scratch lacks a method of writing text directly onto the screen.)

Moving down the main loop, we reset Scratch’s built-in timer before setting the variable howManyCorrect to zero. You can view all the variables I’ve created for this project by clicking Data in the Scripts tab. Scratch version 2 added support for list variables (also known as arrays) which you can see beneath the standard variable blocks: two of the three lists I’ve defined set the upper and lower limits for addition and multiplication. To change the difficulty, simply click the tickbox next to the list’s name to open a floating panel containing its values, then click and type to change them.

We now arrive at a repeat until loop, which is one of the blocks in the Control section. Scratch has two main control structures: repeat and if-then. You can use one of the forms of repeat to make something happen until a specified condition is met: in this case, the following blocks cycle until the number of questions answered correctly equals the target number of questions. I’ve set this to 20, but you can change it by editing the howManyQuestions variable.

The repeat block triggers four custom blocks. Most of the work is done by assembleSum so let’s look at that. This custom block begins with an if-then-else structure that sets the lower and upper bounds of the calculation. To assemble structures like this, you begin by placing the if-then-else block, then go to Operators and drag the equals comparator onto if-then-else. Finally,drag your variables into place: no typing needed.

The block immediately following the if-then-else structure calls the generateDigits function, which uses the “pick random” block to choose a number in the range given. The custom block printDigits cycles through each digit of the number and sends that single digit to drawDigit. We’re able to use one sprite to show multi-digit numbers by creating a clone of the sprite for each digit, and setting the costume of that clone to the number needed. The costume change is accomplished in the whichCostume block: if the number fed in is 0-9, the block changes the costume to that digit. If it’s over 9 it must be a maths symbol, so the else part of the block looks up which to show by cross-referencing with the list variable costumes.

Moving back to the main loop, you’ll see that once assembleSum has completed, we call the custom block calculateAnswer, which works out the correct answer. It’s followed by an ask block, which pauses the program and waits for input. Once an answer has been entered, the evaluateAnswer block checks whether it was correct and, if so, increments the howManyCorrect variable. Once 20 questions have been answered correctly the repeat loop ends, the variable timeTaken is set to the value of the built-in timer and the feedback is shown – reusing the printDigits custom block to show how many seconds the player took.

Next steps


As it stands, this is a pretty basic game. It could easily be expanded with the addition of extra difficulty levels, or by including subtraction and division. For subtraction, you might want to ensure that the right-hand value in the calculation is smaller than or equal to the left: this can be achieved simply by swapping the left and right sides if necessary. For division, you’d probably want the answer always to be a whole number: the simplest way to achieve this is to multiply two numbers and use the product and one of the multipliers to create your division sum. You could also polish it by showing the current score throughout, improving the graphics, adding special effects or altering the scoring system – feel free to have a go, and please do share the results with me.

I was sceptical about the value of Scratch when I first encountered it; having spent time using it to create a complete project, I’ve revised my opinion. In my view it’s the best choice for children to start learning programming, and a good option for adults too. Its increasing sophistication makes it possible to create advanced projects – the most impressive I’ve seen is 2D Minecraft (pcpro.link/253scratch2) – and get a head start on learning more traditional languages such as Java or Python.