CHAPTER 4

Coding: How to Write a Game Program

Everything in a video game comes from the gamemaker’s imagination, including how characters act, how objects move, and every twist and turn of the storyline. How does the game get from your brain to your screen? It must be translated into a list of instructions your computer can understand—a computer program.

The people who write, or code, computer programs are called programmers or coders. To build games, they use programming languages such as Java, Python, or C++. Each language has its own set of commands or statements, which are similar to the words in a spoken language.

WORD TO KNOW

programming language: a language invented to communicate instructions to a computer.

ESSENTIAL QUESTION

How is programming a computer game like baking cookies?

Computer languages also have their own syntax, which is like the grammar you use to put words together into a sentence. Syntax includes what order the commands go in and what punctuation marks are used. For example, in English you generally end a sentence with a period. In Java every line of code must end with a semicolon (;) or the computer won’t read the code correctly.

Some programming languages are better for certain things, so programmers often learn more than one. Mastering a new language can take time, because every letter, symbol, and space must be exactly right.

Luckily, there are tools designed to help beginners start coding without having to learn to write an entirely new language!

Visual programming languages (VPL) such as Scratch, Tynker, and Blockly let you build programs using drag-and-drop blocks instead of typing in commands. You simply use your computer mouse to move the block you want to the right spot. The blocks snap together to form a column on your screen, and you read your program from top to bottom. Other kinds of game programming environments include Unity, Construct 2, Stencyl, and GameMaker Studio.

WORD TO KNOW

syntax: the rules for writing commands in a programming language.

visual programming language (VPL): sometimes called graphical software, this is computer code that uses images such as blocks to create a program instead of typed-out commands.

drag-and-drop: clicking on an object and holding a button on your mouse while you move it to the desired spot.

BONUS POINTS

The number system you use every day has 10 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. It is known as a Base 10 number system.

COMPUTER TALK

Computers are machines, and they understand machine language. They are made up of billions of electronic switches called transistors that are either turned off or on. Machine language is made up of only two numbers: zero for off, and one for on. This number system is called binary.

Each zero and each one is also known as a binary digit, or bit. Machine language groups those bits into groups of eight to form a byte. A byte can be used to represent a letter, number, or symbol. In machine language, the word “hello” is written like this:

WORD TO KNOW

machine language: the code used directly by a computer, written in zeroes and ones.

transistor: a small device that acts as an on/off switch to control the flow of electricity in a computer.

binary: a math system containing only zeroes and ones. The word binary comes from the Latin word bi for “two,” as in bicycle and binoculars.

bit: the basic unit of information storage in a computer, consisting of a zero or a one.

byte: a group of eight bits that is treated as a single piece of information.

All computer programs, no matter how advanced, are really nothing but zeroes and ones!

THINK LIKE A PROGRAMMER

The most important thing you need to learn before coding isn’t how to write any particular language, it’s how to break down a problem or action into a series of steps. This series of steps is called an algorithm.

Think of an algorithm as a recipe for baking a computer program.

When you make chocolate chip cookies, your recipe tells you all the things you’ll need to do. Of course, the sequence of commands is also important. If you don’t follow the steps in the right order, your cookies—or your program—might not come out the way you expect!

Looking at problems as a series of steps can also help you find patterns that repeat over and over. And computers are good at repeating patterns. That means you don’t have to write out each step every time, which makes programming easier and faster! There are two main ways to do this: functions and loops.

WORD TO KNOW

algorithm: a series of steps to complete a task. There can be different algorithms to do the same thing.

sequence of commands: the order of the steps in a program.

function: a short piece of code that is given a name so it can be used multiple times in a program simply by inserting the name. Also called a subroutine or procedure.

loop: a section of code that is repeated a certain number of times or until a specific condition is met.

BONUS POINTS

In 2013, Google executive Dan Shapiro invented a board game called Robot Turtles to teach coding basics to young children. The game shows kids how to break big problems into small steps as they move their turtles through a maze. The game became an overnight hit, selling 25,000 copies before it was even printed.

A function is an algorithm that is given its own name. Instead of writing out all the steps, you just write the name instead.

For example, in the Goldilocks text adventure game from the previous chapter, the little girl finds three bowls of porridge and performs the same series of steps for each one.

You can define a function called tasting to perform these tasks.

Sit down at the table.

Pick up the spoon next to a bowl.

Dip it into the bowl.

Put the spoonful of porridge in her mouth and swallow.

Each time Goldilocks comes upon a new bowl, you can just call the function tasting and the program will repeat those steps.

You can also insert variables into your function. This is a letter or word that can be replaced with different information. The information must be in the form of data that can be processed by a computer. It can consist of numbers or a string of letters that make up a word or group of words. When you run the program, the variable tells it to look for the information in another part of the program or asks the player to fill it in.

WORD TO KNOW

define a function: to tell the computer what steps a function contains.

call a function: to tell the computer program to run a function.

variable: a symbol that holds the place for information that may change each time a command runs.

data: information, usually given in the form of numbers, that can be processed by a computer.

string: a short group of letters or words that is used as data.

A loop is a little like a function. But instead of running whenever you call its name, a loop keeps repeating as many times as you tell it to.

Another way to tell a loop to stop is to use conditional statements.

These tell a program to check whether or not certain conditions exist before continuing.

One common conditional statement is IF-THEN-ELSE. For example, IF the porridge is just right, THEN Goldilocks will eat it.

A WHILE statement tells the program to check to see if the condition is still true. WHILE the porridge is cooling, the bears will continue their walk. Every time they return to their house, they check the porridge to see if they should keep walking.

Conditional statements are a type of Boolean logic. Because a computer can only understand “on” and “off,” Boolean logic reduces every decision to two possible choices: True or False.

You can also expand the conditions using three logic gates: NOT (the condition is not true), AND (there are two conditions and both are true), and OR (there are two conditions and at least one of them is true).

WORD TO KNOW

conditional statement: a step in a program that gives a computer two choices depending on whether the answer to a certain test is yes or no.

IF-THEN-ELSE statement: a command that tells the computer to test whether a certain condition is true, then either go on to the next step or else a different step depending on the result of the test.

WHILE statement: a command that tells the computer to keep repeating a loop as long as a certain condition is true.

Boolean logic: named after George Boole, to turn every decision a computer makes into a yes or no question.

logic gate: a test that results in only one true-or-false answer.

You could say that if the bears are still on their walk AND the porridge is NOT too hot OR too cold, THEN Goldilocks will eat it.

BEFORE YOU CODE

Planning your computer program can help you code it correctly and make it easier to find problems when you test it. Here are a few best practices to try.

Write it out. Before you translate your game into a computer language, list all the steps using pseudocode. Write down all the actions you want your program to perform. Later, you can translate it into whichever programming language you decide to use.

WORD TO KNOW

pseudocode: from the Greek word for false, this is an algorithm written in language a human can read and understand.

TIC-TAC-TOE PSEUDOCODE

Here is one way to write out pseudocode for a game of tic-tac-toe. Notice that there are three different ways the game program can end.

WHILE there are empty squares on the tic-tac-toe board

Player 1 puts an X in a square.

IF there are three Xs in a row, THEN Player 1 wins.

ELSE Player 2 puts an O in one of the squares.

IF there are three Os in a row, THEN Player 2 wins.

ELSE REPEAT from Player 1’s turn

GAME ENDS in a tie (no winner).

Draw a flowchart. A flowchart is a diagram that shows all your possible options and the results for each one. These options can be shown as Yes/No or True/False statements. Flowcharts are also helpful for showing how loops work.

WORD TO KNOW

flowchart: a diagram that shows all the possible options and results.

BONUS POINTS

An old saying from the early days of computers is, “Garbage In, Garbage Out” or GIGO. It means a computer is only as accurate as its programs. As a programmer, you need to test your code for syntax bugs, which are mistakes caused by typing errors, and logical bugs, which are problems putting the right steps in the right order. Test your coding just like you test every other part of your game.

Organize it with a chart. A chart can be a great help in keeping track of all the objects and characters in your game. Your chart should have three columns.

Name and category: these are the objects and characters.

Properties: what it looks like, how many versions are needed, where and when it starts.

Actions and abilities: any movement or changes in appearance, any interaction with other objects or characters.

Goldilocks Flowchart

GOLDILOCKS GAME CHART

Here is a sample game chart showing objects and characters in the Goldilocks game.

CODING IN SCRATCH

Scratch is a great first programming language to learn. It was developed for kids in 2003 by computer scientist Mitch Resnick and the Scratch Team at the Lifelong Kindergarten group. This group is part of the Massachusetts Institute of Technology Media Lab.

What makes Scratch special is the online community where you can share your work. You can get feedback on your projects and learn from projects that other Scratch members have done.

The Scratch site is moderated, so it’s safe for kids to use at school or at home.

One way Scratch helps you learn to code is with the “See Inside” feature, which shows you the programming for any project on the site. You are also encouraged to “remix” other people’s projects, which is when you make a copy for yourself that you can then change to create your own version. The rules on the Scratch website allow anyone to remix any of the projects found there.

Getting started is easy. Go to the Scratch website at scratch.mit.edu and start creating programs right away. When you create a free account, you can save your work and share it with others. You can also download Scratch to your computer’s hard drive so you can use it without having to connect to the Internet.

BONUS POINTS

One of the first programs ever written by Microsoft founder Bill Gates was an algorithm to make the computer play tic-tac-toe.

DOCUMENTATION

If you look at code written in programming languages such as Python and Java, you might notice short notes in English that tell you what is going on. This documentation is a powerful tool for helping programmers fix problems in their code. You should always document the programs you write so you or another programmer knows what each step is supposed to do. In many languages, a double slash (//) is inserted before any documentation comments. That tells the computer to ignore whatever comes next on that line. For human brains only!

WORD TO KNOW

documentation: an explanation of a section of computer code, written in non-machine language.

The Scratch projects in this book were built using Scratch 2.0. If you are using a computer with an earlier version, the look of the workspace and some of the features will be a little different.

You can start a new Scratch project by clicking Create at the top of the screen. This will take you to the user interface (UI), where you will build your project. Let’s look at the different parts of building a program.

Sprites and costumes: When you open Scratch, you’ll already have a character there to play with—the Scratch Cat. In Scratch, objects and characters, such as the Scratch Cat, are known as sprites.

All the sprites you use in your project are displayed in the lower left section of the screen, the Sprite List.

You can add other sprites from the library on the Scratch website. Just click on the menu bar above the Sprite List.

To change the look of a sprite during a game, you can add a costume. In Scratch, a costume doesn’t refer to clothes. It’s an image of the same character, but in a different position. For instance, to make an animation of the Scratch Cat walking, you can add several costumes with its legs in different positions and switch between them quickly. There is also a Sprite Toolbar above the stage with buttons that let you duplicate, delete, grow, and shrink them.

WORD TO KNOW

user interface (UI): in Scratch, the screen where you build your project.

sprite: an object or character.

costume: a variation of a sprite that looks somewhat different from the original.

stage: the background of a Scratch project.

Stage and backdrops: The Scratch Cat and other sprites do all their activities on a large space called the stage. This is a small version of what a player sees on the screen when your program runs.

When you’re programming, the stage lets you see immediately what happens when you add, take away, or change things.

Backdrops are backgrounds for the stage. On the left edge of the Sprite List, you’ll see a column with a thumbnail of the current backdrop in your project. Click on that column to open the Backdrops Tab. Here you can choose a new backdrop from the library or create your own. Backdrops can also be programmed to interact with the characters, objects, or users.

WORD TO KNOW

backdrop: a design that can be applied to the stage on the Scratch UI.

Stage coordinates: Scratch uses geometry to help your sprites find their way around the stage. One helpful backdrop, the xy grid, divides the stage using a system of crossed lines. The horizontal line that passes through the middle of the stage is the x-axis.

The x-axis is similar to a number line because there is a zero at the center and it counts to 240 on the right and to -240 on the left. The vertical line that passes through the middle of the stage is the y-axis. It’s numbers go to 180 at the top and -180 at the bottom.

Every point on the stage where these lines cross can be identified by a pair of numbers. The first number shows where it is along the x-axis and the second number shows where it is along the y-axis. These numbers are called the xy coordinates.

WORD TO KNOW

geometry: a branch of mathematics that deals with points, lines, and shapes and where they are in space.

horizontal: going straight across from side to side.

x-axis: the horizontal line on a graph that passes through the center point (0,0). Points are measured by how far to the left or right of the y-axis they are.

vertical: going straight up and down.

y-axis: the vertical line on a graph that passes through the center point (0,0). Points are measured by how far above or below the x-axis they are.

xy coordinates: a pair of numbers written like this (x,y) that tell where a point is on a graph, measured from the x-axis and y-axis.

For example, the center of the stage is shown as (0,0). Move three lines to the right and two lines down and you are at (3,-2). You can always see the coordinates of any spot on the stage by placing your mouse over it and reading the x and y numbers shown at the bottom right of the stage. The grid helps you plan out the movements of your sprites.

Sprite coordinates: Sprites have their own personal coordinates that move around with them. When you first place a sprite on the stage and tell a sprite to move, it will go forward, meaning left to right, unless told otherwise. To make it move in a different direction, point it in that direction by giving it the coordinates it should face in degrees.

WORD TO KNOW

degree: a measurement used for angles and circles. A circle is divided into 360 degrees.

To understand how it works, imagine the sprite is in the exact center of a big square. Now imagine a horizontal line and a vertical line to divide the big square into four smaller squares.

Each corner of a square forms an angle measuring 90 degrees. If 0 points up, 90 degrees points to the right along the edges of the squares to the sprite’s right. Directions to the left of the vertical line are indicated by negative numbers. So -90 degrees points to the left. To get the measurement for straight down, you add 90 and 90 to get 180 degrees.

Blocks and scripts: In Scratch, programs are called scripts, and they go in the Scripts Area on the right of the screen. All the scripts you write will be connected to either a sprite or a backdrop.

You can even make a blank backdrop or an invisible sprite and still connect code to it.

When you click on a sprite or a backdrop, the programming that goes with it is displayed in the Scripts Area. Scripts are made by creating stacks of blocks. You can find them in the Blocks Palette column between the stage and the Scripts Area.

Blocks are color-coded according to type—Motion, Looks, Sound, Pen, Data, Events, Control, Sensing, and Operators. They also come in different shapes, depending on their use.

WORD TO KNOW

script: the name for a computer program that a user can write in Scratch.

block: a puzzle-piece shape that is used to create code in Scratch.

To make a script, click on the category you’d like to use, choose the block you want, and drag-and-drop it into the Scripts Area with your mouse.

Stack the blocks from top to bottom in the order you want them to run. Once stacked, blocks stick together.

HOW TO CONTROL BLOCKS AND SCRIPTS

To remove a block from the script, pull it away from below. Grabbing a stack of blocks from above moves the entire stack.

To delete a block, use the scissors icon in the Sprites toolbar or drag it back into the Blocks Palette.

Each sprite or background can have several scripts running at the same time. Breaking the programming into smaller chunks makes it easier to write and debug.

If you have several separate scripts floating around the space and want to make them neater, right-click in the Scripts Area. A box will pop up that gives you the choice to Clean Up the area.

To document your code in Scratch, right-click in the Scripts Area and choose Comment. A little yellow box will appear where you can type in some text. Comments make the script run more slowly, so use them only where necessary.

Tabs: Above the Blocks Palette you’ll find three tabs. The first is the Scripts Tab, which shows you the blocks. The middle tab changes depending on whether you have selected a sprite or a backdrop thumbnail. If you select one of the sprites, the Costume Tab will appear.

WORD TO KNOW

thumbnail: a small copy of an image on a computer, usually linked to the full-sized version.

Open it to see what costumes are available for that sprite, to choose a new costume, or to change the way a costume looks. If you have selected the backdrop thumbnail, the Backdrop Tab will appear, which works the same way.

The last tab opens up the Sound Palette. That lets you choose a new sound for your sprite or backdrop, and edit the sound you have selected.

Start: To run a Scratch program, you usually click on a green flag. The red stop sign shape ends it. But you can program Scratch to respond to clicks on other objects, different colors, or different sounds. You can also make it respond when a particular key is pressed on the keyboard. You can give players directions for using your game on a backdrop or in the description on the project page. This is the page other people see when they first go to your project.

Help: Scratch offers many ways to find help about all the things you can do with the program. You can see the help menu by clicking on the tiny question mark in the upper right-hand corner. The help menu contains animated guides to help you get started.

BONUS POINTS

Redstone is a material that transmits energy, similar to electrical wires. You can build switches with redstone that turn on and off under certain conditions to program in Minecraft!

Another way to get help is to right-click on any block to bring up information on how it works.

The Scratch Help Page, which can be found at scratch.mit.edu/ help, has more links, guides, and video tutorials. You can also go to the Scratch Wiki, which can be found at wiki.scratch.mit.edu/ wiki. The Scratch Wiki is largely written by Scratch users and is a good place to search when you are looking for answers to specific questions.

WORD TO KNOW

wiki: a free website that allows users to write and edit articles explaining a topic or range of topics.

ESSENTIAL QUESTION

Now it’s time to consider and discuss the Essential Question:

How is programming a computer game like baking cookies?

 

GAME JAM ACTIVITY

DRAW A FLOWCHART FOR A GAME

IDEAS FOR SUPPLIES

game you like to play, such as your memory game from Chapter 3

Every game gives players choices to make and steps to follow. A flowchart is a quick way to show how those options lead to different results. In this activity, you will make a drawing that shows how a game works.

A flowchart uses different shapes to indicate different kinds of steps.

Start and End blocks are oval.

Diamond-shaped Decision blocks mark where a choice is made. These are usually yes/no or true/false questions.

Rectangles indicate where an Action will be performed.

1 Draw a flowchart for a game of your choice that starts with the first move. Include all the possible ways players can move through the game, using the correct shapes. Use arrows to show directions. You might be surprised at how many steps ‘ even a simple game can take from beginning to end!

BONUS POINTS

Mark Engelberg is the inventor of Code Master, a board game that teaches kids programming logic. He says that the one thing everyone should know about coding is that computer programs are made of reusable parts. Functions and loops and the way they can be layered inside one another make programming powerful!

 

SCRATCH CAT DODGE BALL

IDEAS FOR SUPPLIES

computer with access to Scratch

Video games that involve multiple levels, characters, and objects require a lot of planning. But you can build a quick game using tools such as Scratch. In this activity, you will create a very simple game in which players must dash across the screen and ring the bell without getting hit by the ball. Once you’ve got the basic tools and commands mastered, you’ll be on your way to programming your own video game prototypes!

This game requires three sprites that perform some simple roles. Here’s a chart to give you an idea of what they do.

1 Open up Scratch and create a new project. Refer back to the chapter for help if you need it. The Scratch Cat sprite is automatically supplied— it will be called Sprite 1. You can change the name by right-clicking on the image in the Sprite List and clicking “Info” in the menu that appears. You will create three scripts.

One moves the Scratch Cat at the left of the stage when the game starts.

The other two make it move back and forth.

2 Start by building the Scratch Cat. In the Block Palette, click on the dark brown Events category.

Drag and drop when [flag] clicked to the Scripts Area.

Drag and drop when space key pressed into the Scripts Area. Click on the triangle after the word space. Choose right arrow. Repeat with another copy of the same block and set it to left arrow.

Click on the dark blue Motion category.

Drag the block go to x: [ ] go to y: [ ] and snap it to when [flag] clicked.

Under the right arrow block, snap the Motion block that says move [ ] steps. Set the number of steps to 30 by clicking in the box. Do the same for the left arrow block, changing the number to -30.

Stop and test your code by clicking on the green flag. Use the arrow keys to move the Scratch Cat. Which way does it go?

3 To code the soccer ball, click on the little creature in the New Sprite toolbar and open the sprite library. Select the soccer ball. You’ll need to build three separate sections for the soccer ball script.

To tell the ball where to be at the start of the game connect the when [flag] clicked block and a x: [ ] go to y: [ ] motion block as before. Set x to 0 and y to -158.

To make the sprite move up and down, add a point in direction block, click the triangle, and set it to up. The number 0 will appear.

To keep the ball bouncing across the stage, use a loop. Drag a forever block from the Controls category into the Scripts Area, separate from the others. To make a loop, insert the following Motion blocks into the opening of the forever block: change x by [ ] and set it at 1; move [ ] steps set to 10; if on edge, bounce.

4 To make the ball play a Game Over sound if it touches the Scratch Cat, use a conditional statement.

From the Control category, drag an if [ ] then block. The diamond in the center is where you put your condition.

From the Sensing category choose the touching [ ]? block. Click the little triangle and choose the Scratch Cat sprite name.

Drag the Sensing block over the diamond in the Control block until the diamond lights up and then snap it into place.

Drag a stop [ ] block into the opening of the if [ ] then block and set it to all.

From the Sound category choose play sound [ ] until done. The pulldown menu shows any sounds that come with your sprite. Click on the popping sound to select it for that block. The Sound block goes directly above the stop block.

5 Connect all the sections of the soccer ball script. Drag the entire if [ ] then block into the mouth of the forever block and snap it in below the Motion blocks. Snap the entire forever block to the bottom of the stack under the when [flag] clicked block. Test before moving on.

6 To create the bell, find and add the bell sprite to your project.

Start with the when [flag] clicked Events block.

Go to the Control blocks and drag over the wait until [ ] block.

Find the touching [ ] block in the Sensing category, set it to the Scratch Cat sprite, and snap it into the Control block. Add a stop [all] block at the end.

From the Sounds category, insert a play sound [ ] until done block between the Control blocks. It should be set to bell toll.

Test out the bell script alone. If it works, you can test and play the whole game!

 

WRITE A PSEUDOCODE ALGORITHM

IDEAS FOR SUPPLIES

memory game from Chapter 3

In this activity, you will use ordinary English words instead of a programming language to program a memory game.

1 Demonstrate your game as if you were teaching it to someone else. If your game needs more than one player, you can play for all of them. Make notes about every step as you go. Look for patterns of moves that are repeated throughout the game.

2 Write a complete set of instructions in the form of a pseudocode algorithm. Where the same steps are repeated exactly, you can create a loop or a function.

Sample set of instructions.

Turn the cards so the blank backs are facing you.

Mix them up.

Place them face down in four rows of four cards each in front of you (the playing area).

While there are still cards in the playing area:

Pick one card at random and turn it over;

Do the same with a second card.

3 To test your pseudocode, give it to someone who doesn’t know how to play your game and ask him or her to follow your instructions. Watch as they try to play to see if you left out any steps or mixed up the order. Make changes as necessary.

WHERE ARE THE GIRLS?

In 2015, 12-year-old Maddie Messer did a study and found that out of the top 50 endless running iPhone apps with human characters, 98 percent offered boy characters, but only 46 percent had any girl characters at all. And while 90 percent of those games had free boy characters, only 15 percent had free girl characters. On average, adding a female character cost $7.53—even though the games themselves cost less than $1. In the Disney game Temple Run Oz, the only female character offered cost nearly $30! She wrote an article for The Washington Post newspaper and game companies took notice. Temple Run promised to add a free female character. Disney made its female character free as well. And the creators of the game Noodles Now even added a female character named Maddie!