Add Me!Close Menu Navigation

Interaction Design Courses, Workshops, and Resources

Add Me!Show Navigation

This tutorial introduces basic programming concepts using the Scratch language and Flash ActionScript 3, and was developed to support a live workshop I give to my design students (so it doesn’t have the complete explanations that I give in person). I’ve found that because Scratch is a visual programming language, designers (and other non-technical people) pick up programming concepts faster with it. This is especially true because of the single stepping feature of Scratch, which allows the user to watch each line of code work while the program runs.

Introduction

We’ll first cover the basic concepts of programming using Scratch, a visual programming language. Scratch allows you to create programs without typing in any code. Instead, you snap together programming blocks (kind of like Lego) to accomplish the task you want. Learning concepts this way allows you to concentrate on the actual concepts rather than getting bogged down with the spelling and syntax of traditional programming languages.

Once you’ve gotten a feel for each of the programming concepts using Scratch, we’ll switch and apply each of these same concepts to a traditional programming language, in this case Flash ActionScript 3 (ActionScript is similar to JavaScript and uses the same syntax).

We’ll cover the following programming concepts:

  • Program sequence – actions happen in a particular order
  • Event handling – perform an action when something happens
  • Loops – do something over and over again
  • Conditional statements (if and if-else) – decision making & logic
  • Variables – remember things over time
  • Arrays – lists of things
  • Collision Detection

Other important programming concepts to explore on your own

  • Randomness
  • Communication between objects

Topics

Expand All Topics | Collapse All Topics

Scratch Basics

To get you started, watch the video introduction from the Scratch site – apologies for the “kid” tone of the video.

Note the following features of Scratch and the diagram above:

  • There are three major parts of the Scratch environment: the Blocks Palette, the Script Area, and the Stage
  • When creating a program, you are applying that program to the currently selected sprite (graphic on the stage) – so click on a sprite and then drag programming blocks from the Blocks Palette to the Script area to apply a script to that sprite.
  • To create a sequence of blocks – i.e. a script – snap together blocks in the script area by dragging one block onto another block
  • Right click on any object for options, including help for any programming block.
  • Double click on a set of blocks in the scripts area to run it
  • To delete a programming block from the Script Area, drag it back to the Blocks Palette (or right click and select delete)
  • To copy a script block from one sprite to another sprite, drag the block of code onto the sprite in the Sprite List (lower right corner of Scratch).

Program sequence – Actions happen in a certain order

Programs are composed of a series of actions arranged in a particular order. The order of actions is very important, because one action may depend on another action occuring first. For example in Scratch, if you want to play a sound, it’s important to set the particular instrument you want before you play a note. Otherwise, the program will play whatever the default instrument is.

Scratch Examples:

In Scratch, to visually see program sequence in action, click on the Edit button at the top of the screen, and select “Set Single Stepping…”, and then select “Flash Blocks (slow)”. This will execute each step of the program at a slow speed so you can see what’s happening.


Once you’ve watched it “step” through the code a few times, re-order the code (e.g. put the “say hello” first) and then step through the code again and see what happens.

 

 

 

ActionScript 3 Examples:

Example 1

trace("step 1");
trace("step 2");
trace("step 3");
trace("step 4");

Example 2 – requires a movieclip on stage with an instance name of myMovieClip

myMovieClip.x += 20;
myMovieClip.rotation += 15;
trace("Hello");

Event Handling – Performing an action when something happens

Event Occurs -> Perform an Action

When programming for interaction, the most basic programming approach is to respond to the user’s interactions – i.e. a mouse click, pressing a button, walking in front of a screen. In programming terms, these interactions are thought of as events. Flash ActionScript and similar languages provide a standard way to perform an action when ever an event happens. In Scratch, you can use the “When Sprite Clicked” control block to handle the event where the user clicks on a graphic.

Scratch Examples:

The first example responds when the sprite is clicked on. It sets the instrument, plays a note, then changes the instrument and plays a note. In the second example, the sprite moves by 30 pixels, turns, and says hello.

 

ActionScript 3 Examples:

In ActionScript 3, responding to events seems complicated (especially when compared to ActionScript 2), but actually just requires some extra typing. The concept is that once you have given an object an instance name, it can be told to listen for events using the addEventListener() function. This function needs the name of the event you want to listen to, and the name of the function that should be executed when the event occurs. You then create a function with that name that contains the code you want run when the event occurs.

Note: If you are using a movieClip instead of a button, you will need to set the movieClip.buttonMode property to true so the cursor changes to a hand on rollover.

Example 1 – requires a button symbol on stage with an instance name of myMovieClip

myMovieClip.addEventListener(MouseEvent.CLICK,onClick);
// myMovieClip.buttonMode = true; // you only need this if using a movieClip rather than a button

function onClick(event) {
myMovieClip.x += 20;
myMovieClip.rotation += 15;
trace("Hello");
}

Example 2

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);

function onKey(event) {
	if (event.keyCode == Keyboard.SPACE) {
		myMovieClip.x += 20;
		myMovieClip.rotation += 15;
		trace("Hello");
	}
}

(see this adobe docs page for a complete list of the keyCodes)

Example 3 – requires that there be two button symbols on the stage with instance names of leftArrow and rightArrow respectively. In addition, there should be a keyframe at frame 1 named “page1″, and a keyframe at frame 5 (or where-ever) named “page2″.

Example 3 completed Flash file: events.fla

leftArrow.addEventListener(MouseEvent.CLICK,goPage1);

function goPage1(event) {
	gotoAndStop("page1");
}

rightArrow.addEventListener(MouseEvent.CLICK,goPage2);

function goPage2(event) {
	gotoAndStop("page2");
}

Loops – Perform an action over and over again

Many programming tasks require doing something over and over again. Looping structures enclose a series of actions and repeat them. For example, if you want to animate a graphic (sprite) across the screen, you would use a loop to do this – moving the sprite say 10 pixels each time through the loop. Looping also means that the program runs on its own for a while, without user interaction.

Scratch Examples:

 

ActionScript 3 Examples:

Example 1

myMovieClip.addEventListener(MouseEvent.ROLL_OVER,onOver);

function onOver(event) {
	for (var i=0;i<10;i++) {
		myMovieClip.x += 10;
	}
}

Example 2

myMovieClip.addEventListener(Event.ENTER_FRAME,onEnter);

function onEnter(event) {
	myMovieClip.x += 10;
}

Conditionals – Making decisions and controlling the flow of the program sequence

As the complexity of the desired program behavior increases, the software will need the ability to make decisions and perform different actions based on those decisions. For example, if you want a graphic to reverse direction when it hits the edge of the screen, your code will need to check the current position and decide if it is beyond the edge. If it is, it will need to reverse direction. To see these IF statements in action, turn on the “single step” mode to watch as the code makes a decision and follows a different sequence of actions as it reaches the edge of the screen.

Scratch Examples:

In the first example, the sprite tests for the right edge of the screen, and stops when it gets there. In the second example, the sprite tests for the right edge of the screen, and when it gets there, it reverses direction. It does the same when it gets to the left side of the screen.

 

ActionScript 3 Examples:

myMovieClip.addEventListener(Event.ENTER_FRAME,onEnter);

function onEnter(event) {
	if (myMovieClip.x < 500) {
		myMovieClip.x += 10;
	}
}

Example 2

myMovieClip.addEventListener(Event.ENTER_FRAME,onEnter);

function onEnter(event) {
	var clip = event.currentTarget

	// check to see if we are at the right or left edge
	if (clip.x > 500) { // right edge
		clip.rotation = 180;
	} else if (clip.x < 0) { // left edge
		clip.rotation = 0;
	}

	// go in the direction we are pointing
	if (clip.rotation == 0) { // pointing to the right
		clip.x += 10;
	} else { // pointing to the left
		clip.x -= 10;
	}
}

Variables – Storing information over time

In most projects, it’s important to store information such as numbers or some text. Variables provide the mechanism to not only store, but to change information as the program progresses through time. For example, in a game, the score starts out at zero, and each time the user does the right thing, the score is increased. A variable will hold the initial value (or be initialized to it), and then that value will be increased (or decreased) as an effect of a user action. Variables are how a program keeps track of the current score or other information that it needs to reference.

Scratch Examples:

Create two sprites on the stage, called Sprite1 and Sprite2. Then go to the Variables panel, and “Make a variable” called “counter”.

Then double click on each sprite and add the following programs to the appropriate sprite, where Sprite1 adds 1 to counter, and Sprite2 subtracts one from counter.

 

ActionScript 3 Examples:

Example 1 – These two examples require that there be two buttons or movieclips with instance names of “sprite1″ and “sprite2″ respectively.

var counter = 0;

sprite1.addEventListener(MouseEvent.CLICK,addOne);
sprite2.addEventListener(MouseEvent.CLICK,subtractOne);

function addOne(event) {
	counter++;
	trace(counter);
}

function subtractOne(event) {
	counter--;
	trace(counter);
}

Example 2 – This example requires that a dynamic text field be on the stage with the instance name of “showCounter”

var counter = 0;
showCounter.text = counter;

sprite1.addEventListener(MouseEvent.CLICK,addOne);
sprite2.addEventListener(MouseEvent.CLICK,subtractOne);

function addOne(event) {
	counter++;
	showCounter.text = counter;
}

function subtractOne(event) {
	counter--;
	showCounter.text = counter;
}

Example 3 – This example uses only one function to accomplish both addition and subtraction by giving the sprite objects a score value in a variable called changeByScore, and using that to change the score. The technique of giving an object new variables only works with movieClips, not buttons. So if you used buttons in the previous example, open the property inspector and change the sprite symbols to “Movie Clip”  instead of “Button”.

var counter = 0;
showCounter.text = String(counter);

sprite1.addEventListener(MouseEvent.CLICK,changeScore);
sprite1.changeScoreBy = 1

sprite2.addEventListener(MouseEvent.CLICK,changeScore);
sprite2.changeScoreBy = -1

function changeScore(event) {

	// get the object that called this function
	var clip = event.currentTarget

	// change the counter by the amount stored in that object's changeByScore variable
	counter += clip.changeScoreBy;

	// display the current value of the counter variable
	showCounter.text = counter;
}

Lists/Arrays – Storing lists of values

Lists, or the more formal name of Arrays, are collections of values that can be accessed by an index. For example, if there are 10 items in the list, you can get each item in the list by number. Scratch starts at the number 1, and ActionScript and most other programming languages start at the number 0.

These lists are like simple databases, and allow the programmer to manage large sets of things efficiently.

Scratch Examples:

Example 1 – Go to the variables blocks and click on “Make a List”. Select For all sprites, and name it “phrases”. Once you’ve created the list, you can add items to it by typing them in. Then add the code blocks shown to have a sprite say one of the phrases. Experiment by changing the item number in the red block.

 

Example 2 – Using the same list you already made, modify the Scratch project to add a button sprite to the stage, and assign the first code blocks below to it. Then modify the original sprite to have the second set of code. Once you’ve tested clicking on the button sprite and it works, duplicate the original cat sprite 6 times and see what happens.

This approach is to send a message to all the cat sprites, and each one responds by saying a random phrase from the list.

 

Collision Detection – Testing for when two graphics touch

Collision detection is the programming term for detecting when one graphic on the screen touches another graphic. That is, have they collided? Collision detection is commonly used for games to find out if things have hit each other (e.g. a bomb hitting a spaceship), but it can also be used to find out of a user has dragged one graphic onto another in an interactive interface.

Scratch Example:

Create two sprites on the stage named Sprite1 and Sprite2, and add the following script to the first one. You’ll see that when you drag one of the sprites onto the other, the thought bubble will indicate if they are touching or not.

ActionScript 3 Examples:

This example expects two movieClips on the stage, called sprite1 and sprite2 respectively. It also assumes a dynamic text object called showStatus. This example also introduces a method for allowing the user to drag and drop a movieClip on the stage. The function for detecting if there is a collision is hitTestObject(), which in this example checks the dragged movieClip “clip.” against the fixed clip “sprite1″.

The dragging code works by setting up an event listener for mouse_down and mouse_up to start and stop the dragging for that clip, respectively.

Example flash file: collision.fla

showStatus.text = "";

sprite1.addEventListener(MouseEvent.MOUSE_DOWN, dragIt);
sprite1.addEventListener(MouseEvent.MOUSE_UP, dropIt);
sprite1.addEventListener(Event.ENTER_FRAME,showCollision);

function dragIt(event) {
	// get the object that called this function
	var clip = event.currentTarget

	// Enable the moveClip to be dragged
	clip.startDrag(true);
}

function dropIt(event) {
	// get the object that called this function
	var clip = event.currentTarget

	// Disable dragging
	clip.stopDrag();
}

function showCollision(event) {
	// get the object that called this function
	var clip = event.currentTarget

	// check to see if the dragged sprite is touching the fixed sprite
	if (clip.hitTestObject(sprite2)) {
		showStatus.text = "Touching...";
	} else {
		showStatus.text = "Not Touching...";
	}
}

Apply all the concepts - Create a game

Now it’s time to apply all of these concepts into a single interactive project. Make a game where the user has a paddle at the bottom of the screen, and they move it back and forth, trying to capture one color of falling graphic (gain points), but avoid a different color (lose points if they hit it).

  • Make a simple game where sprites fall from top to bottom, some one red, some a different color
  • Make black bar-shaped sprite move back and forth at the bottom of the screen when the left and right arrow keys are pressed
  • Change the score so that one color of falling sprite increases the score, and the other color sprite decreases the score when the bar and the sprites hit.

Programming tasks:

  1. Initialize the score to 0 when the game starts (hint: put a script on the “stage” sprite to do this)
  2. Make the sprites fall – i.e. animate from the top of the screen to the bottom of the screen.
  3. Make the sprites cycle back to the top of the screen when they reach they bottom of the screen
  4. Make the bar move back and forth when the left and right arrow keys are pressed
  5. Make the sprites check to see if they have collided with the bar
    1. if they have, add or subtract from the score
    2. move the sprite back to the top of the screen
  6. Display the current score

Bonus Tasks:

  1. When the falling sprites recycle to the top, make them start in a random position left to right (i.e. the x position should be reset to a random number). This will make the game less predicable and more fun.
  2. Add a “good” sound for when the score is increased, and a “bad” sound for when the scored is decreased.

Hints:

  1. Creating programs is a trial and error process – they never work right the first time. Expect this, and just keep improving and refining it as you go.
  2. Get a single falling sprite working first, and then copy it to make additional falling sprites. This way, you’ll only make mistakes and changes to a single sprite, and won’t have to go back and change all the other sprites over and over again.
  3. Consider where the code for each part should go. There is no right way to program, but often putting the code on the right sprite will make it easier because the sprite knows where it is.

Download the finished game in Scratch: game.sb, or Flash: game.fla