GameDev1:Functions
If your location has enough mentors that understand the following material and are comfortable with explaining it to the students, we recommend each mentor do this separately with a pair of students. Otherwise, you'll need to choose one mentor to lead the class in this activity. It is also highly recommended that you print this page out, or load it on your mobile device. |
We deviate from the book a bit in order to demonstrate the power of functions, but students can use the books to write the first few lines of code. From then on, we'll just be making slight modifications to the existing code.
During this discussion, you will need to pause at various times to make sure the students are following along. At each stage in the discussion, make sure everyone's caught up by asking students to raise their hands. If other students are still catching up, try filling in the time by asking those students questions to test their knowledge.
Contents
Starting code
Instruct students to clone a new workspace using gamingjs/functions-practice as a template (you may need to tell students to close the preferences tab once their workspace is cloned). Their workspaces should have the following code:
var log = document.createElement('div');
log.style.height = '75px';
log.style.width = '450px';
log.style.overflow = 'auto';
log.style.border = '1px solid #666';
log.style.backgroundColor = '#ccc';
log.style.padding = '8px';
log.style.position = 'absolute';
log.style.bottom = '10px';
log.style.right = '20px';
document.body.appendChild(log);
Briefly explain what this code does:
The code you see in your workspace uses JavaScript to create an HTML
<div>
element and add CSS styles to it (some of you who took our web developer course might recognize some of these CSS styles).If you save your code ( Ctrl + S ), you should see a small gray box in the lower-right corner.
We're going to use this box to display messages on the screen. Some games (such as Minecraft, for example) use something similar to show chat messages or other notifications to the player.
Log some messages
Tell students to turn to page 50 in their books and write the first 3 lines of code there. Explain that the messages we're logging are contained in quotes after `message.textContent =`. They can change these messages to whatever they want (let them have fun w/ it).
Remember , only type the first 3 lines for now. Raise your hand when you're done.
var message = document.createElement('div');
message.textContent = 'Hello, World!'
log.appendChild(message);
Tell students to check their code to see if it works Let students know they can copy and paste the next two blocks of code:
Now we want to log two more messages. What's an easy way to do this?
(students should suggest copy and paste)
Let's go ahead and copy ( Ctrl + C ) and paste ( Ctrl + V ) those lines to log two different messages.
Remember to save and check to make sure your code runs!
Changing things is a pain
Next we're going to make a change to our messages. Let's say we've decided we want to make our messages italic. To do that, we need to add another line of code just after the first
message.textContent
line.
Write the following code on the whiteboard or on a piece of paper so the students can see what to add:
message.style.fontStyle = 'italic';
Have students check their work by saving and previewing the result. The first log message should be italic. Then ask the students what we need to do to make the other messages italic
Now, save your work, and you should see the first message in italic. What do we need to do to make the rest of our messages italic? Go ahead and copy-and-paste that line to the other two messages.
As students are doing this, explain the following hypothetical:
Now, it's easy enough to just copy-and-paste that line a couple times. But imagine that we've created a huge game, with messages being logged in hundreds of places in our code. We'd have to have to find every single place we log a message and add that line of code to make it italic. What a pain!
Don't Repeat Yourself
Have a student point out what is the same between each function and what is different.
Note that we're repeating ourselves a lot in this code. Can someone tell me the only thing that's different between each block of code? What's the one thing that's changing?
The message itself! Why are we wasting so much time repeating all this other code? As coders, there's a mantra called Don't Repeat Yourself , or DRY . By keeping your code DRY you're making it easier to manage later on.
Remember when you made the trees? What shapes did you use to build tree?
You made four trees, right? Did you have to write the code for the cylinder and the sphere and the colored material four separate times? (No)
What did you use instead?
You used a function !
Functions to the rescue
Tell students to erase everything but the first block of code They should be left with:
var message = document.createElement('div');
message.style.fontStyle = 'italic';
message.textContent = 'Hello, World!'
log.appendChild(message);
Now let's delete everything but the first block of code, and make this into a function.
Next, highlight those 4 lines of code and hit the tab key so that we can indent it over.
Then, above that line, type
function logMessage(message) {
And below those lines, just put a closing curly brace
}
Students should now have code that looks like this (we're intentionally leaving the old message text to make a point later):
function logMessage(message) {
var message = document.createElement('div');
message.style.fontStyle = 'italic';
message.textContent = 'Hello, World!'
log.appendChild(message);
}
Explain function definition vs function call using the recipe/cake analogy:
Now save your code. Why doesn't your log message show?
What you just wrote is your function definition . It's like writing a recipe for baking a cake. We write a recipe to make it easier to follow the same instructions whenever we want to bake a cake. But just writing the recipe by itself isn't enough, we need to actually tell someone to follow the recipe!
In coding, we can "tell" the computer to follow our "recipe" (our function) by writing the function name followed by parentheses and whatever other info it needs to know.
On the next line, write:
logMessage("Hello World!");
That's all you need to do to tell the computer to run those three lines of code! Go ahead and add more log messages:
logMessage("Hello World!");
logMessage("This is really cool.");
logMessage("Functions are great!");
When students run their code, they'll see their messages are all the same. Challenge students to figure out how to fix it.
But wait, something's not right. Can someone tell me why our messages are all the same? What do we need to change to fix this?
Remember that one thing that was different in our code earlier? Well, now we can use the
message
parameter (the part in parentheses. Inside the function definition, replace the message text (and the quotes) with themessage
parameter. This works just like a variable. The value of this variable depends on how we call the function later on.
The function should now look like this:
function logMessage(message) {
var message = document.createElement('div');
message.style.fontStyle = 'italic';
message.textContent = message;
log.appendChild(message);
}
Have students save and run their code to see the results. They should now have different log messages showing.
Show how making changes is now much easier --
Now, what if we need to make another change? What if we wanted to make all the messages red? We just add one line of code below our 'italic' line:
message.style.color = 'red';
Input and Output
Functions are like magic boxes that you can put something into, and it will do all kinds of stuff with whatever input you give it. We just did that with our
logMessage
function.
If our function was the logMessage function, what was our input for that function?
(the answer is
message
)Let's try making a function that takes some input and then returns some output. We want a function that takes a person's name as input, and spits out a sentence as output.
Can someone give me a sentence that would have a person's name in it?
Use this step to explain the parts of a function:
Remember how a function is like a recipe? We need to define our "recipe" to make a sentence using someone's name as input. We start by typing function followed by the name of our function. Let's call it hello . After that, we add parentheses. Inside those parenthesis are the parameters -- this is the input that our function takes.
What parameter does our function need?
The empty function should look like this:
function hello(name) {
}
Now, we need to show how to add strings together. We don't need to go into detail about how data types work -- just explain that when we add text together using the
+
sign, it "smushes" the values together into a single piece of text.
Now let's write the code that spits out the sentence. We need to use the return keyword first to show that we're giving something as output from our function.
Then, we need to "glue" the pieces of text together with our
name
parameter using plus signs. Remember, don't put quotes around the name parameter.
The final function should look something like this:
function hello(name) {
return 'Hello, ' + name + '! You look very pretty today.';
}
Now, show the students how to use this function in combination with their
logMessage
function.
We can now put a
hello()
function call inside alogMessage
function call, like so:
logMessage(hello('President Obama'));
The hello function runs first. It takes our name as input , and produces a sentence as output . That sentence is that used as the input for our
logMessage()
function.
Presentation tips
If you have a whiteboard, it may be useful to draw a diagram on the board of the "function machines" for
logMessage
and
hello()
, with arrows for inputs and outputs, like so: