Showing posts with label Scratch programming projects. Show all posts
Showing posts with label Scratch programming projects. Show all posts

Monday, February 27, 2012

Project: Caesar Cipher

Hello and welcome to the first project of 2012 at Fun with Scratch! Ever wanted to send secret coded message to your friends? This project is a simple code machine that encrypts your message into a cipher text with a technique called the Caesar Cipher. You can send the encrypted text to your friend - via some means like e-mail or phone, etc - and with this same program your buddy can decrypt and read your secret message!



In the past I usually explain from start to end all the scripts in a project. If you have been following them all, I trust that by now you would be able to understand the use of broadcast and when I receive blocks to control scene transitions in this project.

What I want to focus on this time is the concept of Caesar Cipher, how we devise an algorithm for it, and how we translate this algorithm into Scratch scripts.

Let's begin.

The Caesar cipher

The idea is simple. Given a message, we change it into a code (or cipher) by replacing each letter in the message with another letter in the alphabet. The letter we use for replacement is determined by the shift.

A shift of 1 means that we replace the letters in our message with the first letter after it. So A is replaced with B, B with C, and so forth. At the end of the alphabet, we restart at the beginning. So, Z is replaced by A.

Here is another example. When the shift is 3, A is replaced with D, B with E, Y with B, Z with C, etc. The message "I LOVE APPLES" will be encrypted as "L ORYH DSSOHV".

Caesar cipher with shift of 3 e.g. B is replaced with E
(image from Wikipedia)

Decryption is the reverse of encryption. So given the cipher text "L ORYH DSSOHV" with a shift of 3, we would replace each letter in the cipher with the third letter before it in the alphabet, yielding "I LOVE APPLES".

Caesar cipher algorithm

First off, if you are new to the word "algorithm": it simply means a set of step-by-step instructions. A recipe is an example of an algorithm. A recipe specifies ingredients needed and contains step-by-step instructions to make something with the ingredients.

Now, when we are given a plain text like "I LOVE APPLES", what step-by-step instructions can we create to convert it into a Caesar cipher?

Here is one way we could do it.

Before we start any encryption we:
  • List the entire alphabet on paper, in order.
  • Ask someone to give us a message to encrypt.
  • Also ask that person to tell us the shift that they want to encrypt with.
So let's say the message is "HELLO", and the shift is 3. To help us remember, we will write them somewhere like so:

alphabets  : ABCDEFGHIJKLMNOPQRSTUVWZXYZ
shift      : 3
plainText  : HELLO
cipherText :


We leave cipherText blank for now. We will fill cipherText as we go along our algorithm.

This is how we can proceed to encrypt it:
  1. Point the left index finger at the first letter of plainText (which is "H").
  2. Point my right index finger at the first letter in the list of alphabets (which is "A").
  3. Compare the letter that the left index finger is pointing at, to the one the right index is pointing. If they are different, shift the right index to the next letter. Continue to do so until the letter the right index is pointing at is the same as the one on the left. Once that happens, move the right index 3 letters down (because the shift is 3). We would reach the cipher letter (in this case, once we reach "H", we move 3 letters down to reach "K", its cipher). So we write it down:

    cipherText: K

Now we redo Steps 1-3. However at step 1, move the left index to the next plainText letter (which is "E"). At Step 3, we stop only when the right index reaches "E", then move down 3 letters and to reach "H". That's the cipher for "E". So we write it down:

cipherText: KH

All we do is that we would repeat Steps 1-3, moving the left index to the next letter until all of plainText has been encrypted, resulting in:

cipherText: KHOOS


Caesar cipher encryption in Scratch

One of the nicest things with Scratch is that we can almost always translate our algorithm into Scratch blocks directly. We actually have six "ingredients" in our algorithm, and we will translate these into variables in Scratch:

"Ingredients":Scratch Variables
alphabets:alphabets
shift:shift
plainText:plainText
cipherText:cipherText
left index finger:idx
right index finger:aIdx

Let's look at the algorithm in Scratch script:

Full Caesar cipher script for encryption

This script is run when the sprite receives an "encryptCaesar" message. It does two things. First, set idx to 0,  which is like saying that we move the left index finger to the beginning of the plain text, not pointing at the first letter, but resting just to the left of it. Second,  set cipherText to blank, and that is akin to getting ourselves a blank sheet of paper to write our cipher on.

When we have done that, we are ready to repeat Steps 1-3 of the algorithm for the entire length of the plainText.

Repeat algorithm for all letters in the plain text

The two blocks below represent Steps 1 and 2:

Steps 1 and 2

Remember that idx is the Scratch representation of the left index finger. Changing it by 1 moves the left finger to the next letter. Since we first rest the index before the first letter, this change by 1 just moves it to point at the first letter.

Step 2 points the right index at the first letter of the alphabet, that is equivalent in Scratch to setting aIdx to 1. We ignore the encrypted? variable for now.

The next does Step 3, which compares the letters pointed at by the two indexes. If it is the same, we append the letter shift numbers down it to the cipherText. If not, we move on to compare the next letter in the alphabet.

Step 3

The encrypted? variable is there to tell us whether we have encrypted the current plainText letter (i.e. the pointed by the left index, or idx in Scratch). Once we find a match in the alphabet, we can set encrypted? to true, so that we needn't compare the rest of the letters in the alphabet and can move on to the next plainText letter.

If we have traversed down the entire alphabet, and encrypted? remains false, then we know that the character we are pointing at in the plainText is not a letter, but some symbol not in the alphabet. In this case, we simply use back the same symbol in cipherText. This is what the following block does:

When there is no match in the alphabet, simply append the plain text symbol to the cipher

Final message

This is definitely a tad more advanced than the projects we have had here before. You would at least need to know modular arithmetic, and reason out the range transition of the indexes. Post a comment here if you need help with it. If you are a Scratch teacher you may want to introduce these concepts to the student first before embarking on the project.

Wednesday, December 21, 2011

Project: Fruit Basket Mini Game

Recently, I posted a Scratch tutorial on summing or updating scores with sound effects, like in a game show. In today's project I will show how that is applied in a mini time-based game. In this game, players have one minute to catch as many fruits as they can. Each fruit earns the player points:

Cherry: 1 point
Lemon: 2 points
Pear: 5 points
Plum: 10 points
Pineapple: 20 points

After one minute, the game ends and the final score is decided based on the number and types of fruits caught. Play to experience it for yourself (the sound quality is horrendous in this online version - you may download and run on your computer for the music notes to play better):


We will program this game in four steps.

Step 1: Do staging and initialization

We have two backgrounds for the stage - one with the game title "Fruit Basket" and another without. This script basically displays the one with the title at the beginning of the program, and only switches to the next background when the player hits the spacebar. Since this game is timed, we also reset the timer before broadcasting a message to start the game.

Script to change stage background and initialize variables
All the orange blocks in this script do two things: first, they hide all the variables so that the watchers are hidden. We also set all the variables to zero.

We have six variables in this game. We use those named after the fruits to keep track of the number of fruits collected. We will see how to do this in Step 3. In Step 4, we will use the values in these variables to arrive at the final score, which we put in the totalScore variable.

Step 2: Control the basket


Script to control basket
When the basket receives the broadcasted message to start the game, it shows itself and for the next 60 seconds, keeps checking whether the left or right arrow keys are pressed. If the right arrow key is pressed it moves 8 steps to the right, and if it is the left arrow key it moves the same distance to the left.

Once the 60 seconds is up, it broadcasts "end" to signal that the game has ended. We will make use of this "end" message in Step 4.

Step 3: Program the falling fruits

We want the fruits to fall in differing speeds and stages. The more points a fruit is worth, the later it will appear in the game, and the faster it will fall. When the player successfully collects a fruit we will also play a note. The instrument that we use for each fruit will also be different.

The Cherry is the first fruit to appear, and it starts falling right immediately when it receives the 'start' signal:

Script for Cherry
The Cherry first sets its instrument to #13, which is the Marimba. Next, it shows the variable that counts the number of cherries the player collects (with the show variable cherry block), and appears on stage (with the show block).

Then, for the next 60 seconds, it repeatedly:
  1. Positions itself somewhere at the top of the stage, with the set x to_ and set y to_ blocks.
  2. Keep falling until either it touches the basket (I use touching color block here, but you could also use the touching sprite block), or if it has reached the bottom of the stage (when y position is less than -170), or if time is up.
  3. Checks if it touches the basket. If it has, then it adds to the count of cherries collected with the change cherry by 1 block. It also plays the 65th note of the Marimba for 0.01 beats.
When the minute is up, it disappears from stage with the hide block.

The script for Lemon is almost the same as Cherry's. Lemon appears only after 10 seconds into the game, so we insert a wait until (timer > 10) block to ensure this:

Script for Lemon has the wait until (timer > 10) block
All the fruits - Pear, Plum and Pineapple - have the same script as the lemon. They are different in terms of:
  • instrument used (observed in the set instrument to_ block)
  • time to appear (observed  in the wait until_ block)
  • falling speed (observed  in the change y by_ block)
  • the variable to update  (observed  in the change_by_ block)

Step 4: Display final score

Remember the "end" message that we broadcasted in Step 2? This is where we use it.

Scoring script adapted from the game show scoring template
The Score sprite detects that the minute is up and that the game has ended once it receives the broadcasted "end" message. To this, it shows its first costume, which says "Time's Up!". It waits two seconds, to be sure that the player reads that, and switches to the next costume, which says "Your total score is:"

It then proceeds to do a game show flavour of totaling up the scores using the Scratch script template from the game show scoring tutorial. Note that in this game, we increase totalScore by 1, 2, 5, 10 or 20 for each count of cherry, lemon, pear, plum and pineapple respectively.

Monday, December 19, 2011

Project: Malibu Beach Crab

What comes to your mind when you think of the beach? Sand castles, surfers, ice cream under the shades and maybe even a nice swim in cool clear seawater.

I think of crabs. Not the hordes of hermit crabs that flood some beaches, but tiny little crustaceans no bigger than the fingertip with soft translucent shells. They emerge from holes in sand washed and wet from the waves.

With Scratch, we need not be confined to reality. Let's take our imagination further. This is what we will create:


There seems to be a lot going on in this project but we'll soon see that the idea is really simple. Basically, the entire project breaks into four steps.

Step 1: Setting the stage

There are two stage backgrounds. The first background has a short introductory text to the game. What we want to display this from the beginning of the program until the user hits the 's' key to start the game. This is how the script looks like:

Script for the stage
It displays the first background, and switches to the second one on 's' key press. At this point, we also reset the points variable that we'll be using to keep score. Then we broadcast a "start" message. We will see in the following steps that we program all sprites to respond to the "start" message.

Step 2: Controlling the crab

In the Run, Scratch, Run! project, we have seen how to program movement controls on a sprite with the keyboard. We do the very same thing here:

Script to control the crab
The difference in this script is that we use the glide blocks to simulate jumping. Notice that we constrain the crab to the same x position when it glides. So the crab only moves vertically upwards to the y-coordinate of 100, and then back to -111. (You may find it interesting to compare this to the jumping script in the Run, Scratch, Run! project. The Three Ways to Program Falling Objects in Scratch tutorial briefly mentions the difference between using glide blocks and changing position coordinates in a loop.)

Step 3: Moving the bananas, suns and fruit platter

If you play the completed program above, you will see that the bananas and suns appear to fall rather haphazardly from the sky. Let's take a look at the scripts that we use to make the banana and sun sprites fall:

Script for a banana sprite
Script for a sun sprite
They are actually the same! The minute difference lies in the wait_secs block, where we pick a larger random number for the sun. So what's going on here? When the sprites receive the "start" message, they hide themselves - this clears the stage when we replay the program. Then, they repeatedly do the following sequence:
  1. Reset their own positions to somewhere at the top of the stage. We purposefully set the y-position 240, which is safely offstage since the stage covers up to 180 in the y-axis. We want them to fall anywhere from the top of the stage. This means that we will need to vary the starting x-coordinates. we do this by selecting a random number that is within the range of the stage. 
  2. Wait for a random number of seconds. We do this because we want the sprites to fall unpredictably. If we had specified a constant number, the player will be able to time the falls - that's no fun when playing a game!
  3. Show themselves and fall by gliding to the bottom of the stage.
Why do me make the sun sprites wait longer than the banana sprites? We do this because we want the bananas to fall more frequently than the suns. The game will be more challenging if the suns fall very often. See this for yourself - download the project and experiment with the script.

Next, we move the fruit platter. This is the most satisfying "food" for our crab. It does not fall from the sky, but moves horizontally across the stage. The crab will need to just to "eat" it. This is how we make the fruit platter move:

Script for the fruit platter
This script is also about the same as those for the banana and sun! It repeatedly does the same three main things: reset position, wait, and glide. This time however, the fruit platter resets its position to a fixed location at the top left of the stage. Also unlike the banana and sun, when the fruit platter glides it keeps the same height on stage while changing its x position to move from left to right.

Step 4: Keeping score

Here is a more exciting part of the program. We have created a variable, called points, to keep score. We want to change the value of points depending on what the crab has eaten. One eaten banana is a point, while a fruit platter gives 20 points. Getting touched by a falling sun however, loses 10 points. To do this, we will need to keep track of whether a banana, sun or fruit platter has come in contact with the crab. To each of these sprites, we insert these scripts respectively:

Script to detect whether a banana has touched the crab
Script to detect whether the fruit platter has touched the crab
Script to detect whether a sun has touched the crab  
All we are doing here is to broadcast a particular message depending on what has touched the crab. If it is a banana the message is "eaten!", if it is a fruit platter then "eatenFruits!", and a sun, "sunBurnt!". On touching the crab, we make the sprites disappear using the hide block.

What happens to the broadcasted messages "eaten!", "eatenFruits!" and "sunBurnt!"? They are received by the crab:

Script for crab behaviour
The crab does three things on receiving each of these messages. It updates points, plays a sound and says something. For example, when a fruit platter touches the crab, it broadcasts the "eatenFruits!" message. The crab immediately receives this message, updates points by 20 more, burps, and says "BURRRRRRP!!!"

There we have it. A game in Scratch in just four simple steps.

Project trivia

I first created this project in May 2010 while assisting a five-day Scratch course for students from Nanyang Girls High School. It was held at the School of Computing, National University of Singapore and was great joy to do. Back then, I went by the username chapati on Scratch. 

Tuesday, December 13, 2011

Project: Magic Wand

With Christmas so near, I sense magic in the air! Magic is exactly what we are going to program today - Okay, maybe that doesn't make it magical anymore…but anyways, this is what we will create:


I am not embedding the online version here because the wand does not behave as it should online. So, to see it in action you will need to download and run the project on your computer.

There are 16 sprites and 33 scripts in this project. Only five of them are unique - the rest are copies - and only four truly matter. Let's see what we have…

The wand

The wand is easy to code. Easy to create too. I drew it on the Scratch Paint Editor using two lines of different shades. Its script simply instructs it to follow the mouse pointer at all times:

Scripting wand to follow the mouse pointer

The stage

I put this script on the Stage, but it could really be on any sprite. All this script does is to broadcast a "click" message when it senses a mouse down event.

Broadcast 'click' when mouse down event occurs 

The magical round things

These are the stuff that emerge out of the wand tip. They each have a copy of the same script and their own variables.

A "magical round thing" (yes, I have no better name for it. Ideas, anyone?) has four variables:
  • outOfWand indicates whether the sprite has shot out of the wand and is moving on the stage. When outOfWand is 0, it means that the sprite is not on stage - you can think of this as the sprite being "inside the wand" and has not emerged yet. When outOfWand is 1, it means that the sprite has left the wand and is out on stage.
  • v is the y-coordinate change for the sprite.
  • dv controls the rate of fall for the sprite. You would easily understand what v and dv do if you have seen past tutorials and projects related to falling. (If you have not, you may want to take a look at some of these: Programming Falling Objects in Scratch, Three Ways to Program Falling Objects, Keep Afloat, and Run, Scratch Cat, Run!)
  • u is the x-coordinate change for the sprite. We want the sprite to fall some distance to the left or right of the wand. u is the change in x that will help do this.
We will soon see how these variables are used. Before that, we need to do some initialization:

Initialize outOfWand to zero when program starts
At the very start of the program the sprite stays "in the wand", so we set outOfWand to 0.

Setting values of variables when 'click' message is received
Then, when the sprite knows that the the mouse is clicked, it will proceed to set the other variables. However, it only does this when it is not out of the wand yet. We really don't want to mess with these variables if the sprite's already on stage. Note that it now sets outOfWand to 1, indicating that it is now ready to emerge. It then positions and shows itself at the wand tip with the go to Wand and show blocks.

The rest of the code in the repeat until (outOfWand = 0) block controls the behavior of the sprite after it has emerged:

Behaviour  having emerged from the wand
First, it changes its colour effect. Then it falls down and to the right or left depending on the random values that u and dv were set to.

It also checks whether it is touching the edge of the stage. If it is, then it hides itself and sets outOfWand to 0 to indicate that it has left the stage and - in a sense - has gone back in the wand. This means two things:
  1. The repeat until block terminates, since outOfWand is now 0.
  2. The next time the mouse is clicked, the if (outOfWand = 0) block will evaluate to true and it will continue the process of resetting its variables and emerge again.
We make 14 duplicates of this sprite and finally have…our magic wand! You may experiment by changing other effects like size and ghosting, or make more duplicates of the "magical round things". Have a magical time programming.

Monday, December 12, 2011

Project: Happy Calculator

Here we are again with another Scratch project! We are going to program a simple calculator. Scratch has built in operators that we can use and we will use the ready-made addition, subtraction, multiplication and division operators.

We will also program the power function in our calculator by doing appropriate numbers of multiplication - we will see how to do this later.

Right now, check out the Happy Calculator program below!


I call the yellow fellow "Happy". Happy asks three questions: first to enter a number, then he asks for an operator, followed again by a number. He will then do the math on both numbers.

For example, we might do this:

Happy: Enter first number
We type 5 (and press Enter, or click the tick icon)
Happy: Enter an operator
We type *
Happy: Enter second number
We type 6

Happy goes on to multiply 5 by 6, and shouts out the result, which is 30.

Here are the operators Happy knows about: +, -, *, / and ^
I am sure we are already familiar with the plus (+) and and minus (-) symbols.
At school, we write our multiplications with the x symbol e.g. 3 x 5 = 15
Here we will use * as the multiplication symbol. We will use / as the division symbol, and ^ as the power symbol. We will program Happy to understand these symbols.

More examples of math with our operator symbols:

2 to the power of 3 : 2 ^ 3 = 8
100 divided by 5 : 100 / 5 = 20
13 multiplied by 6 : 13 * 6 = 78

Alright, now we are ready to program our calculator! I suggest downloading the project and have a look at the full script.

Step 1: We need variables

We know that we are programming Happy to ask for input. When someone enters an input, we have to store it somewhere, or it just vanishes and our program will have no idea what the input was. To do this, we create variables. You could think of variables as boxes to keep things. We may store input in variables, or just any value we want. Here, we create five variables:
  • err that stores the sentence "Oops, I can't calculate this!" This is what Happy will say when something goes wrong.
  • num1 that stores the first input number.
  • num2 that stores the second input number.
  • op that stores the input operator.
  • ans that stores the final result of our calculation.

At the start, we set these variables to their initial values:

Setting variables to initial values

Step 2: Happy asks for input

Having set those variables, we program Happy to ask for user input:

Asking for and getting input
The script is pretty straightforward. We use the ask_and wait block and then we set a variable to the answer given by the user.

Notice that we use several broadcast blocks in our script. They are just there to signal the instructions sprite to appear and disappear. They are not the main focus of our calculation script, but you could always comment on this post if you need help with them.

Step 3: We do math!


Script for calculation
We have a chunk of code here as you can see. They are actually just a lot of nested if-else blocks. I prefer this to snapping many if blocks together, since the whole "else" part is immediately ignored once the "if" condition is met. Basically, what we are doing here is to check the user's input for the operator symbol.

Addition, subtraction and multiplication

When the operator is +, - or *, we do the necessary math with Scratch's operator blocks, and set the ans variable to the result of the operation.

Addition
Subtraction
Multiplication

Division

When the operator is /, we know we are doing division. However, we can only divde when divisor is not zero, so we add an extra check:

Division with a check for valid divisor
When the divisor is zero, we set the ans variable to "Anything divides zero is undefined!" This makes Happy a pretty smart talking calculator. If the divisor is anything but zero, we do division with Scratch's divide block.

Power

Scratch does not have an operator block for the power operation so we are going to work around this. As we know, the power operation simply means a string of multiplication on the base number e.g. 2^6 is 2 multiplied by itself 6 times or 2*2*2*2*2*2. 9^3 is 9 multiplied by itself 3 times, or 9*9*9. Anything to the power of zero is 1 e.g. 6^0 = 1, 541^0 = 1.

Repeated multiplication to do power arithmetic
So, what we do is to first set the ans variable to 1. The we multiply ans by num1, num2 number of times using the repeat block. For example, if num1 is 9 and num2 is 3, then we repeat 3 times the multiplication of ans to 9. At every loop of the repeat block we update ans to the latest multiplication result. Take a look at an example:

At the start, ans is 1
After loop 1 of repeat block ans is 1*9 = 9
After loop 2 of repeat block ans is 9*9 = 81
After loop 3 of repeat block ans is 81*9 = 729

Suppose if num2 is zero, then the repeat block repeats for zero times, meaning that no further multiplication is done at all, and so ans remains at 1.

Invalid operator

If after comparing against all our five operators we cannot find one that matches the input, then we set ans to err.

Error when there is an invalid input operator

Step 4: Happy reveals the answer

By the end of the script, all that Happy does is to say the the value of ans. If it isn't an err value, then switch Happy's costume so that it looks really happy to be getting an answer. If it is an err value, then Happy remains real serious and says "Oops, I can't calculate this!"

Happy saying the answer

Sunday, November 13, 2011

Project: Run, Scratch Cat, Run!

Hello! Hope you have had some fun with last week's project, also our very first project to have user interaction via the microphone. You may also have read the tutorial on programming falling objects. This week, we will explore interaction with the keyboard. We will see how to program a character to run and jump. The final program is below. Use the left and right arrow keys to control Scratch Cat. Hitting the spacebar will make it jump.


Once you have downloaded the project file you will notice that the script is short! There are really just two main behaviours we want to program and they are: Running and Jumping. Let's begin:

Step 1: Program Scratch Cat to run left and right

Let's start with a new program. We have the default Scratch Cat and a blank Stage. We paint a black strip on Stage with the Paint Editor. That's our floor.


Click the Scratch Cat sprite and put in these blocks of code:

Code to move Scratch Cat left and right with the arrow keys
The go to x.. and y.. block merely places Scratch Cat at coordinates (0, -80) at the very start. The more interesting bits lie in the forever loop block. What it says is "forever (or always) look out for the left and right arrow key presses". If the right arrow key is pressed, then "make Scratch Cat face right and move it Cat 10 steps forward". Similarly, if the left arrow key is pressed, then Scratch Cat should face left and move 10 steps to the left.

Run the script now and you should be able to move the cat left and right with the arrow keys, as if it is skating. That is not what we want. We want it to look like it is running. We will fix this later after we have programmed it to jump.

Currently, notice that Scratch Cat stops as soon as it reaches the left or right edge of the stage. We will add in a script to "roll up" the screen such that when Scratch cat reaches the right edge it continues to the left edge and vice versa:

Makes sure that Scratch Cats "rolls over" from edge to edge
Run the script, move Scratch Cat to an edge and watch the difference.

Now, on to the next step:

Step 2: Program Scratch Cat to Jump

Jumping essentially involves falling. Think about it. As soon as our feet leave the ground, we are already acted upon by gravity. The reason we are able to leave the ground is because the force we muster in our jump is greater than that of gravity. Nevertheless, due to gravity, our velocity decreases all the time as soon as we jump. Here is how we will translate this in Scratch: We add in the code for falling first. Refer to the tutorial on programming a falling object in Scratch for a better understanding of this script.

Blocks added into the script above to simulate fall
The blocks above says that if Scratch Cat is on the ground, we set its falling velocity to 0.5 to cancel out the work by gravity. this makes sure that it lands on the ground, and not through it. Now we slip in a couple of blocks to make it jump:

Blocks for jumping
With these blocks, when we hit the spacebar the cat jumps as its y position is changed by the jump velocity of 10.

The only thing missing now are the running legs. We will do this by alternating the costumes. Note that we only want Scratch to move its legs while running on the ground and not while its jumping in the air, so we slip in controls for this in the if y position < -80 block (i.e. if it is on the ground):

Blocks to change costumes, giving the impressing of running
And we are done. This is the final script for keyboard interaction, after adding in all the code that we have discussed:

Final script to make Scratch Cat run and jump with the keyboard
There you go! You have just programmed Scratch Cat to run and jump with keyboard controls. Congrats!
Note: if you have downloaded my project you will notice that I have used variables to store my values. If "variables" sound alien, you may go without them for now. We will have a tutorial about them soon.

Friday, November 4, 2011

Project: Keep Afloat

It has been almost a week already! Hope you have fiddled more with the project from last week and the week before. Our new project has only one sprite and a very short script. Yet it illustrates interesting ideas on simulating falling objects and using the audio input to control a sprite. We will need a microphone for this project.

This is what we will create:


Just a few simple steps:

Step 1: Setup stage, sprite and variables

The Stage is really simple for this one. We will just whip up the Paint Editor and put in a few strokes of blue for our "water".

Painting "water" on the Stage
In this project we will use two variables to help program the movement of the ball. To create a variable, first click on the ball sprite (you would have to add it first, of course). Then go to the Block Palette and click on the "Variables" block group. Under the group, you will see the "Make a variable" button.

The "Make a variable" button under the "Variables" block group
Click on the "Make a variable" button and a you see a small popup. That's for us to name the variable. Select "For this sprite only" option, and name the variable old y:

Creating a variable for the ball sprite
Once we hit "OK", we will get a variable named old y whose value can be read by the ball sprite only. Create one more variable and call it y velocity. This is what you should see once done:

Our two variables
What is left of the setup now is for us to set (or in programmer speak, "initialize" our ball position and the value of the y velocity variable. This ensures that every time we start the program by clicking the green flag, the ball is positioned at the right place and y velocity is reset to 0.

Initializing ball position and  the "y velocity" variable

Step 2: Program ball movement

How are we going to program the ball movement? Before we get our hands dirty, let's talk about how a ball really moves in the real world. If we hold a ball still in the air, it has zero velocity because it does not move. The ball has a certain position - it could be say, 100m off the ground.

Now what happens when we release our grip on the ball? At the very instant we release it, the only force working on the ball is gravity. The ball now picks up velocity, and moves faster and faster towards the ground.

Let's rewind this scene and play it very, very slowing in our heads. Imagine the movement of the ball at every second while it falls. Suppose the ball falls 0.1m after one second. Its position after that one second is now 99.9m off the ground. Since it fell 0.1m in one second, its velocity after one second is 0.1ms-1.

The ball's velocity is not going to stay at 0.1ms-1 throughout the fall. It will pick up because of gravity. Let's say that gravity increases its velocity by 0.1ms-1 at every second. Now imagine what happens after two seconds. Since gravity has increased the ball's velocity by 0.1ms-1, it would have travelled at 0.2ms-1. This means that from the first second to the second second, the ball has fallen 0.2m. Its position is now 99.9m - 0.2m = 99.7m.

In the third second, its velocity would increase again by 0.1ms-1 to 0.3ms-1. So its position is now 99.7m - 0.3m = 99.4m

This is exactly how we are going to program it. We will move the ball at very small time slices by changing its position and velocity at every iteration of a forever block. Think of one iteration on the forever block as a small time slice.

Changing and keeping track of the position and velocity of the ball at every time slice
Remember that we also need to increase its velocity (due to gravity) at each time slice. We separate the script for this to a different stack:

Increasing velocity at each time slice
And there we have it - a falling ball.

Step 3: Keep the ball afloat by blowing

The last thing we need to do is to make the ball float up as we blow into the microphone. The harder the blow, the louder is our puff and the faster the ball will float upwards. To do this, we will use the loudness sensor. The loudness sensor is found in the "Sensing" block group:

loudness sensor
The loudness sensor has a Stage Monitor (or Watcher) that we can enable by ticking the checkbox next to it. We should be able to see the loudness value on Stage once it's ticked:

loudness Stage Monitor
Connect a microphone and blow into it. The loudness value is larger the stronger, or louder, you blow. So how shall we "blow the ball higher"? This is how:

Script to move the higher the louder we blow
All we do is change the velocity of the ball by a value factored by the loudness. We could merely change the y velocity by the loudness value, but the change would be too drastic - you could test it and see. So we pick a value, in this case 0.005, to multiply it by to adjust its effect.

Finally, we add a block to constantly turn the ball just so that it looks more natural and nice.

And that is all. Have fun!

Coming up: next week, we will learn how control a sprite with the keyboard. Til then!