[Repost] Multi-Coloured Ink Blotting (Processing)

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

blotty

This one is quite complicated but I thought I’d share how great Processing can be. This program creates an expanding circle (think ink blotting from a fountain pen) as long as the mouse click is held. Once the mouse is released, the colour of the next circle will be different (through a random colour generator). It will also appear on top of the previous circle should you click in the same place. You can make some pretty great graphics (see above) once you’ve made the program.

There’s not a lot of code, but it uses arrays which will be difficult for students to get their heads around. An array is best thought of as something like a series of containers ready to be filled with a value. Like a single-file ice cube tray or something. They’re particularly useful when using motion as they can store a sequence of values, such as a large set of x coordinates or y coordinates. In this case they store a sequence of circle sizes. A bit like a memory bank.

There’s a bit of code at the bottom which will clear the screen should it get too messy.

Note that the colour changer is random. Specifically it’s the fill (random (255), random (255), random (255)) bit of code, which assigns a random number up to 255 for the red, green and blue values of the colour respectively. All colours on a computer are a combination of these three elements, going to a max of 255.

blotty2

Hopefully the comments in the code make sense. If you plan on using this as a lesson, I’d provide the students with the code and ask them to alter parts of it, such as making rectangles instead of circles, or setting the colour randomiser to select one of four predefined colours, or get them to annotate the code to guess what it’s doing.

I’m pretty confident most students wouldn’t be able to create this from nothing in a secondary school. Congrats if you think they can!

They should be able to create a similar program that generates a single expanding circle just using ‘if’ statements rather than arrays.

Again, this post is more to showcase what Processing is capable of.

Copy and paste the code below the formatted screen print directly into Processing and run it. Comments are included on the copy-paste version.

(adapted from here)

code

colour splat

int num = 250;
int count = 0;
// Create array of type 'float' to store circle sizes in
// Size of array is var 'num' which is 250
// 250 is the max size of the circles. you can make these smaller if you like
float ms[] = new float[num];
void setup() {
size(800, 800);
noStroke();
fill(0, 255);
background(255);
}
void draw() {
if (mousePressed)
{
// count%num means 'remainder of (count / num)'
// this is a fairly standard way of ensuring a 'circular array' loops back around
// so when it is full, it starts filling up again (replacing values) from the start
ms[count%num] = 0;
// below is a 'for' statement that increases the size of the circle as long
// as the mouse is pressed
// below, 'i' needs to be less than the minimum value of 'count' or 'num' in order
// to ensure that the circle keeps 'growing' until it reaches a maximum size and then stops
// the for loop fills the arrays with appropriate values
// ms[i] changes (++) so that circle gets bigger (redrawn in a bigger size each time essentially)
for (int i = 0; i < min(count, num); i++) {
ellipse(mouseX, mouseY , ms[i], ms[i]);
ms[i]++;
}
count++;
}
}
// when mouse is released, var count is set to zero (reset essentially),
// this ensures that a new circle will be drawn when the mouse is pressed again
// and colour of circle is changed (fill) randomly (r,b,g values respectively)
void mouseReleased() {
count=0;
fill(random (255),random(255),random(255));
}
void keyPressed(){
background(255);
}
Advertisements

[Repost] Shape Shifter (Processing)

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

proc1

So far we’ve covered only 2 programming ‘languages’, of which, only one is an actual language (Scratch is more of a simulator i suppose?). The other language I think really (REALLY) benefits students is Processing. It’s very much a sequel to Scratch (and free), but requires real coding rather than drag-and-drop boxes. It’s a kind of stripped down Java, but with a much bigger emphasis on graphics manipulation. Think LOGO x 1000. It’s incredibly straight forward to use and has a huge amount of support and tutorials readily available.

The reason why I think it’s so perfect for schools is it’s huge focus on graphics. It allows the user to make moving images, and  urges them to. The end product therefore is more satisfying in a lot of ways for children and young adults. The best part is that there are a wealth of export options so that a student can take home their work as a windows stand alone file, or mac, or linux, or as a .gif, or even as an android app for their phone (!). Convinced yet?

The tutorial that follows is largely taken from the book (recommended) written by the creators of Processing, which can be found here.

This program prints a shape at the point of the cursor as you move it around a screen. When you click the mouse, the shape ‘fills in’ (black), otherwise it is empty (white).

The result looks something like this:

proc2

The code is blissfully simple and short:

proc3

I think you’ll be able to figure out the code so I won’t spend paragraphs decoding it above and beyond the comments (note comments are with “//” rather than # (from Python). Syntax is slightly different from Python, but syntax is slightly different in all programming languages. “void” is basically a declaration of a function that doesn’t return any values to the rest of the program.

That reminds me, if you don’t know what something means in Processing, you can right click on it and there’s a Processing Dictionary that will tell you what it means and how to use it, with examples! Great stuff.

As a lesson, I’d get students to write the code above themselves, just to get used to the interface, how to run it, check for errors etc.

Once they have it working, get them to try replacing the circles with other shapes.

Basic ones are below:

triangle(x1, y1, x2, y2, x3, y3)

(where x1, y1 are the coordinates of the first corner of the triangle, etc)

quad(x1, y1, x2, y2, x3, y3, x4, y4)

(for quadrilateral)

rect(x, y, width, height)

That last one should be straight forward enough!

As an extension you could get them to replace the original shape with a different shape when the mouse is clicked, rather than colouring it in.

Below is an example of where you can go with Processing in not a lot of time:

proc4

[Repost] The Name Game (Python)

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

namegame

This project involves very little code but some great ‘figuring out’ beforehand.

If you’re unfamiliar with the song, watch below:

The lyrics of the song actually describe the rules you need to apply in Python, which would make for a great exercise for students to work through – figuring out pseudocode from a song!

The lyrics in full are at the bottom of this post.

We’re going to write Python code that generates lyrics to the song based on a user’s first name.

The pseudocode should essentially go something like this:

input word
for word:
if 1st letter = vowel, then word = word,
else word = word – 1st letter
print lyrics

(at its most basic)

From this students should be able to deduce that they’re going to need 2 versions of the input name, one unaltered, and one altered. The altered version will be the original name minus any consonants before the first vowel.

To check whether a letter is a vowel, you’ll need a list of vowels to check against.

The only part of the code that hasn’t been discussed or used in previous examples is the checking of characters against other characters.

Specifically, we have the line “if name2[0] in vowels : “

the [0] part is returning the first character in the string ‘name2′. You’d think the first character would be [1] but you’d think wrong. Python starts counting from 0.  We’re also using “in” which we haven’t used before. It pretty much does what it says on the tin.

The complete code, with comments is below. Copy and Paste version below that (remember to indent once you’ve pasted it!)

Finally, I got the idea from this post on a forum.

code1


name = input (“what is your first name?”)

name2 = name

vowels = “aeiouAEIOU”

if name2[0] in vowels:
name2 = name

else:
name2 = name2.replace(name2[0],””)

if name[0]==”B”or name[0]==”b”:
print (name + “!\n” + name + ” ” + name + ” Bo ” + name2 +
“\nBanana Fanna Fo F” + name2 + “\nFe Fi Mo M” + name2 + “\n” + name)

elif name[0]==”F” or name[0]==”f”:
print (name + “!\n” + name + ” ” + name + ” Bo ” + “B” + name2 +
“\nBanana Fanna Fo ” + name2 + “\nFe Fi Mo M” + name2 + “\n” + name)

elif name[0]==”M” or name[0]==”m”:
print (name + “!\n” + name + ” ” + name + ” Bo ” + “B” + name2 +
“\nBanana Fanna Fo F” + name2 + “\nFe Fi Mo ” + name2 + “\n” + name)

else:
print (name + “!\n” + name + ” ” + name + ” Bo ” + “B” + name2 +
“\nBanana Fanna Fo F” + name2 + “\nFe Fi Mo M” + name2 + “\n” + name)

____________

Shirley Ellis Lyrics:

Shirley!
Shirley, Shirley bo Birley Bonana fanna fo Firley
Fee fy mo Mirley, Shirley!

Lincoln!
Lincoln, Lincoln bo Bincoln Bonana fanna fo Fincoln
Fee fy mo Mincoln, Lincoln!

Come on everybody!
I say now let’s play a game
I betcha I can make a rhyme out of anybody’s name
The first letter of the name, I treat it like it wasn’t there
But a B or an F or an M will appear
And then I say bo add a B then I say the name and Bonana fanna and a
fo
And then I say the name again with an F very plain
and a fee fy and a mo
And then I say the name again with an M this time
and there isn’t any name that I can’t rhyme

Arnold!
Arnold, Arnold bo Barnold Bonana fanna fo Farnold
Fee fy mo Marnold Arnold!

But if the first two letters are ever the same,
I drop them both and say the name like
Bob, Bob drop the B’s Bo ob
For Fred, Fred drop the F’s Fo red
For Mary, Mary drop the M’s Mo ary
That’s the only rule that is contrary.

Okay? Now say Bo: Bo
Now Tony with a B: Bony
Then Bonana fanna fo: bonana fanna fo
Then you say the name again with an F very plain: Fony
Then a fee fy and a mo: fee fy mo
Then you say the name again with an M this time: Mony
And there isn’t any name that you can’t rhyme

Every body do Tony!
Pretty good, let’s do Billy!
Very good, let’s do Marsha!
A little trick with Nick!
The name game

[Repost] Sonic Game

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

sonic

I’ve created a background and a fully (ish) functional character who can jump and run around. I used sonic the hedgehog as it’s pretty easy to find the numerous variations of a character in animation from a popular computer game. (type in ‘sonic sprites’ into google for example). You’ll be looking for an image like this.

Once you have the image for the character(s) you want, then you have to chop it up in Photoshop or similar into individual characters. Finally, convert them into .gifs with transparent backgrounds and import them into Scratch. (see below)

p1

So now we have all the ‘poses’ needed for smooth animation, without having to be an expert in creating digital images.

Next you need a background. You could make a simple one using the paint tools, or cheat like I did and just find a large enough image from google like this one.

p2

Use the ‘clone stamp’ in Photoshop to remove any unwanted parts of the image (it’s likely to have your character on it for starters) then import it as a background into Scratch.

If it appears too small, just enlarge it from within the image editor in Scratch.

Now we’re ready to start the code.

This exercise is a great example of when to use pseudocode first. In other words, write down on paper what you want the program to do, in programming-ish language. It makes the final program easier to make and understand.

This program has a few components:

  1. the sprite needs to respond to left and right arrow keys by moving left and right
  2. the sprite needs to respond to the space bar by moving up and down
  3. the sprite needs to change costumes when it moves

Those are the basics. But out of that, you’ll find plenty of issues if you’re not careful.

The first bit of code is below. When you click the green flag (start the program), the sprite (sonic) switches to ‘Sprite 1′ and then alternates between ‘sprite 1′ and ‘sprite 2′ until either the left or right arrow is pressed. Sprites 1 and 2 are the ‘waiting’ sprites – sonic is tapping his foot.

Note there is also a variable in this program called ‘walk cycle’. You’ll need a variable in Scratch if you have something that will require more than 2 possible outcomes. If you just have 2 outcomes, you can essentially use true or false. In this program we need more than 2 outcomes for the state of Sonic. He’s either standing still (walk cycle 0), jumping (walk cycle 1), walking right (walk cycle 2) or walking left (walk cycle 3). At the start of the program he is standing so we set it to zero.

So far in this code we DON’T need the variable, as it isn’t called upon anywhere. However, I suspect I’m going to need it later in the program which is why I’ve kept it in.

p3

You can see a smaller piece of code in the picture above that sends a message within the program when the ‘space bar’ is pressed. This triggers the jump programs below:

p4

The code above changes the variable ‘walk cycle’ to 1, then moves the sprite upwards for 0.6 seconds, pauses at its maximum height for 0.1 seconds, then falls back down to its original position (which takes another 0.6 seconds).

The second part of the ‘jump’ program is below, and is concerned only with costume changes. Note that the costume changes time just about adds up to the same as the vertical movement time (they’re about 0.15 seconds out). That’s so that none of the costumes ‘hang’ during the jump.

Once the jump is complete, the program resets the ‘walk cycle’ to zero (stationary) and changes the costume back again.

p5

The reason there are 2 jump programs, rather than one integrated program is as follows:

the 1st program involves a glide for 0.6 seconds. If you wanted to change outfits every 0.1 seconds, then the glide won’t work. It can only do one thing at once within one program. That’s why we run them alongside each other. It would also seem jittery if the smooth glide function was broken up into 0.1 second chunks to allow for costume changes.

So far so good. Sonic now stands tapping his foot, and jumps (with its own unique animation) when you press spacebar.

Next we need him to move left and right:

The code below shows how it’s done. As soon as either left or right is pressed, we get a costume change to a ‘moving’ sonic. And for as long as the left/right key is pressed AND sonic is on the ground (y position = -88 in this case). there is a costume change loop. Every 0.2 seconds, the costume changes by +1. In other words, costume 10 would change to costume 11, costume 11 to costume 12 etc. If the costume is on #14, the ‘else’ clause kicks in and the costume is reset to costume #10. If that didn’t happen, then sonic’s costume would go onto 16, 17 etc which are NOT set as running sprites. The last running sprite is 15. (14+1 = 15, hence “if costume #<14″).

p6

The second part of the ‘left’ and ‘right’ code is below. This part makes sonic actually move, rather than change costumes.

He moves -10 when you press left, and +10 when you move right.

The reason why we have the AND clauses in the program, to check sonic is not in the air, is to make sure that he doesn’t “accidentally” change costume in the air if you press right or left.

p7

This is a good time to point out another great advantage of scratch: when you use variables, you can see what they’re doing whilst your program is running. In the top left corner of this program, you get feedback as to what value the variable ‘walk cycle’ currently has. This is great for debugging, as if it’s not what you expect, you know whereabouts your program is going wrong.

Later I’ll do part 2 where we introduce some bad guys for sonic to jump into/onto.

Working program is available here.

[Repost] What Would You Weigh On Mars?

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

1995561-mars_attacks_1_1024x768

This week I’ve been exploring a couple of new concepts in Python (new… to me). The main one is a big one. Python has a lot of pre-created code for bits and bobs that crop up often for programmers. This is both majorly helpful and also a bit of a pain. Helpful because it stops you having to work out simple ideas using complex code (as you’ll see below), but a bit annoying in that you have to find it first.

The code I’ve developed prompts users to enter their birthday and weight, and then displays their equivalent ages and weights across the different planets in the solar system. Pluto isn’t technically a planet these days, but we’ll keep it regardless.

plutodog

Pluto, you suck.

So the program doesn’t use many features I haven’t covered before, but the first line shows that I’ve imported ‘date’ from a bank of code called ‘datetime’. This code allows for basic manipulation of dates without having to do all the hideous conversions from integers, to strings, to calculating days from months blah blah blah. Useful.

It gets used in this example by taking two dates, finding the difference between them and giving back an integer that is essentially the number of days you have been alive (give or take a little).

The program then takes that number, which obviously is different for every user (hence the inputs at the start of the program), and performs basic calculations on it based on values supplied helpfully by smarter people than me, here.The values basically being the different lengths of years per planet measured in earth days.

The program also takes the user’s weight, and does much the same thing with the number, albeit with values relevant to the different surface gravity on each planet (which I found here).

Funnily enough you’re a lot younger on some planets than others…

w3

Not sure this is quite how it works.

Numbers had to be ‘float’ rather than ‘int’ because ‘int’ only covers whole numbers, and we need decimals (otherwise your age will likely be less than 1 for some of the planets, and hence appear as a series of zeros … boring). However ‘float’ displays a lot of decimal places, so I also had to use the ’round’ function to get them a little more sensible.

w2

Hopefully students can figure out for themselves that it makes sense that you’d be ‘younger’ on planets further away, as they take longer to get around the sun.

The weight calculation just forms part of the ‘print’ function rather than being separate variables just to make the code shorter.

w1

Seriously, just go to Mars you’ll be fine.

Code with comments, followed by copy-paste code is all below. Based on two examples found here and here.

If you want to know your weight and age on other planets RIGHT NOW (because it’s awesome) click here and here   .

w10

from datetime import date
print (“Please enter your birthday “)
bd_y=int(input(“Year:”))
bd_m=int(input(“Month (1-12):”))
bd_d=int(input(“Date:”))
weight = float(input(“what is your weight (any units)? “))
units = input(“What units did you use? “)
now = date.today ()
age = date(int(bd_y), int(bd_m), int(bd_d))
delta = now – age
earth = round(float(delta.days/365.26),2)
mercury = round(float(delta.days/87.97),2)
venus = round(float(delta.days/224.7),2)
mars = round(float(delta.days/(365.26*1.88)),2)
jupiter = round(float(delta.days/(365.26*11.86)),2)
saturn = round(float(delta.days/(365.26*29.46)),2)
uranus = round(float(delta.days/(365.26*84.01)),2)
neptune = round(float(delta.days/(365.26*164.79)),2)
pluto = round(float(delta.days/(365.26*248.59)),2)
print (“on earth you are”, earth, ” years old and weigh “, weight, ” “, units,”\n”)
print (“on mercury you are”, mercury, “years old and weigh “, weight*176, ” “, units,”\n”)
print (“on venus you are”, venus, “years old and weigh “, weight*117, ” “, units,”\n”)
print (“on mars you are”, mars, “years old and weigh “, weight*1.03, ” “, units,”\n”)
print (“on jupiter you are”, jupiter, “years old and weigh “, weight*0.41, ” “, units,”\n”)
print (“on saturn you are”, saturn, “years old and weigh “, weight*0.43, ” “, units,”\n”)
print (“on uranus you are”, uranus, “years old and weigh “, weight*0.75, ” “, units,”\n”)
print (“on neptune you are”, neptune, “years old and weigh “, weight*0.67, ” “, units,”\n”)
print (“on pluto you are”, pluto, “years old and weigh “, weight*0.58, ” “, units,”\n”)

[Repost] Consequences (game)

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

cons

Here’s a nice Python lesson. I’ve written some very basic code that recreates the classic game of Consequences – which you may, or may not have heard of! It’s a simple premise – the first player writes down an adjective, folds over their paper, then the second player writes down a name, folds the paper over, and so on. Once both / all players have inputted their allocated text types (adjectives, names, places, speech etc), the paper is unraveled and a hilarious (yes, HILARIOUS) if somewhat random story unfolds.

cons2

(hilarious)

This link explains and demonstrates the game a little better than me.

The code for this game is ridiculously simple. Essentially you have eleven different input prompts, then print them all out at the end, with a few sentence links added in.

The only bit that took a while to work out is reenacting the secrecy element (ie the paper folding in the original game). You’d think that Python would have some nice easy code to disable the ‘echo’ it displays (in other words, stop Python from printing each part of your story before you’ve told it to print).

Well, unlucky. Python has no clear way of not echoing. Neither is there a simple way of text-masking (like when you type your password in and it appears as ******). There are work-arounds and module-imports that can do those things or similar, but they make the code overly complicated and would ruin a lesson for children.

The closest I’ve found is a fairly cheap but workable

print (“\n” * 100)

It feels cheap, because all it does is print 100 blank lines, therefore ‘pushing’ each part of the story off the screen. However it’s easy code, easy to explain to students, and crucially, allows them to play the game as pairs / groups. Obviously students would have to divert their eyes whilst their partner types in their own part of the story, as it doesn’t disappear until they’ve finished entering it.

The best part of it all is that the results can be really funny, and students get to learn about printing multiple strings and variables within one single print function.

cons3

def main():

adj1 = input(“Enter the first adjective “)
print (“\n” * 100)
adj2 = input(“Enter the second adjective “)
print (“\n” * 100)
manname = input(“What was his name? “)
print (“\n” * 100)
adj3 = input(“Enter the third adjective “)
print (“\n” * 100)
womanname = input(“What was her name? “)
print (“\n” * 100)
loc1 = input(“Where did they meet? “)
print (“\n” * 100)
gift1 = input(“What gift was given? “)
print (“\n” * 100)
said1 = input(“What did he say to her? “)
print (“\n” * 100)
said2 = input(“What did she say to him? “)
print (“\n” * 100)
cons = input(“What was the consequence? “)
print (“\n” * 100)
wtw = input(“What did the world say about it? “)
print (“\n” * 100)
print(“The “, adj1, ” and “, adj2, ” “, manname, ” met the “, adj3, ” “, womanname,
” in “, loc1, “; he gave her “, gift1, ” and said to her “, said1, ” She said to him: “, said2,
“; and the consequence was “, cons, “, and the world said ‘”, wtw, “.'”)

[Repost] Target Practice

[This was originally posted last year, on an old blog to promote computational thinking and programming in schools. I’ll be reposting these over the next month as I think they’re still useful to schools embarking on the new Computer Science course]

Far-Side-buck-birthmark

This week I’ve started a bit of games development using Scratch. It’s really what it was made for, so once you get used to the basics, simple games can take just a few hours. Even less if you have all the graphics prepared beforehand.

This example is really a starting point rather than a finished game. It’s a simple Duck Hunt style game whereby your cursor is a crosshair, you shoot moving objects.

In terms of programming, you need very little ‘code’. This example introduces the use of ‘random’, sprite costume switches, and sound.

I suggest you play the game first, then read on.

 
jar

So here’s how I built it:

Step 1: Prepare your graphics. As mentioned in a previous post, being able to prepare transparent gifs is essential if you’re going to bring your own ideas into scratch. In this example, I found a crosshair, and a few images of star wars characters, chopped out the backgrounds, shrunk them down and imported them into scratch as gifs. I then ‘duplicated’ the gifs within Scratch, and edited the character duplicates just to add red crosses on their eyes for the ‘dead’ sprite costume. Image editing within Scratch is incredibly limiting and frustrating, hence why I used Photoshop first.

Step 2: Attaching the crosshair to the cursor. Just like in the Homer Simpson example, with almost identical code, I made the crosshair follow the cursor. The only difference here was that I added a sound for when the mouse button is pressed (a Star Wars blaster). All the sounds were just googled. One or two needed a little editing in Audacity before importing, as there’s no sound editing tools in Scratch.

The code for the cursor is below:

code

Step 3: Import one of your sprites. As you’ll want to test as you go, don’t crowd the screen with sprites that you aren’t ready to use yet. Just import one, try out the code until it’s doing what you want, then import the others and duplicate the code. Otherwise it’s needlessly annoying.

As mentioned, each sprite needs an ‘alive’ costume and a ‘dead’ costume:

code 2

Now it’s time to make them do something. The code for each sprite is in two parts. The first part is activated from when the program starts. It essentially sends the sprite on a random journey around the page. The sprite will only stop when its costume changes (ie its been ‘shot’). Although you should note that it won’t stop until it has finished running through the first part of the ‘if’ statement. In other words, if you ‘shoot’ it just as it starts a new movement, it will complete that movement before stopping.

code 3

The second part of the code will only run when you click on the sprite (‘shoot’ it). When that happens, the sprite ‘changes costume’ into the dead version, and its sound file is activated. Then it disappears for a little while, and ‘respawns’ 4 seconds later.

As I said before, it’s barely a game. There’s no scoring system, introduction, game over screen etc, but it’s a starting point for a more complicated program. the code is simple, and if you prepare all the images / sounds beforehand, you could complete this in one lesson.

Note: It obviously doesn’t have to be Star Wars, you could do pretty much anything. It doesn’t even have to be shooting. There’s a fun fly swatting game here for example. Or as an Easter game, the cursor could be a spoon which breaks eggs to find chickens inside or something. I only chose Star Wars because I wanted to shoot Jar Jar Binks.

jar2

You can download the whole program here.