Gameplay in HTML5: Introduction

Introductions

Instructor: David M. Anderson

Experience

Interests

Student introductions

Experience, interests

Course: Gameplay in HTML5

Course One of Game Development for Mobile and Web

This course: Gameplay in HTML5

  • Client-side programming
  • Single-player games
  • Code organization
  • 2D graphics and animation
  • Input, audio, data storage

Course Two: Server-Based Game Development

  • Server-side programming
  • Communication over network
  • Multi-player games, leader boards
  • Databases
  • Collision detection, physics

Course Three: Mobile Integration, Analytics and Optimization of Games

  • Polishing and optimizing games
  • Instrumentation and analysis
  • Going mobile
  • Integration into social network platforms

Course requirements

  • Attendance: 8 (of 10) classes
  • Homework: 80% average

Resources

Technologies for the Web

HTML5

History

  • HyperText Markup Language
  • HTML first created by Tim Berners-Lee in 1991
  • HTML5 is successor to HTML 4.01 (1999) and XHTML (2000)
  • Web Hypertext Application Technology Working Group (WHATWG) began work on HTML5 in 2004.
  • The World Wide Web Consortium (W3C) abandoned work on XHTML 2 in 2009 and joined with WHATWG on HTML5
  • "HTML5" often means more than just the markup language
  • An evolving standard
  • Ongoing adoption of standard by browser developers (CanIUse.com)

Features

  • Forgiving: Conformity with XML syntax encouraged but not enforced
  • Semantic markup (<nav>, <header>, etc.)
  • Document editing, drag and drop, microdata
  • Graphics with Canvas, SVG, WebGL
  • Multimedia: audio, video
  • Web Storage: beyond cookies
  • WebSockets: beyond Ajax

CSS

  • Cascading Style Sheets
  • Separates content (HTML) from presentation (CSS)
  • Can be responsive to platform (screen vs. print, PC vs. tablet)
  • Latest version is CSS3

JavaScript

Programming language of the Web

  • Developed by Netscape in 1995
  • Soon adopted by Microsoft
  • Supported by all major browsers

Not Java

  • Originally "LiveScript"; renamed, probably for marketing reasons.
  • Some superficial similarities to Java, as well as C/C++ and other curly-brace languages
  • Actually more like Self and Scheme

Objects but no classes

  • JS objects are collections of key-value (a.k.a. name-value) pairs, called properties
  • A.k.a. "associative arrays", "maps" (C++, Java), "dictionaries" (Python), "hash tables" (Common Lisp), "hashes" (Perl, Ruby), "tables" (Lua)
  • Example:
    var brother =
    {
        first_name: "Groucho",
        last_name: "Marx",
        dob: {
                day: 2,
                month: 10,
                year: 1890
             },
        saySomethingFunny: function()
                           {
                                return "Time flies like an arrow; fruit flies like a banana.";
                           }
    }
    
    var lname = brother[ "last_name" ];
    var birthYear = brother.dob.year;
    var other = brother.nick_name; //undefined
    other = brother.nick_name || "Groucho";
    brother[ "nick_name" ] = "Groucho";
    brother.first_name = 'Julius';
    brother.saySomethingFunny( );
    delete brother.last_name;
                    
  • Constructor functions and prototypes provide for inheritance of one object's properties by another and for code reuse

Functions are first-class objects

They can be assigned to variables, passed as parameters to other functions, defined within other functions, and returned from functions.
Chapter 4 in JavaScript: the Good Parts and in JavaScript Patterns explain their many uses.

Best practices & patterns

JavaScript has good parts and bad parts

It was developed by some very smart people, but in a hurry, and with so much code already written for it (some good, some not), fixing the bad parts would break too much. We just have to avoid them.

Always declare variables with var

JavaScript allows a = 4 without ever mentioning a before, but then a becomes a global variable.
So always write var a = 4.

Do not pollute the global namespace

  • Variables and functions declared outside of functions are global.
  • Declare one global object with a unique name and make everything else a property of that object.

Declare all function variables in a single var statement

Instead of
function foo( )
{
    var a = 1;
    for ( var i = 0; i < 10; ++i )
    {
        var b = a + i;
        console.log( b );
    }
}
              
do this
function foo( )
{
    var a = 1,
        i,
        b;
    for ( i = 0; i < 10; ++i )
    {
        b = a + i;
        console.log( b );
    }
}
              
This avoids surprises, because JS "hoists" all variables to the top of a function anyway, and their scope is the entire function, regardless of where you declare them.

In for loops, avoid repeatedly evaluating limits

Instead of
var i;
for ( i = 0; i < list.length; ++i ) ...
              
do this
var i, lim;
for ( i = 0, lim = list.length; i < lim; ++i ) ...
              

Use new judiciously and carefully, if at all

"Constructor" functions can give the illusion of classes and can make code needlessly complicated.
But, especially with prototypes, they can be useful, so they are worth studying. See Chapters 3 and 6 of JavaScript Patterns for details.

Be aware of "truthiness"

false, null, undefined, '' (empty string), 0 (zero), and NaN (not a number) are all "falsy".
All other values are "truthy".
if, while, and for decide based on truthiness.

Learn to use regular expressions

Regular expressions are a powerful way to describe patterns in strings for searching text. JavaScript offers built-in support for them.

Some gotchas

Beware of implicit semicolon insertion
JavaScript will "helpfully" end a line for you if you forget a semicolon. It does this if the line already makes sense by itself. This can lead to trouble.
Example:
To avoid this:
function foo( )
{
    var message = "Watch" //JS inserts a semicolon here!
        + " out"
    return //JS inserts a semicolon here!
    {
        status: true
    }
}
                
Do this:
function foo( )
{
    var message = "Watch" +
        " out";
    return {
        status: true
    };
}
                
Avoid ==
= is for assignment.
=== tests for equality. (!== tests for inequality.)
== and != coerce type conversions, leading to unexpected results.
typeof( null ) is 'object'
So instead of
if ( typeof( foo ) === 'object' ) ...                    
                
check for null first:
if ( foo && (typeof( foo ) === 'object') ) ...                    
                
Use the radix parameter with parseInt
parseInt( "010" ) returns 8.
Unless that is what you want, use parseInt( "010", 10 ).
NaN === NaN is false
Use isNaN().
eval() is evil
It has serious security issues and is rarely, if ever, needed.
Use, e.g., JSON.parse() instead.

Web development tools

Text editor

Choose a good one and learn it well. Wikipedia has a comparision of text editors.
Some considerations:
  • Editing and file-handling features
  • Extensibility and customizability
  • Cross-platform availability and longevity
  • License (consider open source)
(I use GNU Emacs.)

Command line

Get comfortable working at a command prompt (a.k.a. "terminal", "console") with command-line tools. It is often the best way to work with files and other aspects of your operating system. On many Web servers it is your only option.
Windows users should consider Cygwin and/or GnuWin.
A few useful Unix commands are:
  • cd
  • ls [-l]
  • cp
  • mv
  • ln -s
  • less
  • diff
  • grep
  • tar -czvf and tar -xzvf

Browsers

Determine which browsers you will support and test on as many as possible. This may involved compromises with Marketing. If they insist on old versions of Internet Explorer, push back. IE will break your heart.

Browser debuggers

Most modern browsers feature built-in or easily installed debugging and analysis tools.
  • Chrome: Ctrl-Shift-i
  • Firefox: Install FireBug plug-in
  • IE: F12
Features include
  • Setting breakpoints and examining JS variables
  • Exploring the DOM and examining style settings of elements
  • JS programs can output data using console.out.
  • You can execute JS code from the console.
  • Tracking network activity: what resources fail to load or take a long time? What was sent and received in an Ajax call?

JavaScript libraries

jQuery

  • jquery.com
  • Smooths over many browser differences
  • Select DOM elements using CSS-like syntax.
    • document.getElementsByTagName( "a" ) becomes $( "a" )
    • document.getElementById( "theId" ) becomes $( "#theId" )
    • $( "#menuDiv button.active" ) returns the buttons with class "active" within the element with ID "menuDiv"
    This feature is available by itself as Sizzle.
  • Provides functions for manipulating elements (setting attributes, showing and hiding, animating effects, etc.)
  • Simplifies event handling
  • Plug-ins available.
    This page uses the Accordion widget in jQuery-UI.
  • But jQuery is too large for mobile use and much of its code is just to fix Internet Explorer.
    For proper browsers, including mobile, we can use Zepto (zeptojs.com) instead.

Modernizr

  • modernizr.com
  • Includes YepNope, which (conditionally) loads JavaScript files asynchronously.
  • Determines what features the browser supports, allowing for work-arounds or graceful failure.
  • Work-arounds might involve completely different approaches (DHTML instead of Canvas), or "Polyfills", which "patch" the browser so it acquires an equivalent feature.

Version control

  • Keeps an organized history of your work on a file or project
  • Essential when working with others, but highly useful even on solo projects
  • Git is great: distributed, works whether on- or off-line, fast and lightweight.
  • Git even works well with Subversion, a modern but more traditional, centralized VCS, and others.
  • Mercurial is another fine distributed VCS.
  • If you keep your Git archive on your workstation, don't forget to back it up regularly!

Web server

  • Not required for this course. You can develop without one.
  • But if your Web app needs data from a database or similar services, or is for multiple players, you need a server.
  • And if you want other people to play your game, you need a public server to serve it.
  • Web servers include Apache, nginx, lighttpd, and Microsoft IIS.
  • Server-side development is covered in Course Two of this program.

Homework #1

http://EpsilonDelta.us/UW_GameplayHTML5/Homework/Homework_1.html