CS4344 Networked and Mobile Games
Lecture 4: JavaScript and Pong
Guest Lecture – Davin Choo
Javascript
Overview
• JavaScript is case sensitive.
• Extra white spaces are ignored.
• Delimited with semi-colon ;
• // for single lined comments; /* */ for multiple lined comments
• Convention:
o Class names start with a capitalized letter
o Variables and function names start with a lowercased letter
Variables
• JavaScript variables have implicit type (i.e. types will be inferred)
• Declared with var (Refer to Warnings)
e.g. var x = 1;
• Access to variables are according to lexical scoping
Primitives
• Use typeof x to check type of x
• Undefined, Null, Number, String, Boolean, Objects, etc.
Objects
• Prototypical (Refer to Other references and links)
• Associative: key-value paired
• Example of an object with 2 attributes
var obj = {
attribute1 : value1,
attribute2 : value2
};
• Can access attributes in objects via square brackets and double
quotes([“attribute”]) or a dot (.attribute)
o Do note that the dot access only works if the attribute is properly
named (i.e. starts with underscore, dollar sign or a letter)
• Attempts to modify a missing attribute will end up adding it as a new entry in
the object
Arrays
• A special kind of JavaScript object
• Example of a 3x3 array
var matrixArr = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
];
• Has useful methods in its prototype chain:
reverse(), join(), slice(), pop(), push(), etc
Functions
• A special kind of JavaScript object
• JavaScript functions are first class
(i.e. you can assign and refer to them with a variable)
• Arguments
o Extra parameters are ignored
o Missing parameters are replaced with undefined
o Access/Refer to arguments with arguments[index]
var fn = function() {
return arguments[1];
}
fn(1);
// Undefined
fn(1, 2);
// 2
Object-Oriented Programming
• JavaScript classes are implemented via functions
• Regardless of access type of variables/methods (public, private, etc.), we:
o Anyone can view the JavaScript code because it’s client-side code
o We can do a “wrap-around” on our execution code to prevent anyone
from meddling with our running code
• 2 main methods of doing OOP
o Method 1
(Proper information hiding, similar to Java)
var NewClass = function() {
var privateMember = 10;
this.publicMember = 20;
var privateMethod = function() {
}
this.priviledgedMethod = function() {
}
}
NewClass.staticMember = 30;
NewClass.prototype.publicMethod = function() {
}
o
// Running code
var newObj = new NewClass();
Method 2
(Information hiding done via “wrap-around”.
Because we put our running code in an anonymous function and run
it, no one can reference/access it)
var NewClass = function() {
// Access types don’t really matter here
}
// Running code
(function() {
var newObj = new NewClass();
})();
// newObj cannot be referenced here, outside the anonymous function
•
Comparison of the 2 methods
o Method 1: More alike to what you already know about OOP
o Method 2: Feels a little “hack-ish”, but is required if you intend to do
proper inheritance
Inheritance
• There is no proper implementation of “protected” access type in JavaScript
• If you are to do inheritance, the easiest way is to:
o Use Method 2
o Make everything public (NOT privileged), i.e. via “.prototype.”
o Use the prototype chain to do inheritance overriding etc.
• Example code
var ParentClass = function() {
this.chat = “hihi”;
}
ParentClass.prototype.talk = function() {
console.log(this.chat);
}
ParentClass.prototype.talk2 = function() {
console.log(this.chat);
}
var ChildClass = function() {}
// Extending the parent class - Set it directly above itself in the prototype chain
ChildClass.prototype = new ParentClass();
// Overwrite
ChildClass.prototype.talk = function() {
console.log(“child”);
}
ChildClass.prototype.supertalk = function() {
// Access and prepend “super” on each call through prototype
this.chat = “super” + this.chat;
this.talk2();
}
// Running code
(function() {
var parent = new ParentClass();
parent.talk(); // hihi
parent.talk2(); // hihi
var kid = new ChildClass();
kid.talk(); // child
kid.talk2(); // hihi Accessed through prototype
kid.supertalk(); // superhihi
kid.talk2(); // superhihi Accessed through prototype
kid.supertalk(); // supersuperhihi
}) ();
Warnings
• No tail recursion optimization
o Use while loops to simulate (if you need efficient recursion)
• ‘ ’ and “ ”
o Both inverted commas and double quotes are valid for strings
o You can embed them up to 1 level
console.log(“Hello ‘world’!”); // Hello ‘world’
• == vs. === (as well as != and !==)
o == will attempt to convert the compared values to the same type
before comparing
o === will compare without attempting to convert
o Try:
0 == ”” // True. Which is wrong!
0 === “” // False. As expected
• Global declaration
o If var does no precedes a variable declaration (e.g. x = 1;), the
variable becomes a global variable and is accessible anywhere
• Semicolon insertion
o JavaScript is “helpful” by helping you append semicolons at the end of
the line if you have forgotten to do so
o AVOID this at all cost. Add the semicolons yourself
o Consider (from http://en.wikipedia.org/wiki/JavaScript_syntax):
return
a + b;
// Returns undefined. Treated as:
//
return;
//
a + b;
But:
a = b + c
(d + e).foo()
// Treated as:
//
a = b + c(d + e).foo();
Node.js & Socket.io
How to use
Installation
• http://nodejs.org/download/
• Version v0.8.8
• Download the appropriate one based on your Operating System
• If node.js has been upgraded beyond v0.8.8, drop a comment on the module
blog. I will send the installation files (.msi, .pkg, and .tar.gz) for v0.8.8 to
everyone via email, IVLE or something.
Useful libraries (Recommendations from Michael Yong)
• DOM Manipulation
o jQuery
http://jquery.com
Very popular
o Zepto.js
http://zeptojs.com
Similar to jQuery but targeted at webkit. Mobile, and much
more lightweight
• MV* (these libraries are used to give structure to front end code)
o Backbone.js
http://backbonejs.org
Under 1k lines of code. Used by LinkedIn, Foursquare, etc.
Assumes very little
o Ember.js
http://emberjs.com
Formerly sproutcore. Huge. Assumes a lot. Popular too.
o Angularjs
http://angularjs.org
By Google
• Backend
o Express
http://expressjs.com
Framework for web stuff (like Sinatra for ruby)
• Check out: https://npmjs.org
o Repository for node.js modules
o Shows most popular libraries
Client-side
Things to do
• Include socket.io
http://server_name:server_port/socket.io/socket.io.js
• Create a socket and connect it to the server
socket = io.connect(http://server_name:server_port);
• Set up socket event handlers
socket.on(“event”, function() { });
Server-side
Things to do
• Run the server
node server_name.js (in Terminal)
sudo node server_name.js (for restricted ports)
For your purposes, just use Port 8000
• Open a port and listen to it
io = require(‘socket.io’).listen(port_number);
// Note: io is a defined object in socket.io.
// Do not overwrite it or attempt to do “var io”
• Set up socket event handlers
io.sockets.on(‘connection’, function(socket) {
// Code to do stuff once connection is made
// Other event handlers go here
socket.on(‘event’, function() { });
}
Events
• Standard
o The full list is available at the Socket.io wiki page:
https://github.com/LearnBoost/socket.io/wiki/Exposed-events
• User-defined
o Any string but avoid those standard events
• What you really need (besides user-defined events)
o Server
connection (to know that a client has connected)
disconnect (to know that a client has disconnected)
o Client
connect (to know that you have connected to server)
disconnect (to know that you have disconnected from server)
Other references and links
(Really, really useful references are bolded)
[Book] Javascript: The Good Parts (Crockford, 2008)
[Video] JavaScript: The Good Parts (Crockford at a GoogleTechTalk in 2009)
http://www.youtube.com/watch?v=hQVTIJBZook (1hr 3min 47sec)
[Website] JavaScript tutorial:
http://www.w3schools.com/js/default.asp
[Website] Intro to syntax:
http://en.wikipedia.org/wiki/JavaScript_syntax
[Website] Guide to some JavaScript naming conventions:
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
[Website] Guide to prototypes
http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-youneed-to-know/
[Video] Introduction to Node.js with Ryan Dahl (1hr 6min 34sec)
http://www.youtube.com/watch?v=jo_B4LTHi3I
[Screencast] Introduction to Node.js (22min 28sec)
http://net.tutsplus.com/tutorials/javascript-ajax/this-time-youll-learn-node-js/
[Website] Socket.io Homepage
http://socket.io
[Website] HTML5 Canvas tutorial
http://billmill.org/static/canvastutorial/
[Website] Skeletal Pong Code (Download or fork)
https://github.com/SozoS/2PP
© Copyright 2026 Paperzz