Wednesday, May 31, 2017

Byte: Raspberry Pi - Using Variables & Loops student workbook (a.k.a. FLAPPY BAT!)



Student Workbook: Using Variables and Loops

In this lesson we are going to use Scratch to introduce how to use data variables and code loops to create more sophisticated, interactive computer programmes. To do this, we’re going to make a videogame called Flappy Bat. Create a new Scratch project.

Start > Programming > Scratch
File > Save As
New Filename: Flappy Bat [yourname][date]

Flappy Bat is a heroic tale of a bat trying to escape from a dark and menacing forest, while he is being chased by horrid, vampire bat fiends. We will start making the game by finding a suitable background for our Stage. Select the Stage in the objects pane and click the Backgrounds tab.

New background: Import
Nature > forest > OK

That’s an appropriately spooky forest, so delete background1 from the list on the Backgrounds tab by click the cross icon button. We won’t be needing that anymore.

Since we’re creating a game called Flappy Bat and not Flappy Cat, Scratch the Cat has to go. Select Sprite1 in the objects pane and click the Costumes tab. You can see here that Scratch has two costumes to animate his walk. While we don’t want these specific costumes, we do want a sprite that has at least two costumes to properly animate our player-controlled bat. Otherwise our bat won’t flap, which would be no good at all, since this game is Flappy Bat. Fortunately, there are two costumes that suit our needs, and we can use them to replace costume1 and costume2.

New costume: Import
Animals > bat1-a > OK
New costume: Import
Animals > bat1-b > OK

Once the bat costumes have been imported, delete costume1 and costume2 from the list. Sprite1 is now a bat! And the two costumes we’ve imported will allow him to flap when we animate him. Sprite1 isn’t a terribly inspiring name, though. Our Flappy Bat is a HERO! He needs a heroic name, like Derek. Can you honestly think of a more heroic name for a bat trying to escape from lethal bat fiends in a creepy forest?? Rename Sprite1 using the text field at the top of the coding pane.
Derek may be very batty and he may be exceedingly flappy, but if you look at the preview pane, you’ll notice one rather large problem with him. He’s HUMONGOUS. Derek frankly needs to go on a diet. Slim him down by right-clicking his sprite in the preview pane and selecting resize this sprite on the pop-up menu. Click and drag the arrow to resize Derek until he’s about the size of your index finger when you touch the screen.

Derek, our hero, unfortunately has enemies. Pursuing him through the forest will be four deadly vampire bat fiends. Add them to your project and save your progress.

New sprite: (Import Sprite from File)
Animals > bat2-a > OK
New sprite: (Import Sprite from File)
Animals > bat2-a > OK
New sprite: (Import Sprite from File)
Animals > bat2-a > OK
New sprite: (Import Sprite from File)
Animals > bat2-a > OK
File > Save

Pro-Tip: It’s a sensible idea to save your project every ten minutes or so – it would be a pain to have an unexpected power cut and lose your work!

You should now have four dark, fiendish bats menacing Derek in the preview and objects panes on the right of the screen. To make sure that these bats are also flappy (the game’s called Flappy Bat, it can’t have bats in it that aren’t flappy… we’re clear on that, right?), we’ll need to give them a second costume to animate their movement. We should also give these bat fiends terrifying names, like Geoffrey, George, Zippy and Bungle. Makes your blood run cold, doesn’t it? Brrr. These names will help us to give each bat their own characteristics and properties, and keep track of them more easily. Rename the Bat Fiends and add their second costumes to make them flap!

Geoffrey
New costume: Import
Animals > bat2-b > OK
George
New costume: Import
Animals > bat2-b > OK
Zippy
New costume: Import
Animals > bat2-b > OK
Bungle
New costume: Import
Animals > bat2-b > OK

Use the mouse to drag the four bat fiends into random starting positions on the preview pane, and then use the same right-click à resize this sprite method we used on Derek earlier to slim down the four bat fiends. Depending upon how difficult you want to make the game, you can make the bat fiends about the same size as Derek, or make them larger if you want to increase the difficulty.

We’re now ready to start coding the actual game itself. A good place to start is with scripts for the dastardly bat fiends, for two good reasons. Firstly, their behaviour is automated and practically identical, so once we’ve written the script for one of the bat fiends, we can simply duplicate it to the other sprites. Secondly, as the bat fiends’ movement is randomised, it gives us a good opportunity to get to grips with how to use random functions and loop blocks, before we code Derek’s rather more sophisticated script later.

Geoffrey, curse his rotten, putrid soul, is the leader of the foul pack of fetid fiends after Derek’s life essence, so we will start with him. Geoffrey will not rest, chasing Derek around the forest for eternity, unless our hero can somehow manage to escape. Select Geoffrey on the objects pane and click the Scripts pane to begin writing his main script.

when GreenFlag clicked                
forever

The forever block is U-shaped, with an up arrow at the bottom, indicating that this is a loop. Any code dragged and dropped inside the U-shape will run in an infinite loop until a condition elsewhere in the project is reached that globally stops all the scripts. Let’s test that the loop works by making Geoffrey move. Add this code inside the forever block.

next costume                                     (now Geoffrey will flap every time the code goes around the loop)
move 10 steps                                  
if on edge, bounce                          (this stops him getting stuck on the edge of the screen)

Click on the green flag in the Scripts tab and watch Geoffrey go! Goodness me, that looks tiring! Give Geoffrey a bit of a rest between each flap by adding in a short delay at the bottom of the forever loop.

wait 0.1 secs

You can customise this wait value to increase or decrease the speed at which Geoffrey flies, but we’ll leave it at 0.1 for now, because there’s a better way of making Geoffrey’s movement around the screen less predictable and harder to avoid. This involves using Operators to generate to generate random numbers. Replace the 10 in the move 10 steps line using the pick random command from the Operators code category. The line needs to look like this:

move pick random 1 to 10 steps

Geoffrey will now fly faster and slower at random after every flap. It’s a definite improvement, but it’s still quite easy to avoid a bat flying straight and level. Add a turn command into your forever loop underneath the next costume line.

turn Clockwise 15 degrees

When you test the script this time, you should see that Geoffrey now starts flying in circles, and if you leave the script running, he’ll probably end up bouncing his way around the edge of the stage, before occasionally going back to flying in circles. We can fix this navigational problem and make his flight more realistic by using the pick random operator. Change the turn block to following.

turn Clockwise pick random -15 to 15 degrees

Much better! Far more fiendishly flappy and swoopy! Now that Geoffrey’s main script is complete, we can duplicate it (by right-clicking on the finished script) once each for George, Zippy and Bungle. Once you’ve dragged and dropped copies of the script onto the sprite icons for the other three bat fiends in the objects pane, we can customise each bat to make them behave slightly differently.

Make George lazy by tweaking the values in his forever loop to the following:

turn Clockwise pick random -15 to 15 degrees
move pick random 1 to 5 steps
wait 0.2 secs

Zippy, as his name implies, is fast, but he doesn’t really know what he’s doing, because he’s honestly a bit clueless… Poor guy!

turn Clockwise pick random -55 to 55 degrees
move pick random 6 to 5 steps
wait 0.04 secs

And dear old Bungle, he once flew head first into a tree, and it’s left him really rather confused about things. Not even he knows where he’s going to lurch next.

turn Clockwise pick random -40 to 40 degrees
move pick random -40 to 40 steps
wait 0.6 secs

Click the green flag above the preview pane to behold a malevolent maelstrom of fearsome, ferocious and fiendish flapping! Derek’s going to have his have his work cut out trying to escape from the deadly clutches of that lot! Before we can start on Derek’s script, we need to bind a key that we can use to reset and restart the game. Add the following script to Bungle’s Scripts pane.

when space key pressed
point in direction 90
go to x: 150 y: -15
stop all

Duplicate the new reset script and drag it into the objects pane for the other three bat fiends, changing their reset coordinates so that they don’t bunch up or overlap.

Geoffrey
go to x: 90 y: -140
George
go to x: 0 y: 100
Zippy
go to x: -120 y: -150

Derek will also need a reset script, so duplicate the script one final time and set our hero’s starting coordinates.

Derek
go to x: -220 y: 0

With the coding for the bat fiends now finished, this is now good point to create the two variables we need to track the player’s score and whether the game has ended. Select the Variables category in the coding pane.

Make a variable > score (For all sprites) > OK
Make a variable > gameover (For all sprites) > OK

We now have two global variables that can be referenced and modified by any of the sprites in the game. At the moment, we only need to use them with Derek, but other sprites could modify the values later in the extension challenges later.  Add the following two lines to the when space key pressed script to reset the global variables.

set score to 0
set gameover to 0

Next we need to make Derek respond to player commands. We can do this by adding four very simple scripts to accept inputs from the keyboard.

when down arrow key pressed
change y by -12
when up arrow key pressed
change y by 15
when left arrow key pressed
change x by -10
when right arrow key pressed
change x by 10

If you press the arrow keys now, you should find that Derek responds to your commands! He won’t flap yet, but we’ll fix that with our final script.

when GreenFlag clicked
set score to 0
set gameover to 0
forever

This sets up the core of Derek’s main script. From now on everything goes inside the forever block. Note that we need to reset the score and gameover variables to stop unscrupulous players from using the stop all button and the mouse to cheat their way to a high score by interrupting the code loop! Our first order of business within the forever loop is to make sure Derek is animated properly. After all, he is supposed to be the Flappy Bat the game is named for…

next costume
change score by 1
wait 0.05 secs

If you run the code now, Derek will flap his wings when he moves and the player’s score gets incremented by one every time the player avoids being touched by one of the bat fiends after the completion of a full run through the code loop. Before we add collision detection between Derek and the other sprites, we need to add a touch of realism to the game. A hero like Derek would never get stuck on the side of the screen and stay put when he’s being chased by mortal enemies, and he also needs to fly faster forwards than backwards, because a hero never retreats! Sadly though, Derek is still subject to the force of gravity, so we need to reflect this in the way that he moves. Add three more blocks to the bottom of our forever loop.

move 5 steps
change y by -3
if on edge, bounce

You can always tweak these values if you find later that the game is too hard. Our game is almost finished! The final stage is to use several if statements to add collision detection between Derek and the bat fiends, and check the gameover variable to see whether the game still needs to continue running. To avoid confusion, add each if statement at the bottom of the forever loop. Use the touching ? conditional check in the Sensing category to see if any of the bat fiends have caught Derek. If they have, it’s curtains for our hero!

if touching Geoffrey ?
                set gameover to 1
if touching George ?
                set gameover to 1
if touching Zippy ?
                set gameover to 1
if touching Bungle ?
                set gameover to 1

Lastly, we can use two final if statements and comparison Operators to check the values in our two global variables and tell the player using a say speech bubble from the Looks category if they have won or lost the game.

if gameover = 1
                say GAME OVER! Derek was killed by a bat fiend! for 5 seconds
                stop all
if score > 1000
                say CONGRATULATIONS! Derek escaped from the bat fiends! for 5 seconds
                stop all

It’s all up to you, now… Can Derek make a heroic escape, or will he meet a gruesome fate at the fangs of the terrible, vampiric bat fiends?!? Good luck, Flappy Bat-Hero. FLAP HARD. FLAP FAST!

What Next?

Congratulations! You’ve just made a devilishly addictive Scratch game! But how could you make it better? Here are some things that you could try…

·         Can you alter the game’s difficulty by changing the movement speeds of the player bat or the bat fiends?
·         Can you add a variable to the game to give the player a number of lives?
·         Can you add sounds whenever the player loses a life or wins the game?
·         Can you change the script so that the player gets an extra life when their score passes a certain value?
·         Can you change the script to alter the size of the bat fiends (or the player bat) as the player’s score increases?
·         Can you tell the player the name of the bat fiend which caught them?
·         Can you find a way of turning the player bat into a dragon, which can eat the bat fiends, if the player score goes over 1000? (Challenging!!)

Byte: Raspberry Pi - Animation in Scratch student workbook



Student Workbook: Animation in Scratch

In this lesson, we are going to use Scratch to introduce the basics of programming by creating an animation of the first scene of the Shakespeare play Macbeth. First, we need to create a new project in Scratch.

Start > Programming > Scratch

These menu commands will start a new session of the Scratch editor. Maximise the window and give your project a name:

File > Save As
New Filename: Macbeth [yourname][date]

Now that you have saved your project file, it’s time to get familiar with the Scratch interface. Underneath the menu bar are three columns, split into several panes. The left-most column allows you to choose code blocks for your scripts. These can be dragged and dropped into the scripting window (the large, central pane of the interface). The code blocks all have colours to help you find different categories of commands. Dark blue blocks control the motion of sprites, Purple blocks change the appearance of sprites and allow you to show the user text, Orange blocks allow you to start and stop scripts or insert loops, and so one. When we start writing our animation, the colour of the text will show you what kind of block it is and which category it belongs to. Finally, the two panes in the right-most colour are the preview area, which allows you to test the output of your code, and the object pane, which allows you to select the stage and any sprites used by the project.

Where to get started, then? No play would be complete without a suitable stage, so click on the Stage icon in the object pane. You should see the central scripting pane refresh to show that the Stage is the object in focus. Click the Backgrounds tab and you should see that background1 is the only image file in the list of backgrounds for the stage. Since plain white is a bit dull as a background for a play, let’s find something rather more colourful and interesting

New background: Import

This command button will open up a pop-up window: Import Background
You can select any image you like from one of the sub-directories, but the woods background is appropriately spooky.

Nature > woods > OK

Click on the cross icon button on the list beneath background1 to delete it, and the stage is set!


Act I Scene 1 of Macbeth features three witches, so we need two more sprites. Scratch the Cat is also not terribly mystic, so we’ll need to change the costume of Sprite1. Select Sprite1 on the object pane to refresh the scripting window, and click the Costumes tab.

New costume: Import

This will allow you to choose a new look for Sprite1 in the Import Costume window.

Fantasy > witch1 > OK

Click the cross icon buttons next to costume1 and costume2 to delete them.

Now we can add two new sprites to represent the other two witches. Since there is only one witch costume available, we’ll have to pick something different for our other two sprites, otherwise the scene’s dialogue might get a bit confusing. The central button between the preview area and the object  will allow us to select a premade sprite. It looks like a star with a file folder sitting on top.

New sprite: (Import Sprite from File)
Fantasy > fairy > OK
New sprite: (Import Sprite from File)
Fantasy > unicorn1 > OK

Hurrah! Our three ‘witches’ are on the stage! Now we need to tell them what do, and the drama can begin! Select Sprite1 in the object pane and the Scripts tab on the coding area.

Each sprite will need two scripts. One will reset the animation and the other will execute when the green flag is clicked, to play out the scene. At the moment, all the sprites are clustered together in the middle of the stage, so the reset script will have to move the sprites to the edge, so that they can make a grand entrance from Stage Left.

Control

In the left hand column, you should now see all the code blocks for the control functions and commands. Scratch is a visual programming language that allows users who are new to programming to build scripts like a LEGO kit, by slotting together functions one at a time. We’ll start by coding the reset script. Drag and drop the when space key pressed block into the coding area. Note that I’ve highlighted space in pink because this is a value that can be changed by the user – some user-configurable values can be selected by drop-down list, or be entered as free text. Whenever you may have to change a value in a code block, I’ll highlight it this way in the instructions. Now whenever the space key is pressed, Scratch will execute any of the functions or instructions attached to this code block.

Motion

The dark blue Motion functions allow you to move sprites around the stage. Set the starting position for Sprite1 by attaching the following blocks to the script.

go to x: -500 y: 10                             (x is the horizontal coordinate, y is the vertical coordinate)
point in direction 90                       (this resets the sprite to face to the right)

The reset script can be triggered at any time, so we need to add a final command from the Control category to stop any scripts that are running in the background, otherwise things might get horribly out of sync.

stop all

Notice that the bottom of the stop all block is flat. This means that no further commands or functions can be added to this script. We need a separate script to tell Sprite1 what to do when our scene starts.

when GreenFlag clicked

The green flag is used as the starting trigger for all of the main scripts for the three ‘witches’, and is used this way for the majority of Scratch projects. In our multi-sprite animation, it will be very important to pay attention to the time delays between lines of dialogue, otherwise the whole scene will become disjointed and not make sense. To allow our characters to speak, we will need to use the say function from the Looks category. Add the following code to your new script.

glide 2 secs to x: 150 y: -14                           (enter, Stage Left!)
say When shall we three meet again? In thunder, lightning or in rain? for 4 secs               (1st line)
wait 8 secs                          (pause to let the other two witches speak)
say Where the place? for 2 secs                 (2nd line)
wait 6 secs                          (pause to let the other two witches say their next lines)
say I come, Graymalkin. for 2 secs           (3rd line)
wait 1 secs                          (dramatic pause!)
say Paddock calls anon: Fair is foul, and foul is fair, Hover through the fog and filthy air. for 6 secs                                       (final line of scene, said by all)
turn Clockwise 45 degrees          (get ready to leave the stage)
wait 0.3 secs                      (short pause)
glide 2 secs to x: 1500 y: 500                        (flounce out, Stage Right!)

The scripts for the other two sprites are broadly similar in function, they just have different stage directions and their own lines of dialogue. They also have slightly different timings to fit their dialogue into the overall sequence of the scene. Select Sprite2 on the objects pane, click on the Scripts tab and add its reset and main scripts, starting with the reset script, as below:

when space key pressed                               (start of reset script)
go to x: -500 y: 100
point in direction 90
stop all                                                                 (end of reset script)

when GreenFlag clicked                                                 (start of main script)
glide 2 secs to x: -130 y: 111                         (enter, Stage Left!)
wait 4 secs                                                          (wait for first line)
say When the hurly-burly’s done, when the battle’s lost and won. for 4 secs        (1st line)
wait 6 secs                          (pause to let the other two witches say their next lines)
say Upon the Heath. for 2 secs (2nd line)
wait 7 secs                          (pause to let the other two witches say their next lines)
say Paddock calls anon: Fair is foul, and foul is fair, Hover through the fog and filthy air. for 6 secs                                       (final line of scene, said by all)
turn Clockwise -45 degrees         (get ready to leave the stage)
wait 0.3 secs                      (short pause)
glide 2 secs to x: -500 y: -200                       (flounce out, Stage Left!)

Finally, select Sprite3 on the objects pane, click on the Scripts tab and add its reset and main scripts, to complete our scene!

when space key pressed                               (start of reset script)
go to x: -500 y: -50
point in direction 90
stop all                                                                 (end of reset script)

when GreenFlag clicked                                                 (start of main script)
glide 2 secs to x: -150 y: -96                         (enter, Stage Left!)
wait 8 secs                                                          (wait for first line)
say That will be ere the set of sun. for 4 secs        (1st line)
wait 4 secs                          (pause to let the other two witches say their next lines)
say There to meet with Macbeth. for 2 secs         (2nd line)
wait 3 secs                          (pause to let the other two witches say their next lines)
say Paddock calls anon: Fair is foul, and foul is fair, Hover through the fog and filthy air. for 6 secs                                       (final line of scene, said by all)
turn Clockwise -180 degrees      (get ready to leave the stage)
wait 0.3 secs                      (short pause)
glide 2 secs to x: 500 y: 500                          (flounce out, Stage Right!)

Save your project and click on the icon on the far right of the task bar to enable the Full Screen viewing mode (the icon looks like a projection screen). Press the space key to prepare your actors for their big moment, and when you’re ready, break out the popcorn (are you even allowed to eat popcorn at the theatre?), click the green flag and sit back to enjoy your Shakespearean masterpiece!


Congratulations! You’ve just made a Scratch animation! But how could you make it better? Here are some things that you could try…

·         Can you add dramatic sound effects to your scene?
·         Can you make the scene more interactive by having each line of dialogue bound to a separate key, so that you can control the timing of the scene?
·         Can you make the witches creepier by having them change costume after they speak a line of dialogue?
·         Can you add randomly moving ghosts to the background of the scene?
·         Can you script a longer scene, such as Act IV Scene 1 or Act V Scene 4 from Macbeth (or another play) with more speaking parts?