Simon says – Time to play!

the scratch version of simple simon from MagPi magazine

the original Scratch project, courtesy of MagPi

Well, we’re back at school now and settling in.  I’m looking forward to the first few computing classes next week, but I took time out this weekend to have a play on Scratch and BYOB.  I started off with a project from the latest MagPi magazine, on building a Simple Simon game in Scratch.

The game itself was straightforward, following the code given, although I was reminded in the process exactly what the broadcast and wait block does (broadcasts a message then suspends activity on that thread until the receiving thread has finished). That might well come in handy when I sort out the animations for my virtual pet, as I’d been concerned that other scripts might interrupt any animation that’s run.

However, when I played the game, I found one thing that didn’t feel right – it generates a four tone/light sequence, asks the player to repeat it, then generates a completely new five-tone sequence, which quickly makes it very difficult to play as the difficulty increases.  I seem to remember that the original version of the game would add one to the sequence each time, rather than changing it to a new sequence, so I decided to produce my own version and move it up to BYOB in the process.

The game loaded fine from Scratch, although there were one or two issues with the length of list, which apparently is handled slightly differently between the two programs.  However, I was soon picking the code apart and working on the alterations I wanted.

the block I built to cycle through a list and broadcast each item

the block cycles through a list, broadcasting each item in turn

My first problem was that the original game would generate each tone, broadcast it and then add it to the list.  If I was going to add a number to the existing list, I would need to find a way to cycle through all the objects in the list, broadcasting them one by one.  This seemed an ideal candidate for a self-built block.

Looking around the help system for BYOB and finding words like predicates thrown around merrily made me realise that despite appearances this definitely is not just for kids – while kids can quickly get up and running doing something with Scratch, it’s capable of some pretty powerful stuff, even more so in the BYOB version, although the more high-powered you go the more fiddly it gets to produce the blocks needed, with blocks within blocks within blocks.

Simple Simon game, BYOB version

Simple Simon BYOB version

I had to modify the flow of the main program in order to set up a 4 tone sequence, broadcast it, wait for response, then check it.  If the response is correct it adds to the score, generates and adds a number to the sequence then rebroadcasts, while if the response is wrong it takes a life away and replays the sequence as it is.

I definitely needed paper to scribble my thoughts on to work out the logic of the program, but it went together fairly well.  You know when a game is playable, when you have problems forcing yourself to test it rather than just playing!

The new version is more playable than the original, it makes a little use of the extra facilities of BYOB and I learnt a lot about the use of lists in Scratch/BYOB in the process.

The game currently keeps score during the game but is reset on restarting – one improvement would be to add in a high score variable, to keep track of the highest current run. I could also start the score at 4 instead of 0, so that it reflects the number of notes in the sequence.  An alternative would be to start with a one-note sequence, but that might make the game too slow to get started.



Raspberry Pi time!

Although I have had the pi out and working once before, it’s been a while and there’s a new distribution out for the software, so it was like starting all over again: the first thing I needed to do was to download and unzip the new distribution (Raspbian wheezy) from the pi website.  This needs to be copied onto an SD card before you start.  You have to use a disk imager to set up the SD card, it can’t just be copied over, but I’d already downloaded a free disk imager ready.

pi with case

pi with case

The operating system for pi is a linux distribution, with a graphical interface very like Windows available. It also comes preloaded with several pieces of software such as Python and Scratch, making it very fast to get up and working for programming purposes.  It took about 20 minutes altogether to download the software and copy it onto the SD card ready for use, and then I could start plugging things in.

The pi comes with two USB sockets which are usually taken up with keyboard and mouse, and as the operating system is installed onto an SD card which needs recreating for a new setup, this time I was also trying out a powered USB hub, so that I can save any work I do onto a separate memory stick rather than on the SD card.  The Pi itself isn’t powerful enough to run a hub, so it has to be one with its own power supply.

I hit a major problem when connecting the screen – as I explained in an earlier post, I need to use an adapter to connect my screen to the pi, and it had a rather troublesome connection, but eventually we managed to get it working.  So I had the pi up and running, with powered hub running keyboard, mouse and memory stick, and with a cable draped across the room to the router to give an internet connection as well.

I was disappointed to note that this new distribution seems to have a lot less than the previous one in the way of preloaded software, but the essentials are there – web browser, python 2 (with pygame) and python 3 (without pygame), plus Scratch.  Squeeze is also listed, but didn’t seem to load up.

There is also a folder of python games, taken from the book Invent With Python, which I copied onto the memory stick to bring back to my main machine and look at.

The browser seemed to work with no problems at all, and it was as easy as plugging in the cable and typing in a web address to get online with the Midori browser, so that was the basics up and running, although I couldn’t see how to access the memory stick directly from applications such as Scratch – my husband said something about mounting the drive, but I felt copying over is enough for now, until I get to the point of using the pi properly and having files worth saving directly onto the external drive.

I feel now that maybe I’ve reached the point where I need to start looking carefully for instructions, either via the MagPi magazine or some of these books that have sprung up about the pi, in order to take it any further.  Scratch and Python are fine with no issues for me, but the operating system is a little unfamiliar for anything outside the very basic and I’m not confident enough to go poking around, downloading stuff and installing it without advice.

I do believe the pi is a wonderful gadget, but as yet I don’t think I’ve identified its full purpose – as a really cheap machine available to encourage kids to play with programming, it’s great, but apart from its price it doesn’t offer that much different from a desktop machine. I understand you can use it for input and output devices, rather like the arduino, but that again is something that would need research and setting up, although it does seem to me that one major advantage for the pi apart from price is the physical size of it and that seems to be begging to be embedded in some sort of system.

I think it’s time to go off and do some research into what people are using the pi for, and what it’s capable of!

PS the case is great for protecting the pi as it sits on  my desk – I found it on my husband’s desk (around his pi in fact! shh!)

Virtual pet version 2

Time I returned to my virtual pet!  While I have written a detailed specification for the project, I decided to put in an intermediate stage when creating, so in this version there is no day or night, and the algorithms for the change in the variables aren’t completely worked out yet.  I do now have three variables for the pet: health, happiness and hunger.  Each has its own way of interacting with it: feeding, medicine and a ball to play with.  The player has to keep hunger down and happiness and health up in order to have the pet survive.  Health and happiness link to each other – an unhappy pet loses health faster, and vice versa.

virtual pet code version 2

code for version 2

I worked in Scratch originally for version 2, then when I could see repeated code I used BYOB features to pull out that repeated code and make it into a new block, complete with a passed in parameter.  This avoided the repetition as each requirement for death meant broadcasting a message explaining the reason, making the pet disappear and then stopping the script.

I found it straightforward to create my new block, including passing in a message to say why the pet died, and I also like the way that BYOB will change the colour of nested blocks, making it easier to see how they are put together.

Adding a timer to the game made it a little more interesting, as now it will record the length of time the previous pet lasted, but I still need to do a lot of work on the graphics, in order to have the pet show visually what his problems are.  Once I’ve done that, it may be possible to remove all displayed variables from on screen, to make the player look carefully at the sprite rather than just checking the numbers.

die block, including a passed in parameter

custom made “die” block

While the code for the project is becoming more complicated, it is still fairly straightforward, with one script per sprite.  Breaking into more than one script could lead to complications as different scripts running at the same time could interfere with each other, so I’m trying to be careful – for example I could have scripts to run animations for different interactions, but it might be possible to run two or more at the same time, with unintended results.

The project is coming along nicely, so now I need to reproduce this version in App Inventor. I also need to look back at the specification I wrote to see how it fits in with what I’ve done so far and then move on to develop it further, including day/night settings.

I’m still not happy with the gameplay and amount of interaction compared to feedback.  It’s a playable game, but without enough real challenge or interest yet to keep a player interested.  Thinking back to the original tamagotchi, that would beep for attention, and there were mini-games to play.  It was also a much longer-lived game, lasting for days and even weeks.  That’s not possible in Scratch, as it has no file-saving capabilities, but it would be possible in an android app, which is more likely to be the end format of this project.

It would also be possible in a Python project, which is something else I might try at some stage – that would make it usable on a PC, rather than on a mobile device.

Before I do much more with coding, though, I need to work on developing graphics and sound, as a game is so much more than just programming in the behaviours.


Python and Scratch – GCSE syllabus part 1

My intention in this post is to take a look at both Python and Scratch, checking them against the OCR GCSE Computing syllabus.  This should then act as a reference when introducing the topics in Scratch and then moving each into the realm of Python.

Programming constructs: sequence, conditionals and iteration plus algorithm understanding: IF and CASE statements, FOR, WHILE and REPEAT loops

control loop blocks in Scratch - repeat x times, repeat until, forever etc

control loop blocks in Scratch

In Scratch: most of these blocks are clear to use.  I’ve included the STOP SCRIPT block in here as it seems to be the equivalent of the BREAK statement, stopping execution of the code block.

Each of these blocks is C shaped, making it straightforward to see what code needs to be executed within the loop.  The student still needs to keep a careful eye on them, however – a series of IF statements can cause confusion, as there is a tendency not to notice whether they are nested or stacked.

The IF/ELSE block provides another useful structure, but this needs to be used carefully as again confusion can be caused if nesting multiple IFs.

code for control loops in python

Python control loops

In Python each piece of code needs to be typed, and the block is defined by very careful use of indenting.

The IF/ELIF/ELSE in Python provides a neater way to produce a series of IF statements, and serves in place of the SWITCH CASE statements of other languages and in the pseudocode used for algorithm description, where the CASE statement is a list of options, and the instructions for each option, although in CASE the choice is usually made on a variable value rather than a logical test , if I remember correctly (SWITCH variable CASE “y” do this, CASE “z” do that, CASE “n” do something else).  In Scratch, this would have to be done with a series of IF/ELSE IF/ELSE statements and tests, where as usual they would have to be placed very carefully.

The important thing to notice in Python layout is that there are no brackets around the logical tests and no formal line ending such as the semicolon in Java, but the start of the block is shown by a colon :

The editor should then indent the start of the next line automatically.  Each line that is indented forms part of the loop, and the non-indented code (or code back to the next level of indenting) will not be executed until the loop is completed.  You do usually need to delete the whitespace yourself to end the code block (one exception to this is the block to define a function – a RETURN line will automatically end the block and reduce the indentation).

While it is not essential to use whitespace this way in other languages, following this sort of layout carefully does lead to far more understandable code, and so it is a very good habit to get into for whichever language you intend to move onto.  Many editors provide support in laying out code neatly, and it may be possible, depending on the editor, to collapse sections of code for easier viewing.

The colour coding of the editor helps in forming good code as well: the secret to maintaining the colour coding after saving the file with the IDLE is to save it with the extension .py – thanks to the reader who reminded me of that one.  While the IDLE will save and recognise the file as Python, it doesn’t actually save it automatically with the right extension!

Notepad++ is another editor which will quite happily save and colour code Python files, incidentally, and will also cope with other languages, such as Java and HTML – again, the careful use of whitespace in these languages leads to better understanding of the code.

python for loop examples

Python FOR loop examples

FOR loops become very interesting in Python, because they provide the opportunity to do more than cycle through a series of numbers.  You specify a range to step through, and the loop will run for each step within the range, but the range may be a number as in a standard for loop (Scratch’s equivalent would be the repeat loop) or it may be items in a list, for example.

In this example code, the results produce the numbers 0-9 (range starts from 0 if not specified, and stops at the value before the end of the range), the numbers 1-9 and then the individual letters in the string “Hello World”.

In Scratch, the equivalent block would be REPEAT XXX, where XXX is the number of times you want the loop carried out.

Python also proves more powerful than Scratch as well because the value of the number of the loop can be used in the body of the program instead of creating another variable, as in these examples where I print out the number of the current step.

The WHILE loop in Python is the equivalent of the REPEAT UNTIL block in Scratch, although the WHILE loop will continue as long as the test is true, while the REPEAT UNTIL will continue until the test is false.  The FOREVER IF loop in Scratch I am not so sure about, as it appears a little confusing – it is really a FOREVER loop with an IF statement inside it, rather than a WHILE block which will finish as soon as the test condition is false.

Scratch logic blocks - greater than less than, AND, OR, NOT etc

Scratch logic blocks

So that’s a look at the basic looping and decision making structures in Python and Scratch.  As to the contents of the conditionals, these both follow the standard content:

In Python equal to becomes == the double equals sign, as a single equals = is used for assignment – when I forgot this, the editor seemed to pick it up and flag it as an error, which is useful.

Also in Python, True and False both start with a capital letter and NOT becomes !, as in x!=4 (x is not equal to 4).  In both languages, conditional statements can be nested as necessary.

Still to look at: data types, input/output, file handling systems, basic string manipulation, one dimensional arrays.variables, operators and assignments.

Binary display in Scratch

digit sprite

digit sprite

Python was a straightforward input/process/output project, but in Scratch displaying binary numbers can be much more visual.  I found it fairly easy to create once I’d got the basic principles: I used 9 sprites altogether, one for each of the 8 digits and a button which handled most of the actual code.

Each digit sprite has two costumes, one showing 0 and one showing 1.  In fact they have a third, which is the number they represent, but I chose not to continue with the option of displaying that as it would have made the project more complicated and I wanted the first version to be as simple as possible; instead I displayed the value of each digit below it on the background.  Each of these digit sprites responds to three instructions: when Green flag clicked switch to costume zero, when I receive reset switch to costume zero and when I receive [name of digit] on switch to costume one.

button sprite code

button sprite code

The button sprite resets all digits to zero, asks for the number to display, uses a variable to store the answer, then runs through the algorithm to turn the right digits on, broadcasting a message to each digit that needs to be turned on.  The number that is to be displayed is shown at the top of the screen as well.

This project was fun to create, but more complicated than the python version as I had to work out how the sprites would work together to complete the project.  There is also the possibility of becoming distracted by sorting out fancy graphics rather than focusing on pure code, so while I would probably encourage students to play with a finished version and see how it works, I’m not sure I would give it to them as a project for them to create too early on in their learning. as the visual element can distract from the code learning.  On the other hand, it would work well as an extension activity to students who already have experience in Scratch and have learnt the project in a different form.

You can try my project out for yourself on the Scratch website, and download it to look at the code used.  I made this completely in Scratch rather than BYOB, as it did not seem to need any of the extra features.