Published using Google Docs
After-School Coding Club - Month 1 - Javascript Game tutorial
Updated automatically every 5 minutes

Learning JavaScript by building a text adventure game

*note: this tutorial is a work-in-progress. More content is being added as the course progresses.

Contents

Week 1 - Introduction to programming with JavaScript

Week 2 - Functions and Loops

Week 3 - HTML and JavaScript together

Week 4 - Making a game

Getting Started

Before we actually start creating our game, we need to get our tools all set up. We’ll need two types of tools: something with which to write our programs, and something with which to run or execute our programs. There are lots of different tools you can use to write JavaScript, from basic text editors like Notepad (Windows), TextEdit (Mac), or gedit (Linux). We can also use more advanced text editors (complete with handy features like syntax highlighting and JavaScript linting) such as Sublime Text, Notepad++, and Brackets. Second, we’ll need a tool to actually run our JavaScript. Fortunately, JavaScript runtime environments are built into most web browsers, so we can use Google Chrome, Apple Safari, Mozilla Firefox, or Microsoft Internet Explorer to run our JavaScript programs.

For this tutorial, we’ll be using an online IDE (integrated development environment) called JSFiddle, and the browser Google Chrome.


Week 1 - May 4, 2015

Hello World

As is tradition when using a new software development platform, we’ll get started with one of the simplest possible version of our app: the Hello World program. What does Hello World do? It launches, then displays the text “Hello, world!”. Sorry if you had your hopes up for a personified 3D globe waving an animated greeting to you. What Hello World allows us to do is to confirm that we’ve set everything up properly. If you can’t successfully complete this step, everything after it will be much more difficult. Here’s the code we’ll need to write, it’s a one-liner:

alert('Hello, world!');

When we run this program, we should see a popup window that says “Hello, World!”, like this:

Screenshot 2015-05-22 12.14.56.png

The text that we print out with our alert function is one of JavaScript’s basic data types, called a string. We can also print out numbers (e.g. 5) or Booleans (e.g. true or false).

File status: 1.00-hello-world (JSFiddle, GitHub)

Variables

Ok, we survived Hello World. Everything is working as planned! Directly logging strings is easy, but as our programs become more complex, we may need to change the text in our strings more frequently. To do that, we can borrow a concept from Algebra called variables. You may be used to using variables named x and y in your Algebra class, but with JavaScript, we can create variables with much more descriptive names. Similar to our Algebra variables, the variables in our programs can hold or store different values. Let’s try this out by storing some text, our first name, in a variable called myName:

var myName = 'Nick';

alert(myName);

This will return an alert box that says Nick. We could also store the string value of someone else’s first name, say our friend’s name, in a different variable:

var myFriend = 'Mollie';

alert(myFriend);

Maybe we have more than one friend whose name we’d like to print out. While we have to use the var keyword when we first declare a variable, we don’t have to use it when we change the value of our variable:

myFriend = 'Brian';

alert(myFriend);

Even though we used the same alert function call here, since we changed the value of the myFriend variable, we’ll see a different result. Here, we’ve used date of type string, but we could also store number or Boolean values inside our variables.

File status: 1.01-variables (JSFiddle, GitHub)

Prompt

So far, all the string values that we’ve printed out have been hardcoded into our programs. That means that we, the developer, wrote all the text into our code before we actually ran the program. What if we’d like to have our users enter their own text, and do this once the program is already running? To accomplish this, we can use the prompt function:

var yourName = prompt('What is your name?');

alert(yourName);

In this program, we used the prompt function to ask the user to input a string value. We then stored that string value in a variable called yourName. Finally, we called an alert function that printed out the value of yourName, as it was typed in by our user.

File status: 1.02-prompt (JSFiddle, GitHub)

Escape Character

Sometimes, we need to put text inside our strings that makes use of JavaScript’s special characters. For instance, we’ve been using a set of single quotes (' ') to denote the start and end of our strings. What if we needed to use one of these single quote / apostrophe characters inside of a string? Do do that, we can use a special character, the forward slash (\) to “escape” our special character. Here’s an example of using the forward slash to escape an apostrophe:

var yourName = prompt('What\'s your name?');

alert(yourName);

Now, you might ask, what if we actually needed to use a forward slash inside a string? The double forward slash (\\) will allow us to print out a forward slash character, with the first slash acting as the escape character, and the second being the desired character.

File status: 1.03-escape-character (JSFiddle, GitHub)

If Statement

So far, JavaScript hasn’t done much “computing” for us. Remembering and recalling names is nice, but software can do much more powerful things than that. What if we wanted our program to make a decision for us? That’s where the If Statement comes into play. If a condition evaluates to true, an If Statement will run the code inside its code block. If the condition is not true, the code inside the code block will not be run. Let’s start by comparing the values of myName and yourName:

var myName = 'Nick';

var yourName = prompt('What\'s your name?');

if (yourName == myName) {

        alert('Nice to see you again, ' + yourName);

}

In the program, our user will be prompted to enter a value for their name. If the user’s input is the same as the value of myName (in this case, “Nick”), then the condition yourName == myName evaluates to true, and the code block containing our alert function will run. If the user enters a different name (such as “Joe”, “Mary”, or even “nick” without a capital N), then the condition will evaluate to false, and our code will not run.

File status: 1.04-if-statement (JSFiddle, GitHub)

If / Else Statement

It would be nice to be able to do something else when our condition is not true. This is where the Else statement comes in. Else only works when paired with an If Statement. When the condition for the If Statement is true, the If branch of code will run. When the condition for the If Statement is false, the Else branch of code will run. Never both, always one or the other.

var myName = 'Nick';

var yourName = prompt('What\'s your name?');

if (yourName == myName) {

        alert('Nice to see you again, ' + yourName);

} else {

        alert('Nice to meet you, ' + yourName);

}

In this program, if our user’s input matches the value of myName, we’ll see an alert popup with “Nice to see you again, Nick”. If the user’s input doesn’t match the value of myName (such as “Theresa”), we’ll see an alert popup with “Nice to meet you, Theresa”.

File status: 1.05-if-else-statement (JSFiddle, GitHub)

Adding Else If

When we added the Else statement to our repertoire, we were able to make a decision between A and B. What if we have more than two choices? That’s where the Else If statement comes in. It allows us to make a (practically) unlimited number of branches between our If branch and our Else branch. Here’s how it works:

var myName = 'Nick';

var bestFriend = 'Mollie';

var yourName = prompt('What\'s your name?');

if (yourName == myName) {

        alert('Nice to see you again, ' + myName);

} else if (yourName == bestFriend) {

        alert('Hey there, ' + bestFriend);

} else {

        alert('Nice to meet you, ' + yourName);

}

In this scenario, we have known values for the names of ourselves (myName) and our best friend (bestFriend). We have three options for what we want our user to see, depending on what name they enter:

  1. If the user enters the same value as myName, say “Nice to see you again, [myName]”
  2. If the user enters the same value as bestFriend, say “Hey there, [bestFriend]”
  3. If the user enters anything else, say “Nice to meet you, [yourName]”

If we wanted to add additional options, we could add additional Else If branches between our If and Else statements. We can have many Else If branches, but only one If branch and only one Else branch.

File status: 1.06-else-if (JSFiddle, GitHub)

Our First Basic Game

We’ve now learned enough of the basics of JavaScript to write our first, simple game. This game probably won’t be very fun yet, but there will be a way to win and lose. In our game, we’ll ask the player to choose from three different doors. There’s a different outcome behind each door, but the player won’t know what that is until they select a door. We’ll use prompt() to get input from the player, alert() to notify the player of the outcomes, and an if / else if / else statement to decide which outcome the player will see, based on their input. Here’s what our code looks like:

var doorSelected = prompt('You have come to a room with 3 doors. Which door would you like to open?');

if (doorSelected == '1') {

        alert('You selected door number 1 and ran into a bunch of spikes');

} else if (doorSelected == '2') {

        alert('You selected door number 2 and found Unicorns that ride you off to rainbow land');

} else if (doorSelected == '3') {

        alert('You selected door number 3 and get eaten by tigers that haven\'t eaten in 1000 years');

} else {

        alert('That door number doesn\'t exist. Please enter 1, 2, or 3');

}

Congrats, you just made your first game! There are a few things to notice in the code for our game. First, while we have a room with only three doors, there are four total branches for our if / else if / else statement. This is because we use the else branch to catch any erroneous input, which in this case is any input besides the numbers 1, 2, or 3. For now, we don’t do this in a very sophisticated way (like prompting the player for better input until it satisfies our conditions), but we’ll improve upon that later in the tutorial. Also, notice how we use the backslash (\) as an escape character when needed, here to escape the apostrophe characters used in English word contractions contained in our strings. Finally, as far as gameplay goes, Door 2 is considered a winning outcome (of course, Unicorns and rainbows are good!) and Doors 1 and 3 are considered game-ending, losing outcomes. We’ll build more on this in the next section.

File status: 1.07-basic-game (JSFiddle, GitHub)

A More Complex Game, With Nested If / Else

While our first game did provide our player opportunities to win or lose, it was not a very deep game. There was really only one decision to make: which door in the first room. Most text adventure games have LOTS of rooms and lots of decisions to make. To get a little closer to that, let’s add a second level of questions to our game. Since we determined that Door 2 provided a win option in our game, let’s build a new room inside the Door 2 branch. To do that, we’ll nest another if / else if / else statement inside the Door 2 else if block. When we say “nest”, we mean “put inside” or “encapsulate”. I like to think of Russian Nesting Dolls as an example of this.

Let’s see how this looks in code:

var doorSelected = prompt('You have come to a room with 3 doors. Which door would you like to open?');

if (doorSelected == '1') {

        alert('You selected door number 1 and ran into a bunch of spikes');

} else if (doorSelected == '2') {

        alert('You selected door number 2 and found Unicorns that ride you off to rainbow land');

        var colorSelected = prompt('You have landed in rainbow land. Which color would you like to select?');

        if (colorSelected == 'Pink') {

                alert('You are greeted by a pink pig');

        } else if (colorSelected == 'Yellow') {

                alert('You are greeted by a yellow talking banana');

        } else if (colorSelected == 'Green') {

                alert('You meet a green leprechaun at the end of the rainbow and he gives you a giant hug');

        } else {

                alert('Pick a valid color, like Pink, Yellow, or Green');

        }

} else if (doorSelected == '3') {

        alert('You selected door number 3 and get eaten by tigers that haven\'t eaten in 1000 years');

} else {

        alert('That door number doesn\'t exist. Please enter 1, 2, or 3');

}

Wow, that got messy quickly! While this code provides us with a working game, it’s becoming increasingly tough for another programmer to tell what’s going on in our code. We’re only two questions deep into our game, while a typical text adventure may have hundreds of questions.  In the next section, we’ll look at ways to keep our code simple as our programming tasks become more complex.

File status: 1.08-game-nested (JSFiddle, GitHub)


Week 2 - May 11, 2015

Functions

Last week we started off writing our first line of JavaScript code and continued on until we had our first version of a text adventure game. What progress! Yet, as Week 1 came to a close, our code became a bit...messy. With If Statements nested inside If Statements, it became difficult to discern where a level in our game ended or began. This week, one of our goals is to make our code easier to read and more modular. This will make it easier to make our game more complex (and more fun) as we add new levels and other features to the game.

One of the ways we can simplify our code is through creating Functions. This allows us to take chunks of frequently used code, package it into a smaller container, and sprinkle it around throughout our program. There are two parts of using Functions: the declaration and the call. The function declaration is where we define what the function does, kind of like the process of teaching our dog a new trick. The function call is where we tell our program to actually do what the program describes, like when we tell our dog to “Sit” or “Roll Over”.

First, let’s declare our function:

function myFunction(){

    alert("Hello, world!");

}

Second, we’ll call our function:

myFunction();

When we run this, we should see an alert pop up with “Hello, world!”, but we don’t call the alert directly, we call it by calling myFunction. Similar to Variables, you’ll notice that Functions have their own names. Also, when we’re declaring our Function, we’ll use the keyword function before the Function name. This is similar to how we use the keyword var when declaring a Variable. If we want, we can declare another function:

function aDifferentFunction(){

    alert("This is a different function!");

}

Now we can

//alert("this is not a function");

//myFunction();

var select = prompt("Which function?");

if (select == "1"){

    myFunction();

}

else{

    aDifferentFunction();  

}

function aTimesB(a, b){

    return (a*b);    

}

var a = prompt("What is a?");

var b = prompt("What is b?");

//var c = aTimesB(a,b);

alert("A times B equals " + aTimesB(a,b));

var t = function(){alert("this is an anonymous function");}

Some text

File status: 2.00-title-of-section (JSFiddle, GitHub)

Loops

Some text

        Some code

Some text

File status: 2.02-title-of-section (JSFiddle, GitHub)

https://jsfiddle.net/539us83p/  fizzbuzz

https://jsfiddle.net/1gbvoxp5/  intro to functions

https://jsfiddle.net/tnw22f6o/  basic for loop

https://jsfiddle.net/mk6b5pat/  while loop account manager

Comments

Sometimes, we want to leave messages to ourselves or other programmers within our code. We can do that through something called a comment. Comments are lines of code that don’t do anything. Here’s what a comment looks like:

// This is a comment

This comment takes up its own line. We can also place comments to the right side of our code without affecting the execution of that code:

alert('This will print'); // This comment is just hanging out

Comments are also useful for “commenting out” code that would normally run. Here’s an example of that:

alert('This will print');

// alert('This will NOT print');

The first line will trigger an alert popup. The second line will not do anything. This process of commenting out code can be useful for testing and debugging our programs.

One other type of comment is the multi-line comment. We could put the // indicator at the beginning of several lines, but another option is to place /* */ around an entire block of code.

/* This code is commented out

alert('Nothing to see here');

alert('Move along');

*/

Is the same as:

// This code is commented out

// alert('Nothing to see here');

// alert('Move along');

File status: 1.02-title-of-section (JSFiddle, GitHub)


Week 3 - May 18, 2015

HTML

This week, we’ll be adding some HTML to our project. JavaScript is a programming language that inherits abilities from its host environment. In our case, the host environment is an HTML page on the web. This goes for both our work using JSFiddle, as well as when we’ve hand-coded our work using a text editor like Notepad or Sublime Text.

There are 3 main pieces of any web page that you’re viewing on the internet: Structure, Presentation, and Behavior. The job of HTML is to provide the structure. It guides the layout of different elements like Paragraphs, Headings, Lists, and Images. CSS is in control of the presentation. It defines styles like color, size, and font type. JavaScript provides control of a web page’s behavior. It determines what happens when you click on a button, type text in a text field, or move your mouse cursor a certain way.

JavaScript can interact with HTML using what we call an API, or Application Programming Interface. You could think of this like a set of special doors that you can walk through to enter the HTML house. If you want to get inside the HTML house and move things around, you can’t just run through one of the walls, you have to use the doors. The API has special methods depending on what you want to do. When you go in a different door, you have the ability to change different things.

Before we get started, there is one important setting change you’ll need to make if you’re using JSFiddle: change from the default onLoad to No wrap - in <body>. This has to do with the event lifecycle for our DOM elements. Without this change, you’ll likely get errors in your console like Uncaught ReferenceError: functionName is not defined.

Enough talk. Let’s start writing some HTML. If you’re using JSFiddle, make sure you put this in the HTML section in the upper left-hand pane, rather than in the lower left-hand pane where we’ve been putting our JavaScript code. Here’s the “Hello World” of HTML:

<p>Hello, world!</p>

Now, you should see the text “Hello, world!” show up in JS

DOM Manipulation

Some text

        Some code

Some text

File status: 3.03-change-image (JSFiddle, GitHub)


Week 4 - June 1, 2015

Putting The Pieces Together For A Real Game

Last week, we learned how to combine HTML with our JavaScript skills to make an interactive website. This week, we’re going to add in more of our JavaScript game engine, and a touch of style with CSS.

        Some code

Some text

File status: 1.02-title-of-section (JSFiddle, GitHub)

Section Title

Some text

        Some code

Some text

File status: 1.02-title-of-section (JSFiddle, GitHub)


Next Steps

Now that you’ve learned the basics of programming, JavaScript, and HTML, where would you like to go next?

Lessons Learned

Continued Learning

Notes

  1. This content was designed for a 6-hour course, delivered over 4 weeks.
  2. The intended audience is comfortable typing 20+ WPM (I type 60+), is familiar with navigating documents / folders on a desktop operating system.
  3. Some HTML and CSS experience is helpful in extending beyond this lesson, but is not required.
  4. The best way to learn is to teach others. Our TAs are here to help, but often the best person to answer a question for you is the person sitting next to you who just successfully completed the same task.

Help

Sometimes, things don’t work as we expect them to. Here’s some help to get us through those issues:

Outline

  1. All JS. Use prompt, while loop, if statements to make basic game. Play some Zork.
  1. Hello world
  2. Alert, Log
  3. Create variables
  4. Prompt
  5. If / Else
  6. Else If
  7. Basic game with number prompts
  8. Nested If Statements
  9. Code end of Week 1: http://jsfiddle.net/nicksuch/5o0Lmmro/7/
  1. While Loops and Functions
  1. Pre-reading: http://www.w3schools.com/js/js_functions.asp
  2. Review last week’s progress
  3. Functions
  4. For Loops
  5. Modulus Operator
  6. FizzBuzz challenge
  7. While Loops
  8. Arrays
  9. Opt: Sublime Text & local dev environment
  10. Opt: Objects
  1. Some HTML. Get JS to interact with DOM.
  1. Review JS learnings
  2. Hello world in HTML
  3. Paragraphs
  4. Buttons to change HTML
  5. Prompts to interact with HTML
  6. Use Text Editor (alternative to JS Fiddle)
  1. Add CSS. Add some images. Use Forms with HTML. Start with textfield. Add buttons.
  1. Review JS, HTML

References: Code, Design

Inspiration