Overview
Expect this unit to take about 30 minutes to 2 hours, depending on how comfortable you are already with HTML and JavaScript. There's no demo for this Unit.
HTML5 gives us a lot of cool potential with online features and reaching an enourmously broad market (billions of people!), but being a relatively young and undersupported platform we don't have as many tools and features (audio, 3D visual, etc) as native game developers.
While this class isn't meant to teach you HTML, CSS or even JavaScript, it's important that we cover some of the basics so it sets the tone of web-related skills going forward.
Depending on your familiarity with web technologies, expect to spend about 30 minutes to 2 hours getting your project steps for this Unit completed.
Lesson 1: Breakdown of an HTML5 page
Since our game is running on a webpage (is a wepage!) we need to cover a few very simple basics about structuring a webpage.
There are a whole host of other, more robust, resources out there for building web-pages. Hopefully this section will be enough of a primer to get you comfortable with creating your own very basic page for a game project. There are three major components for the type of web application we are building:
- HTML code
The main point of entry for the browser. Some sites may use many html pages, or have the server generate one through another language (PHP or templates), but for this project we will only have a single html file as our landing page. A basic web page is structured like this:
<!DOCTYPE HTML> <html> <head> <title>My first game project</title> </head> <body> <div id="game_content"> <p>Hello user! </div> <script src="main.js"></script> </body> </html>
- CSS code
There may be a few moments when we talk about CSS, but overall we will ignore the topic of it and style sheets. A simple way to set the style of a section directly in the HTML is like this:
<body style="background: white; font-family: Helvetica">
You could also create a style sheet, which can set the style for multiple classes of HTML objects, and include it the HTML using the <link> tag.
<!-- Include this within the <head> tag of your html file --> <link href="styles/style.css" rel="stylesheet" type="text/css"/>
/* Create a file called "style/style.css" and start defining styles for different sections of HTML like this */ html, body { padding-left: 10px; padding-bottom: 20px; font-family: 'DINWebProRegular', helvetica, arial, serif; background: url(../images/background.jpg); }
- JavaScript code
JavaScript can be embedded directly in the HTML page, or included throught the <script> tag. We will be creating several different JavaScript files and loading them individually. Note: Code size is pretty important for JavaScript based apps. The user has to download the code so larger files, or the more number of files, can mean a longer load time. But since this is an academic pursuit we aren't going to be too concerned with it for this project.
Including a JavaScript file into our HTML page:
<script src="js_libraries/modernizr.js"></script>
//========================================================================= function set_visibility(id, value) { var e = document.getElementById(id); e.style.display = value; }
Lesson 2: JavaScript primer
"The world's most misunderstood programming language" - Doug Crockford
"JavaScript became the world's biggest programming language, completely independent of its merits" - Doug Crockford
JavaScript has a lot of really cool, awesome stuff but also a whole lot of really awful, dangerous stuff.
If you are new to the language, the best thing I can recommend to you is this book - JavaScript: The Good Parts
You could also sit through this fantastic hour long talk by the author instead http://www.youtube.com/watch?v=hQVTIJBZook. It is totally worth it, there's very few better resources for navigating the funky weirdness of JavaScript!
Be aware of Bad Stuff
- Operators - Always use the triple equal '===' operator to test for equality, and '!==' for testing inequality. The double equal '==' and '!=' operators have weird type conversion rules that are best to avoid.
- Hoisting - unlike the similar scripting language Lua, function and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter. The variable may be declared earlier than you expect, the value you assign to it will still only get assigned when you initially wrote it (in most cases). It is best to declare you variables with the var statement at the top of each scope block.
Be aware of Cool Stuff
- Loose typing, or rather Dynamic typing, means a variable can be assigned a number, then later a string, or function.
var foo = 100; foo = "foo"; foo = function() { };
- Closures
A function that closes-over variables within it's scope, and can be called somewhere else where those variables are not available
A functions returning a functions
Anonymous functions that get passed in as parameters to other functions
Example:
// This outer function is only ran once, immediately var digit_name = function() { // This variable is essentially 'private', unavailable outside of this function but also not created more than once var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'size', 'seven', 'eight', 'nine' ]; // Inner function is what's get assigned to the variable digit_name // It has a reference to the environment in which it was created (context). return function(n) { return names[n]; }; }(); // Notice this syntax. This is how we run a function immediately at it's creation (an example of an anonymous function) alert(digit_name(3)); // This will output the string to the debug console
Lesson 3: Project setup and Development environment
Required 3rd Party JS libraries
Most games rely on a 3rd party library for one thing or another. Examples in games are usually things like physics, or animation, libraries. For web pages that are supposed to run on multiple different browsers, there are a few very common libraries that help ease our lives. We will be using the following libraries: you can download each of these libraries as a JavaScript file and include them in your game engine.
- JQuery - for easy DOM access and AJAX calls to get assets from the server
- Underscore - for handy JS utilities
- Modernizr - script file loading and helping with cross-browser support
- Box2D - an open source library for simulating rigid bodies in 2D, ported over to JavaScript from ActionScript (flash) after being ported from C++
The documentation for each of these libraries are pretty good (a common advantage web developers have over game developers, where good code documentation is usually hard to come by). I will try my best to explain features as we need them. For now, we will start with Modernizr and demonstrate how to load multiple files.
Example of using Modernizr.js to load multiple JavaScript files
// Create an array to store the list of files to load var EngineFiles = [ // Required third-party libraries "js_libraries/jquery-1.8.3.min.js", "js_libraries/underscore-min.js", // Other engine files to go here ]; // A named function that will run immediately. (function loadFiles( ) { // We'll use these variables to track progress var numResourcesLoaded = 0; var totalResources = EngineFiles.length; // Check the documentation to see the format of this function // Basically it takes an array of objects, each object supplying a list // of files to load and callback functions. Modernizr.load([ { load: EngineFiles, callback: function( url, result, key ) { console.log( "Engine File loaded: ", url ); ++numResourcesLoaded; }, complete: function() { console.log( "All Engine Files loaded!"); } } ]); })();
Running and debugging JavaScript in Chrome
For this class, I recommend using Chrome as your development browser, because it has a fantastic set of Developer Tools.
Documentation for Chrome Developer Tools (DevTools)
- Ctrl + Shift + I (Mac: ⌥⌘I) keys to open Developer Tools
- Ctrl + Shift + J (Mac: ⌥⌘J) to open Developer Tools and bring focus to the Console.
Important DevTools features:
- Console output window - you can use the alert() function to print strings and the values of variables
- Breakpoints - halt execution once it hits a specific line of code
- Watch Window - inspect the values of variables that are within scope at the current point of execution
Web hosting
While you can load your html in a browser directly from your hard drive, you are actually limited in features compared to running it on a web server. An example is that you are not allowed to make AJAX calls (requesting assets from the server)
We can use a tool called "mongoose", which is a light-weight application that creates a web server on your local machine. We can point it to our project directory to have it host our game
Download mongoose on Google Code
Optional: Using an Integrated Development Environment
At the very least you are going to need a good text editor.
I use Sublime Text 2, which has a relatively good support for project/file management. It has fantastic plug in support which means you can use JSLint.
A popular solution with my students is called WebStorm. It has a free 30-day trial, and a very inexpensive student license.
Homework: Getting started with a web page
- Create a new directory for your project
- Create a subdirectory for 3rd party libraries, and download the following libraries to put there:
- Download modernizr.js - You can grab a custom build, which allows you to select which features you need and keep your file size down, but for now the latest development version 2.6.2 will be sufficient.
- Download jquery.js - I'll be using Version 1.10.2. You can avoid downloading it by linking to a CDN instead of your own file, but for development it might be helpful to have a copy with your code.
- Download underscore.js - I'll be using version 1.4.4
- Create your HTML Web Page
- Create index.html and give it the following elements:
- a head, title, and body tags
- in the body create a div with an id
- Put a script tag at the end of the body to load modernizr.js
- Create index.html and give it the following elements:
- Create your JavaScript Application
- Create a file called main.js
- Using the modernizr library, write a function that loads both the jquery and underscore libraries you downloaded.
- Output some text to the console.
- In index.html, add a script tag at the end of the body (after loading modernizr.js) to load main.js
- OPTIONAL: Add a CSS file to give your page special formatting.
- You should be able to load this page in your web browser directly.
- Run mongoose.exe and load your page in the web browser though a url such as http://localhost:8080/ (8080 is mongoose default port, your web hosting solution may vary).