Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
22. June 2012

 

In this tutorial we are now going to implement a web app end to end using YUI and hosted in Node.  It isn’t actually going to do anything much, but it will illustrate everything you need to create a client and server in JavaScript using YUI App and Node.  Over time we will add more bells and whistles, but there is actually everything you need here to create a full functioning web application.

 

After looking in to it a little closer, YUI is incredibly well documented, but actually implementing YUI App Framework in a real world environment there are gaps of information missing.  Generally all you are going to find is samples with a gigantic HTML files where all of the script is located in a single file, which obviously isn’t good form nor very maintainable.  Unfortunately, when you actually set about splitting your YUI App into separate files and templates, you are completely on your own!  In fact, this tutorial may in fact be the first one on the subject on the internet, I certainly couldn’t find one. 

 

That said, there are still some great resources I referred to over and over well figuring this stuff out.  First and foremost, was the App Framework link I posted earlier.  It effectively illustrates using models and views, just not how to organize them across files in a complex project.  The GitHub contributor app was another great sample, but it again, was effectively one giant HTML file.  Finally there is the photosnear.me application’s source code up on GitHub.  It is a full YUI App/NodeJS sample and is certainly worth reading, but as an example for people learning it is frankly a bit too clever.  Plus it renders templates out using Node, something I wanted to avoid.

 

Alright, lets do a quick overview of how program flow works, don’t worry, it’s actually a lot less complicated than it looks. It is initially over-engineered for what it ends up accomplishing.  However, in the end you basically have the bones of everything you need to create a larger more complex application and a code structure that will scale with your complexity.

 

image

This ( in the image to the left ) is the file hierarchy that we are about to create.  In our root directory are two files, server.js which is our primary NodeJS application, while index.html is the heart of our web application, and where the YUI object is created.

 

Additionally, in a folder named scripts we create a pair of directories models and views.  Models are essentially your applications data, while Views are used to display your data.  Finally within the views folder we have another folder templates which is where our handlebar templates reside.  If you have done any PHP or ASP coding, templates are probably familiar to you already.  Essentially they are used to dynamically insert data into HTML, it will make more sense shortly.

 

We are going to implement one model, person.js, which stores simple information about a Person, and one view person.View.js which is responsible for displaying the Person’s information in the browser, and does so using the person.Template.

 

Now lets actually take a look at how it all works, in the order it is executed.

 

First we need our Node based server, that is going to serve the HTML to the browser ( and do much much more in the future ).  Create a new file named server.js

var express = require('express'), server = express.createServer(); server.use('/scripts', express.static(__dirname + '/scripts')); server.get('/', function (req, res) { res.sendfile('index.html'); }); server.get('*', function (req, res) { res.redirect('/#' + req.url, 302); }); server.listen(process.env.PORT || 3000);

 

Essentially we are creating an express powered server.  The server.use() call enables our server to serve static ( non-dynamic ) files that are located in the /scripts folder and below.  This is where we serve all of our javascript and template files from, if we didn’t add this call, we would either need to manually map each file or you will get a 404 when you attempt to access one of these files on server.  Next set our server up to handle two particular requests.  If you request the root of the website ( / ), we return our index.html file, otherwise we redirect back all other requests back to the root with the url appended after a hash tag.  For more details, read this, although truth is we wont really make much use of it.  Finally we start our server to listen on port 3000 ( or process.env.PORT if hosted ). Amazingly enough, these 9 lines of code provide a full functioning if somewhat basic web server.  At this point, you can open a browser and browse to http://localhost:3000, well, that is, once you start your server.

 

Starting the server is as simple as running node server.js from your command line.  This assumes you have installed NodeJS and added it’s directory to your PATH environment variable, something I highly recommend you do.  Now that we have our working server, lets go about creating our root webpage index.html.

<!DOCTYPE html> <html> <head> <title>GameFromScratch example YUI Framework/NodeJS application</title> </head> <body> <script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script> <script src="/scripts/models/person.js"></script> <script src="/scripts/views/person.View.js"></script> <script> YUI().use('app','personModel','personView', function (Y) { var app = new Y.App({ views: { personView: {type: 'PersonView'} } }); app.route('/', function () { var person = new Y.Person(); this.showView('personView',{model:person}); }); app.render().dispatch(); }); </script> </body> </html>

 

The most important line here is the yui seed call, where we pulling in the yui-min.js, at this point we have access to the YUI libraries.  Next we link in our model and view, we will see shortly.  Ideally you would move these to a separate config file at some point in the future as you add more and more scripts.  These three lines cause all of our javascripts to be included in the project.

 

The YUI().use call is the unique way YUI works, you pass in what parts of YUI library you want to access, and it creates an object with *JUST* that stuff included, in the for of the Y object.  In this case, we want the YUI App class ( and only it! ) from the YUI framework, as well as our two classes personModel and personView, which we will see in a bit more detail shortly.  If you use additional YUI functionality, you need to add them in the use() call.

 

We create our app and configure it to have a single view named personView of type PersonView.  Then we set up our first ( and only route ), for dealing with the URL /.  As you add more functionality you will add more routes.  In the event a user requests the web root, we create a person model.  Next we show the personView and pass it the person model we just created.  This is how you connect data and views together using the YUI app framework.  We then render our app and call dispatch(), which causes our app url to be routed ( which ultimately causes our person model and view to be created. If you aren’t used to Javascript and are used to programming languages that run top down, this might seem a bit alien to you at first.  Don’t worry, you get used to it eventually… mostly).

 

Now lets take a look at our model person.js

YUI.add('personModel',function(Y){ Y.Person = Y.Base.create('person', Y.Model, [],{ getName:function(){ return this.get('name'); } },{ ATTRS:{ name: { value: 'Mike' }, height: { value: 6 }, age: { value:35 } } } ); }, '0.0.1', { requires: ['model']});

 

Remember in index.html in the YUI.use() call where we specified personModel and personView, this is how we made those classes accessible.  By calling YUI.add() we add our class into the YUI namespace, so you can use YUI.use() to included them when needed, like we did in index.html.

 

Next we create our new class, by deriving from Y.Model using Y.Base.create(),  you can find more details here.  We declare a single function getName(), then a series of three attributes, name, height and age.  We set our version level to ‘0.0.1’ chosen completely at random.  When inside a YUI.add() call, we specify our YUI libraries as a array named requires instead of in the YUI.use call.  Otherwise, it works the same as a .use() call, creating a customized Y object consisting of just the classes you need.

 

Now lets take a look at the view, person.View.js

 

YUI.add('personView',function(Y){ Y.PersonView = Y.Base.create('personView', Y.View, [], { initializer:function(){ var that=this, request = Y.io('/scripts/views/templates/person.Template',{ on:{ complete:function(id,response){ var template = Y.Handlebars.compile(response.responseText); that.get('container').setHTML(template(that.get('model').getAttrs(['name','age','height']))); } } }); }, render:function(){ return this; } }); }, '0.0.1', { requires: ['view','io-base','personModel','handlebars']});

 

Like person.js, we use YUI.add() to add personView to YUI for availability elsewhere.  Again we used Y.Base.create(), this time to extend a Y.View.  The rest that follows is all pretty horrifically hacky, but sadly I couldn’t find a better way to do things that way I want. The first horrible hack is that:this, which is simply taking a copy of PersonView’s this pointer, as later during the callback, this will actually represent something completely different.  The next hack was dealing with including Handlebar templates, something no sites that I could findon the web illustrate, because they are using a single HTML file (which makes the task of including a template trivial).

 

The problem is, I wanted to load in a Handlebars template( we will see it in a moment ) in the client  and there are a few existing options, none of which I wanted to deal with.  One option is to create your template programmatically using JavaScript, which seemed even more hacky ( and IMHO, beats the entire point of templating in the first place! ).  You can also precompile your templates, which I will probably do later, but during development this just seemed like an annoyance. The photosnear.me site includes them on the server side using Node, something I wanted to avoid ( it’s a more complex process over all, and doesn’t lend itself well to a tutorial ).  So in the end, I loaded them using Y.io. Y.io allows you to make asynchronous networking requests, which we use to read in our template file person.Template.   Y.io provides a series of callbacks, of which we implement the complete function, read the results as our template, “compile” it using Y.Handlebars, we then “run” the template using template(), passing it the data it will populate itself with.  In our case, our name, age and height attributes from our personModel.  template() after executing contains our fully populated html, which we set to our views container using the setHTML() method.

 

Finally, lets take a look at person.Template, our simple Handlebars template:

<div align=right> <img src="https://www.gamefromscratch.com/image.axd?picture=HTML-5-RPG_thumb_1.png" alt="GameFromScratch HTML5 RPG logo" /> </div> <p><hr /></p> <div> <h2>About {{name}}:</h2> <ul> <li>{{name}} is {{height}} feet tall and {{age}} years of age.</li> </ul> </div>

 

As you can see, Handlebar templates are pretty much just straight HTML files, with small variations to support templating.  As you can see, the values {{name}}, {{height}} and {{age}} are the values that are populated with data.  They will look at the data passed in during the template() call and attempt to find matching values.  This is a very basic example of what Handlebars can do, you can find more details here.

 

Now, if you haven’t done so, run your server using the command node server.js, if you have set node in your PATH.

 

Then, open a web browser and navigate to http://localhost:3000, and if all went well you should see:

 

image

 

 

Granted, not very exciting application, but what you are seeing here is a fully working client/server application with a model, view and templating .  There is one thing that I should point out at this point… in the traditional sense, this isn’t really an MVC application, there is no C(ontroller), or to a certain extent, you could look at the template as the view, and the view as the controller!  But don’t do that, it’s really quite confusing! Smile  Just know, we have accomplished the same goals, our data layer is reusable and testable, our view is disconnected from the logic and data.  Don’t worry, the benefits of all of this work will become clear as we progress, and certainly, once we start adding more complexity.

 

In the near future, we will turn it into a bit more of an application.

 

 

You can download the project source code here.

Programming


21. June 2012

 

A few weeks ago, I mentioned that I might put together an HTML5 Roleplaying game tutorial and inquired how much interest there was in the subject.  There was sufficient interest, so I dove into the subject a little bit closer and came to a bit of a conclusion.  It’s ultimately theHTML-5-RPG tools that make the game in this case.  So, in addition to a game, I would have to create an editor, which is actually where most of the guts would reside.

 

This presented an interesting problem for me, as I’ve done a lot of web development, I mostly worked server side in a traditional language like C# or Java.  For this project, I wanted it to be JavaScript end to end.  I have a few key requirements:

 

  • single language, end to end
  • server based editor, that can be run locally on the client
  • code reuse between game and editor
  • MVC/MVP or MVVM based.  ( if you don’t know these acronyms, don’t worry )
  • event driven
  • rich UI
  • run on a tablet’s browser
  • database and local/remote filesystem support
  • json-based level output, which can be used by clients in any language
  • game entity scripting, probably again, in JavaScript

 

Part of these requirements are driven by personal interest, I have always wanted to try making an MVC based game editor.  MVC means, model-view-controller ( MVP == model view presenter and MVVM == model view viewmodel ) and it is a manner of design for decoupling your data ( your game’s/editor’s objects ) from your view ( your application or webpage ).  There are a number of great advantages to implementing things this way, including testability, maintainability, reuse and perhaps most importantly, it imposes a clean separation of responsibilities between systems.

 

The single language end to end is an easy one.  JavaScript.  While JavaScript is by no means the best designed language in the world, it is a extremely well supported one with a very bright future.  It is increasingly becoming a language that every developer is going to need to know, so why fight the future?  Of course, I could use a slightly higher level implementation like Coffeescript, Closure or Dart, they all ultimately compile down to JavaScript in the end.  That said, one of the biggest reasons I want to use a single language from end to end, is so the most people can follow along without having to know or learn multiple programming languages, so I will probably go with plain Jane JavaScript.

 

Now the whole running on a server and locally, that presented a bit of a trick.  I want people to be able to follow along, and run it from their own computer for their own projects, so offline is a must.  However, I also wanted an editor available for people who are only interested in game side of the equation, which is why I want to host one on my server.  That said, I also don’t want to bog my own servers down too badly.  This presented a bit of a problem, but it was solved soon enough when I started looking into….

 

Database and local/remote file system support.  Behind the scenes, a lot of tools are actually built around a database, whether they realize it or not.  In the end, many tools end up creating their own crude database server around their own file format, or often XML.  In my view, this is awfully close to re-inventing the wheel.  If you are using database like functionality in your tool, use a database!  Fortunately when it comes to JavaScript, there are an absolute ton of options!  From redis, a simple to learn key/value based database and JSON based CouchDB to more traditional databases like MySQL and SQL Server.

 

HTML5 has some options when it comes to local storage, such as well… webStorage.  There are some pretty heavily limitations here, one of the biggies is the lack of support.  Size limits are also rather severe size limitations, in the area of 2.5-5MB, a limit that you will run into extremely quickly.  The alternative to persist these files on the server isn’t really appealing to me, when I am the one paying the server bills! Smile

 

This is where Node comes in.  Node nicely solves just about all of these problems.  Essentially I am going to develop the editor as a node based client/server, where the user has the option of installing the client and server locally, and running it just like any other application.  This gives me access to the local file system and whatever other libraries I need.  However, it also allows me to use the exact same code to provide a hosted version of the editor other users can simply run in their browser.  Essentially Node will act as the host for the DB, as a web server and as the interface between the local machine and the view.

 

Speaking of which, this leaves the view…

 

Again, as I said earlier, the majority of client/server programming I did was built over Java or C#, so the HTML5 / JavaScript approach was new to me, so I had to take a closer look at what options exist.  In short, there are an absolute ton of options… too many in fact.  However, my rather well defined needs narrows things down quite a bit.  In fact, I am down to a pair of options, and would love your opinion on them.

 

 

Option 1

 

jQuery for the UIjquery-logo1

jQueryMobiel for the mobile UI

Node for the backend

CouchDB or redis for the database layer

Express for the server bits

Backbone.js for the um, backbone ( this is where MVC comes in )

Moustache and icanhazjs for the templates

underscore, well, just to make things work

 

 

Option 2

 

YUI for the front end (desktop and mobile), routing, MVC and server bitsyuilib

Node for the backend

CouchDB or redis for the database.

Handlerbars for the templating.

 

 

 

Both have benefits and detriments, especially from the perspective of a tutorial.

 

jQuery is easily the most popular UI library out there, and there is a gigantic amount of support available ( and dozens of books ), with a gigantic community.  Backbone and Moustache are less used, but still well supported.  Unfortunately, this also means introducing a half dozen pieces of tech, a very confusing prospect.  Development on all of these products moves extremely fast, which is a double edges sword.  Finally, and this is highly personal, I hate the look of jquery and underscore code, it feels so… hackey.

 

YUI on the other hand, is from a single vendor, with much less supporting material but very good documentation and a very clean modular design.  More to the point, it is an end to end system so it is very consistent.  However, if something goes wrong the community is much smaller and the supporting materials aren’t as readily available.  Perhaps the biggest downside with YUI is the newness of it.  YUI3 is still in transition away from YUI2, and YUI App ( the YUI equivalent to Backbone ) is young and at times it shows.  From an engineering perspective though, YUI just feels more solid and less like a clever hack.

 

Right now, ease of explanation is winning out, and I am leaning towards using YUI.  Going with on all encompassing library is much easier to configure and explain to readers, so that is a big plus.

 

Any thoughts or opinions on the subject? 

 

Oh, and if this is all sounding extremely confusing, don’t worry, it really isn’t that bad.  The end product should still be a single archive you download and execute with a simple click. 

 

So, over the next few weeks ( or more ), we are going to be going off on a slightly odd tangent here at game from scratch, and crossing over into the world of web app development, I hope many of you find it interesting.  For those that don’t, don’t worry, I will still be publishing game development specific contents and tutorials too!

Design


29. March 2012

 

If you frequent developer related forums, this question probably caused your eyes to roll and the bile to rise in your throat.  People with absolutely no development experience get the game creation bug and of all things want to start with MMOs.  Amazingly enough, there is now a very simple answer…  start here.

 

 

 

 

See, the folks over at Mozilla decided to create an HTML5 MMO to showcase the use of Web Sockets a technology for easy two way communication between a webpage and server ( that isn’t without it’s controversy ).  Additionally it makes use of HTML features including Canvas, local storage, web workers and audio.  Node is used on the server side.  Here is the game in action on my desktop:

 

 

 

image

 

It is graphically simple, but when I played there were 73 other players online and it played fairly flawlessly.  I also fired it up on my Android Phone ( Samsung Galaxy Note ) and here are the results:

 

SC20120329-103613

 

Encouraging….

 

export_03

 

 

And… failure.  It never leaves the connecting to server screen.  Perhaps it’s just me, but for now it simply doesn’t work on my phone.  Will try later on my ICS tablet and iPhone, it may just be launch day jitters so I will try again later.

 

 

 

Failures aside, why am I talking about a primitive browser based MMO on this site?  Well, that’s because Mozilla made the complete source code available on GitHub!

 

 

Here for example is the code from character.js for defining the players character.  As you can see, once you get over the Javascriptisms, it’s quite clean and easy to follow:

 

define(['entity', 'transition', 'timer'], function(Entity, Transition, Timer) { var Character = Entity.extend({ init: function(id, kind) { var self = this; this._super(id, kind); // Position and orientation this.nextGridX = -1; this.nextGridY = -1; this.orientation = Types.Orientations.DOWN; // Speeds this.atkSpeed = 50; this.moveSpeed = 120; this.walkSpeed = 100; this.idleSpeed = 450; this.setAttackRate(800); // Pathing this.movement = new Transition(); this.path = null; this.newDestination = null; this.adjacentTiles = {}; // Combat this.target = null; this.unconfirmedTarget = null; this.attackers = {}; // Health this.hitPoints = 0; this.maxHitPoints = 0; // Modes this.isDead = false; this.attackingMode = false; this.followingMode = false; }, clean: function() { this.forEachAttacker(function(attacker) { attacker.disengage(); attacker.idle(); }); }, setMaxHitPoints: function(hp) { this.maxHitPoints = hp; this.hitPoints = hp; }, setDefaultAnimation: function() { this.idle(); }, hasWeapon: function() { return false; }, hasShadow: function() { return true; }, animate: function(animation, speed, count, onEndCount) { var oriented = ['atk', 'walk', 'idle']; o = this.orientation; if(!(this.currentAnimation && this.currentAnimation.name === "death")) { // don't change animation if the character is dying this.flipSpriteX = false; this.flipSpriteY = false; if(_.indexOf(oriented, animation) >= 0) { animation += "_" + (o === Types.Orientations.LEFT ? "right" : Types.getOrientationAsString(o)); this.flipSpriteX = (this.orientation === Types.Orientations.LEFT) ? true : false; } this.setAnimation(animation, speed, count, onEndCount); } }, turnTo: function(orientation) { this.orientation = orientation; this.idle(); }, setOrientation: function(orientation) { if(orientation) { this.orientation = orientation; } }, idle: function(orientation) { this.setOrientation(orientation); this.animate("idle", this.idleSpeed); }, hit: function(orientation) { this.setOrientation(orientation); this.animate("atk", this.atkSpeed, 1); }, walk: function(orientation) { this.setOrientation(orientation); this.animate("walk", this.walkSpeed); }, moveTo_: function(x, y, callback) { this.destination = { gridX: x, gridY: y }; this.adjacentTiles = {}; if(this.isMoving()) { this.continueTo(x, y); } else { var path = this.requestPathfindingTo(x, y); this.followPath(path); } }, requestPathfindingTo: function(x, y) { if(this.request_path_callback) { return this.request_path_callback(x, y); } else { log.error(this.id + " couldn't request pathfinding to "+x+", "+y); return []; } }, onRequestPath: function(callback) { this.request_path_callback = callback; }, onStartPathing: function(callback) { this.start_pathing_callback = callback; }, onStopPathing: function(callback) { this.stop_pathing_callback = callback; }, followPath: function(path) { if(path.length > 1) { // Length of 1 means the player has clicked on himself this.path = path; this.step = 0; if(this.followingMode) { // following a character path.pop(); } if(this.start_pathing_callback) { this.start_pathing_callback(path); } this.nextStep(); } }, continueTo: function(x, y) { this.newDestination = { x: x, y: y }; }, updateMovement: function() { var p = this.path, i = this.step; if(p[i][0] < p[i-1][0]) { this.walk(Types.Orientations.LEFT); } if(p[i][0] > p[i-1][0]) { this.walk(Types.Orientations.RIGHT); } if(p[i][1] < p[i-1][1]) { this.walk(Types.Orientations.UP); } if(p[i][1] > p[i-1][1]) { this.walk(Types.Orientations.DOWN); } }, updatePositionOnGrid: function() { this.setGridPosition(this.path[this.step][0], this.path[this.step][1]); }, nextStep: function() { var stop = false, x, y, path; if(this.isMoving()) { if(this.before_step_callback) { this.before_step_callback(); } this.updatePositionOnGrid(); this.checkAggro(); if(this.interrupted) { // if Character.stop() has been called stop = true; this.interrupted = false; } else { if(this.hasNextStep()) { this.nextGridX = this.path[this.step+1][0]; this.nextGridY = this.path[this.step+1][1]; } if(this.step_callback) { this.step_callback(); } if(this.hasChangedItsPath()) { x = this.newDestination.x; y = this.newDestination.y; path = this.requestPathfindingTo(x, y); this.newDestination = null; if(path.length < 2) { stop = true; } else { this.followPath(path); } } else if(this.hasNextStep()) { this.step += 1; this.updateMovement(); } else { stop = true; } } if(stop) { // Path is complete or has been interrupted this.path = null; this.idle(); if(this.stop_pathing_callback) { this.stop_pathing_callback(this.gridX, this.gridY); } } } }, onBeforeStep: function(callback) { this.before_step_callback = callback; }, onStep: function(callback) { this.step_callback = callback; }, isMoving: function() { return !(this.path === null); }, hasNextStep: function() { return (this.path.length - 1 > this.step); }, hasChangedItsPath: function() { return !(this.newDestination === null); }, isNear: function(character, distance) { var dx, dy, near = false; dx = Math.abs(this.gridX - character.gridX); dy = Math.abs(this.gridY - character.gridY); if(dx <= distance && dy <= distance) { near = true; } return near; }, onAggro: function(callback) { this.aggro_callback = callback; }, onCheckAggro: function(callback) { this.checkaggro_callback = callback; }, checkAggro: function() { if(this.checkaggro_callback) { this.checkaggro_callback(); } }, aggro: function(character) { if(this.aggro_callback) { this.aggro_callback(character); } }, onDeath: function(callback) { this.death_callback = callback; }, /** * Changes the character's orientation so that it is facing its target. */ lookAtTarget: function() { if(this.target) { this.turnTo(this.getOrientationTo(this.target)); } }, /** * */ go: function(x, y) { if(this.isAttacking()) { this.disengage(); } else if(this.followingMode) { this.followingMode = false; this.target = null; } this.moveTo_(x, y); }, /** * Makes the character follow another one. */ follow: function(entity) { if(entity) { this.followingMode = true; this.moveTo_(entity.gridX, entity.gridY); } }, /** * Stops a moving character. */ stop: function() { if(this.isMoving()) { this.interrupted = true; } }, /** * Makes the character attack another character. Same as Character.follow but with an auto-attacking behavior. * @see Character.follow */ engage: function(character) { this.attackingMode = true; this.setTarget(character); this.follow(character); }, disengage: function() { this.attackingMode = false; this.followingMode = false; this.removeTarget(); }, /** * Returns true if the character is currently attacking. */ isAttacking: function() { return this.attackingMode; }, /** * Gets the right orientation to face a target character from the current position. * Note: * In order to work properly, this method should be used in the following * situation : * S * S T S * S * (where S is self, T is target character) * * @param {Character} character The character to face. * @returns {String} The orientation. */ getOrientationTo: function(character) { if(this.gridX < character.gridX) { return Types.Orientations.RIGHT; } else if(this.gridX > character.gridX) { return Types.Orientations.LEFT; } else if(this.gridY > character.gridY) { return Types.Orientations.UP; } else { return Types.Orientations.DOWN; } }, /** * Returns true if this character is currently attacked by a given character. * @param {Character} character The attacking character. * @returns {Boolean} Whether this is an attacker of this character. */ isAttackedBy: function(character) { return (character.id in this.attackers); }, /** * Registers a character as a current attacker of this one. * @param {Character} character The attacking character. */ addAttacker: function(character) { if(!this.isAttackedBy(character)) { this.attackers[character.id] = character; } else { log.error(this.id + " is already attacked by " + character.id); } }, /** * Unregisters a character as a current attacker of this one. * @param {Character} character The attacking character. */ removeAttacker: function(character) { if(this.isAttackedBy(character)) { delete this.attackers[character.id]; } else { log.error(this.id + " is not attacked by " + character.id); } }, /** * Loops through all the characters currently attacking this one. * @param {Function} callback Function which must accept one character argument. */ forEachAttacker: function(callback) { _.each(this.attackers, function(attacker) { callback(attacker); }); }, /** * Sets this character's attack target. It can only have one target at any time. * @param {Character} character The target character. */ setTarget: function(character) { if(this.target !== character) { // If it's not already set as the target if(this.hasTarget()) { this.removeTarget(); // Cleanly remove the previous one } this.unconfirmedTarget = null; this.target = character; } else { log.debug(character.id + " is already the target of " + this.id); } }, /** * Removes the current attack target. */ removeTarget: function() { var self = this; if(this.target) { if(this.target instanceof Character) { this.target.removeAttacker(this); } this.target = null; } }, /** * Returns true if this character has a current attack target. * @returns {Boolean} Whether this character has a target. */ hasTarget: function() { return !(this.target === null); }, /** * Marks this character as waiting to attack a target. * By sending an "attack" message, the server will later confirm (or not) * that this character is allowed to acquire this target. * * @param {Character} character The target character */ waitToAttack: function(character) { this.unconfirmedTarget = character; }, /** * Returns true if this character is currently waiting to attack the target character. * @param {Character} character The target character. * @returns {Boolean} Whether this character is waiting to attack. */ isWaitingToAttack: function(character) { return (this.unconfirmedTarget === character); }, /** * */ canAttack: function(time) { if(this.canReachTarget() && this.attackCooldown.isOver(time)) { return true; } return false; }, canReachTarget: function() { if(this.hasTarget() && this.isAdjacentNonDiagonal(this.target)) { return true; } return false; }, /** * */ die: function() { this.removeTarget(); this.isDead = true; if(this.death_callback) { this.death_callback(); } }, onHasMoved: function(callback) { this.hasmoved_callback = callback; }, hasMoved: function() { this.setDirty(); if(this.hasmoved_callback) { this.hasmoved_callback(this); } }, hurt: function() { var self = this; this.stopHurting(); this.sprite = this.hurtSprite; this.hurting = setTimeout(this.stopHurting.bind(this), 75); }, stopHurting: function() { this.sprite = this.normalSprite; clearTimeout(this.hurting); }, setAttackRate: function(rate) { this.attackCooldown = new Timer(rate); } }); return Character; });

 

 

 

So now, the next time somebody asks you “I want to create an MMO, now what?”, you have an easy answer.  Send them over to Browser Quest.

 

 

Oh, and for the record… starting your game development career off with an MMO is still a right stupid idea! Smile

 

 

EDIT: As per a comment on reddit, this code doesn’t appear to be released under a specific license yet.  Keep that in mind before using any of this code in your own project.  Of course, this should be rectified shortly.

News


4. August 2011

 

With people looking to get into game development the same questions come up over and over, so I’ve opted to put my thoughts on the subject in one place and to compile a list of resources for new developers.

 

Those questions?

“I want to learn game programming, what language should I use?”

“Should I use an engine, or create my own?”

“What library/tools should I use"?”

“Now what?”

 

I will try to address all of these questions and more in the following post.

 

For those of you that like skipping ahead to the last page in a novel, these links are for you!

 

 

… the C++ question.

 

Let me get the 800lb gorilla out of the way first of all.  C++.  This is one of the most controversial and repetitious questions of all.  New developers hear from other developers that C++ “is what the pros use” and therefore want to use that.  To make matters even worse, people answering the questions are often new developers as well and will recommend what they know thus pushing people to use a language they probably shouldn’t.  Frankly, if you have only ever used a single language, you really shouldn’t be answering these kinds of questions!

 

Alright, back to the whole C++ question.  Should you start learning with C++?  NO.   See, no maybe, no wishy washy answer or caveats, it’s simple, C++ is an epically stupid language to start with.  It’s about the same as starting to learn math by starting with advanced calculus.  Again, dumb.  If you are going to listen to a single piece of advice I give, it’s DO NOT START WITH C++.  I know, of course, that you are going to completely disregard this advice and start with C++, but in 3 or 4 years when you’ve got the scars and trauma from ignoring my advice, I’m going to smugly *tisk tisk* and give you my best “I told you so!”.  I will offer another piece of advice while I am at it… anyone that recommends you start with C++, in the future ignore their advice!

 

Don’t get me wrong, I totally understand why you want to go with C++, I’m just as guilty.  Recently I purchased a set of golf clubs and I’m a horrifically meh golfer, but I got a set of “blades” cause that’s what the pro’s use.  The gotcha?  I’m no pro golfer, and my god did these golf clubs totally ruined my golf game.  Sometimes using what the pros use isn’t the right thing to do.  Alright, off that tangent.

 

Again, these are just my opinions ( and those of the vast majority of people that went down this road themselves! ) and I know you are going to start with C++ anyways, but don’t say I didn’t warn you, because you are making a really stupid mistake.

 

Now, if you did in fact make the decision to go ahead with C++, for the love of all that is holy, DO NOT USE DevC++.  It’s old, unsupported and a vastly inferior choice on every measurable level.  Don’t worry, I’ll cover the options off later.

 

Programming is… programming

 

This one is a bit depressing but completely true.  There is nothing really magical about Game Programming.  It’s programming, pure and simple.  In my professional life, I’ve done game programming, tools programming, desktop app development, mobile phone apps, web development, enterprise development and even created an Internet startup.  Through all of that, the programming, though for vastly different purposes was almost always the same.  Hell, the most advanced ( and difficult ) code I’ve ever written was in Javascript!  Now the biggest difference with game developing… math, yeah, you are going to have to learn math.

 

Anyways… why do I bring this up?  Simple, before you can program games, you need to be able to program.  I know that sounds horribly obvious but you would be amazed by how often people jump straight in to game programming without learning the basics first.  That said, my very first line of code was in the attempt to create a game.  I still remember it to this day:

10 PRINT “WHAT IS YOUR NAME?”

All this really means is, the very first thing you are going to have to learn is the basics of programming.  No worries though, I’ll cover that later too.

 

 

The most important thing is…

 

Do something.  Really, the most important thing you can do is start writing code, start learning, jump in.  All the planning, dreaming and forming of teams is all fun and such, but the most important thing you can do is, um… do.  Jump in, learn, make mistakes, the experience will be invaluable.

 

Your first game won’t be good.  Your second game won’t be much better.  But if you finish a single game, you’ve done better than 95% of people that came before you.  Don’t plan an MMO, it’s way beyond you, even with a team of a few hundred people.  Hell, aiming much higher than Pong is setting yourself up for failure.  Pick something small and execute.  Again, there is a 99.99% chance your game isn’t going to be published, so approach it as the learning experience it is.

 

Nothing frustrates new developers more than the lack of progress.  This is why small, doable goals are so important.  Nothing motivates like success!

 

 

Should I use an engine or create my own?

 

Assuming you are a new developer, frankly, this is a premature question.  Grasp the basics of programming before you even think about using or worse, creating an engine.  Otherwise you are doubling your workload, as you learn both a language AND an engine.  As a new learner, you should be minimizing the number of subjects you need to study at once, as you can quickly get overwhelmed if you try to learn everything at once.

 

Now once you’ve got the gist of things and are starting out creating a new game, this is a very valid question.  One thing to keep in mind, an engine like UDK or Unity are tens or hundreds of thousands of man hours worth of work… do you want to replicate that effort?  Generally, especially for a small developer, you are best off to use an engine, doubly so if trying to make a commercial quality product.

 

That said, if you are looking at it as a learning exercise… have at it!  You will learn a ton of interesting and useful things working on a engine of your own.  Generally, if it’s a learning exercise, it totally makes sense to do things that make no sense!

 

The most important take-away from this section is, if you are new to development, put a bit of time into learning programming, then ask this question later!

 

 

What libraries and tools should I use?

 

This one all comes down to the language you pick.   I’ll break it down by language in just a few minutes.

 

 

What are my language choices?

 

Alright, this one is a bit tricky, as frankly there are literally hundreds of programming languages, but I will cover off the most popular ones.

 

C++ – this is the language you shouldn’t pick, but no doubt will.

 

It’s pros…  you can get close to the metal, it’s the pro choice, lots of 3rd party commercial and free libraries and it is well supported across platforms.

 

It’s cons?  Just about everything else.  It takes 10x as many lines of code to do simple things, it’s like juggling live hand grenades safety wise, it’s compilation process is primitive and unwieldy, it’s syntax is painful, it’s learning curve is steep and it’s standard libraries are awful.

 

Learning difficulty: hard

 

EDIT: –8/16/2011 To be honest, I have been overly hard on C++.  Don’t get me wrong, this does not mean that I am endorsing it for new developers, that is still a seriously bad idea!  However, with the rise of iPhone ( which is Objective-C based, but supports C++ ) and Android ( which is Java based, but also supports C++ ) as gaming platforms, C++’s popularity is on the rise.

 

C -  See C++, which is a superset of C.  There are reasons to use just C and frankly it’s a bit easier to come to grips with, but it is like taking a trip back to the stone ages.

 

Learning difficulty: medium

 

C# – full disclosure, all things being equal, this is the language I go to.  Generally, this is the non-C++ language most people will recommend and for good reason.  C# is a modern derivative of C++, in that it was based on C++ ( and not Java as commonly held ).

 

The pros? EXCELLENT standard libraries. Probably the best on any platform I’ve ever used. So things like working over the network, manipulating strings, loading files, etc… are by far easier than C++.  Oh, and LINQ, generics, anonymous methods and various other “new” language features are pretty great.

 

It’s cons?  Probably the biggest is, it’s tied to Microsoft and that makes many people uncomfortable.  As a result, it’s best implementation is on MS platforms, although it is available on OS/X, iOS, Android and Linux, you do have to jump through a few more hoops outside of MS-land.  Next up, it’s garbage collected, meaning you don’t implicitly allocate memory.  Finally, in some regards, it can be slower than C++, although I think this point is way over blown these days.

 

Learning difficulty: medium

 

Java – Java is a tricky one to write about, because of my C# bias.  I used Java before C# came around and I could see how it was more productive than C++ and appreciated the encompassing libraries, especially as I was moving over from C++ at a time the Standard Template Library was anything but standard…  that said, since C# came along, it feels to me as a superior language in just about every way.

 

The pros?  The ecosystem is massive, the tools and library support are legion.  There are nine ways of doing everything in Java, and the number of free tools ( Eclipse, NetBeans, Ant, etc… ) are truly staggering.  Language wise, it’s much like C#, libraries are much more capable than C++ and the language is much less likely to bite you in the ass if you make a slight mistake.  Also, if you are doing Android development, well until very recently ( with added C++ support ) it was the only game in town.

 

The cons?  Java just has this way of annoying you, of getting in your way because it thinks it knows better than you.  Parts of the language are kludgy, overly verbose and again… just annoying.  In recent years, it has been evolving much less elegantly than C#, so the newer language features seem like half assed poorly implemented ugly step children compared to C# ( and in some regards, C++ ).  Also, Java is the language of academics and enterprises and it shows… so many things are so overwhelmingly OVER engineered as to drive you insane, as I said earlier, there are nine ways of doing everything, but 5 of those ways are outdated, 3 are awful and figuring out what the good choice is, is up to you.  Finally game library selection is pretty limited.

 

Oh, and Oracle own them now… of all the tech companies in the world I would want in charge of my language of choice, Oracle sure as hell wouldn’t be the company I would pick.  For people that think Microsoft are the devil… they don’t know Oracle!  Their throwing around lawsuits left, right and center ( including Google/Android ) would not make me feel good about things.

 

Learning difficulty: medium (*)

(*) – figuring out WHAT to use, from the hundreds of libraries, deprecated features, tools, etc..  is overwhelming and is probably going to be as big a challenge for a new developer as learning the language itself

 

 

Visual Basic – to be honest, since .NET, this language effectively died.  Using VB6 is frankly just too outdated to bother with these days, which is a bit of a shame, as it filled a very nice niche that hasn’t completely been filled.  Now, VB.net is basically C# with a VB’ish skin applied.  I am sure VB.net developers will disagree, but… they are wrong. Winking smile

 

Delphi – was a time I would highly recommend this language, but this haven't progressed well for Delphi. Ironically, the guy that invented C# was the guy behind Delphi.  Support just isn’t there, which is a shame as the language is very friendly to newer developers.

 

LUA/Python/Ruby – In all honesty, I’ve only really dabbled with these 3 languages and while all 3 are ( and commercially have been ) good languages for embedding within a game, only Python really has a really solid game development community built around it, so is probably the best recommendation for new developers.  All 3 languages should definitely be on your radar.  My experience is very limited in all regards, so I don’t really feel comfortable making a suggestion one way or the other.  If you are an advocate of any of these languages and want to write a section on them, send it to me for inclusion!

EDIT: If you are interested in Lua, be sure to check out Battle of the Lua game engines for more details.

 

One big advantage to all three of these languages is you can program them interactively, which means type some code and see a result.  When you are just trying to figure things out, that’s pretty powerful!  Later on in this post, I will mostly just cover Python, the most popular of the three, especially in regards to game programming.  There is also Iron Python which is an implementation of Python on the .NET platform, which means you get all the libraries available to C# and VB.net.

 

C++.NET – On the topic of .NET languages, C++ also made a “special” version of C++, with additional keywords to make it compatible with .NET libraries and a mode that makes memory management automatic.  That said, it was a kind screwy-hackish implementation and nobody really took to it, so you can probably ignore C++.NET completely.  The only real use case I can think of is, if you only know C++ syntax and want to do GUI development with WinForms, this may be the way to go.  That said, that’s a pretty damned minor use case!

 

JavaScript – I don’t know how this little language managed to fit into every niche, but damned if it doesn’t!  Most people think of JavaScript as a web scripting language and easily that is it’s most common use, but this language ends up being used just about everywhere.  It’s worth learning, as it is really everywhere, and although beginning life as a bit of a hack, it has proven itself capable again and again.  Not my favorite language to work in, but not the worse by a long shot!  If a new programming paradigm comes along, you can bet a JavaScript implementation will come along sooner then later!  Given HTML5 and Windows 8, Javascript is only going to get more popular in the future, although I’m not really sure this is a good thing.  Javascript is a prototype based language.  All told, Javascript has pretty good library support when it comes to games, and is one of the languages available when using Unity.

EDIT: If you are interested in JavaScript, be sure to check out the list of JavaScript gamedev libraries as well as my Cocos2D-html tutorials.  I also have a pair of JavaScript book recommendations.

 

Assembly – If you as a beginner pick assembly in this day and age, you did something wrong, extremely wrong! Choosing assembly as your first language makes C++ look like a wonderful choice!  That said, this is about as close to the metal as you can reasonably get.  In this age of i7 quad core processors though, getting close to that metal is a pretty stupid thing to do.  At some point Assembly may become important to you, but I highly doubt it.  Until it does, pretend it doesn’t exist.

 

The Rest  - I hope I didn’t miss your language of choice, as there’s Objective-C, D, F#, CAML, Smalltalk, LISP, Perl, PHP, Haskel, Pascal and a few hundred other languages available.  Many of them are domain or platform specific languages, or have fairly poor game library support.  ObjectiveC is gaining in popularity based on it being the main language of iOS platforms, but outside that world it is virtually unknown and frankly… I hate it.  I don’t recommend against any of these languages, but none are really well suited or very popular for game development.

 

 

But I’m an artist, where do I start?

 

In that case, you should probably start here.  Pick out an application and go with it.  Many of the programs on that list have free/demo versions available.  Also, the GFS list of applications used is mostly full of free applications used to create games.

 

 

So I have this great idea for an MMO…

 

Alright, back to being negative again.  You can’t create an MMO.  You and 10 of your best friends can’t create an MMO, unless of course your 10 friends are all A-list developers and even then frankly you still can’t afford to create an MMO.  Got a few million dollars?  No?  Then drop it, an MMO isn’t the way to go.  Now, some day you may be able to work on a Warcraft killer, but as your first project… well frankly that’s like trying to find a cure for cancer in your high school chemistry class.  Aim lower, much much lower.

 

 

Ok, I’ve decided to go ahead with…

 

 

 

 

C++ is the language for me!

 

Egads, you just wont listen will you…  all right, we all make this mistake when we start out.  If you insist on going the C++ route, learn the language first, using the following recommended tools and libraries.

 

Freely available resources for learning the language ( Books and Tutorials )

 

Once you get a bit more advanced, check out

 

I will fill this area in over time.  Much of the free resources are terrible, or outdated. If you have a good suggestion, email me or comment below and I will add it.

 

Recommended books ( Not free )

 

The C++ Programming Language

This is the book by the language creator himself.  It is considered the language bible of sorts.  It may not be the best book to learn on, but it is a book every C++ programmer should have on their bookshelf.

 

C++ How to Program

Currently in it’s 8th edition, this is a pretty good first book for a programmer to learn with.  It covers pretty much all of the language features and even covers Boost libraries, which is a valuable addition.  Keep in mind, this book, like most introductory texts, does not cover GUI programming of any form.

 

C++ Without Fear: A Beginner's Guide That Makes You Feel Smart (2nd Edition)

This one I recommend with a caveat.  It is probably the single best “conversational” introductory C++ texts out there.  It is very approachable and the pacing is quite good.  Nothing is implemented before it’s explained which is very nice.  That said, some things are wrong or outdated, occasionally teach you “The C way” of doing stuff instead of the C++ way.  Finally, the author recommends DevC++, which is really really really bad.  Those flaw aside, if you find all other texts to dry, confusing or technical, you may want to check this one out.  Again, no GUI coverage and no Boost, but many of the newer language features are covered, plus it spends a couple chapters at the end implementing more full solutions, which is a good thing.

 

Beginning C++Through Game Programming 3rd Edition

No doubt you have seen this title and in your future career as a C++ developer AND a game developer, this sounds about perfect.  It isn’t, but it is not bad.  Lets put this out there right away, this won’t teach you how to program games, but what it will do is teach you to program C++.  As an introduction to C++ text, it’s not as good as the previous two books.  As a game programming text it’s all but useless.  So why am I recommending it?  It’s a decent introduction to C++ programming that uses simple games for all of the demonstrations.  So, instead of fairly abstract or contrived examples you see in other texts, all the examples are game related.  For example, pointers and references are taught by creating a Tic Tac Toe game.  Many people will find this a heck of a lot easier to wrap their head around than many examples in other books.

 

Effective C++

This is not a beginner text.  This is an old text, outdated even as it doesn’t cover the latest C++ standard. Heck, it’s 6 years old!  So why am I recommending it?  Simple, every good C++ programmer owns this book.  Once you grasp the basics of the language, buy this book and it will make you a much better C++ programmer.  Seriously.  Hopefully Scott is working on a 4th edition as we speak.  On the bright side, it’s 6 years old so you should be able to find it cheaply.  In addition to Stroustrup’s book, this is the C++ bible.

 

Tools

 

When it comes to tools, the choices are pretty clear with C++

 

Of the two, I would recommend Visual C++ personally, unless of course you aren’t running Windows.  There are a few other options, but they all require a bit more work or installing plugins, but I will list them for completeness

  •  
    • KDevelop a linux based IDE, heavily copied from Visual Studio in style
    • Eclipse IDE for C++ a cross platform ( Linux, Win, Mac) IDE, mainly for Java, but supports C++
    • XCode Apple’s IDE, supports C++ but is obviously Mac OS only
    • Netbeans for C++  NetBeans is another Java IDE that supports C++.  It’s actually surprisingly new user friendly but now that Oracle is in charge, expect that to end!

 

Well, that’s about it.  If you are working on Windows, I see no reason to use anything but Visual C++ personally.  A number of tutorials out there will recommend Dev C++… DON’T under any circumstances use DevC++, it’s old, unsupported, buggy and has little to no advantages over the other choices.  It was popular at the time because back then, there was no freely available C++ IDE, times have changed.

 

Oh, and just to be thorough, there are also Emacs and Vi(m) which are actually just really powerful text editors that you then call out to the likes of Gcc or the MinGW compiler.  I mostly just mention these for completeness; as if I didn’t some guy with a beard and plaid shirt would no doubt scold me over the omission.  In no way do I recommend a new developer start with any of these items!

 

One last point I think should be made here, your choice of IDE has absolutely no affect on how cross platform your code is!  Code ( properly ) written in Visual C++ can be later compiled for Mac OS and Linux, for example.

 

Gaming related stuff

 

So, you are here for game programming advice and all I’ve talked about is C++, now I will rectify that.  First you need to decide if you are working in 2D or 3D.  Just starting out, I highly recommend sticking to 2D for now ( or stick to console apps until you get the gist of the language ), yet once you decide to make the graphical plunge, there are 3 major ( and a few thousand other! ) 2D graphic libraries out there.  I know this sounds like a cop-out, but all three are equally good, so you can’t really make a mistake here.

 

2D Libraries

 

SDL - SimpleDirect Media Layer

It’s beginner friendly, simple ( relatively ), cross platform, well supported and is used to make commercially shipping products ( like the recently release Dungeons of Dredmore ).  It handles just about every aspect of creating a 2D game, graphics, sound, loading files, networking… you name it.  It is very much a C based library.  You can use it from C++ without effort, just don’t expect any object oriented features.

 

Allegro

This is the library ( and Fastgraf ) I started out using many many many years ago.  It was originally written for the Atari ST and I am simply floored that it is still around and in active development.  That said, it was good then and it is good now.  Interesting trivia point, the guy behind Allegro way back in the early 90s, went on to become one of the main programmers behind XNA.  Anyways, this much like SDL, covers just about everything you would need for 2D game programming. Also like SDL, it’s very much a C library.

 

SFML - Simple and Fast Media Library

The new kid on the block, and frankly, I have zero personal experience with this library.  Like the other two, it handles just about everything you would need to implement a 2D game.  Unlike the others, this is an object oriented library ( C++ ).  A quick look at the classes and it looks like a very modern and clean design. On that level alone, I would probably go this route if I was starting out today.  It is event driven, which is a very handy thing ( and something Allegro is moving towards ), which should make your game structure easier to implement.

 

3D Libraries

 

If you are just learning, you probably shouldn’t be working in 3D right now, yet here are the primary libraries in use today.

 

Open GL

Originally developed by Silicon Graphics in the early 90s, this is the grand daddy of 3D APIs.  It’s biggest advantage is it’s cross platform nature, as OpenGL is everywhere.  This is especially true on mobile devices like Android and iPhone, which both implement a stripped down version of Open GL called OpenGL ES.  You can view the getting started guide here. If you prefer in book form the OpenGL Programming Guide ( Red Book ) has long be viewed as “The OpenGL Bible”, the one book all OpenGL programmers should own.  That said, in recent years OpenGL has changed quite a bit and the old cruft and obsolete instructions haven’t been pruned out of this book yet. The NeHe tutorials have long been the goto resource for new OpenGL developers, although in some ways they suffer the same problem as the Red Book, time waits for no docs!

 

DirectX

This is Microsoft’s primary game SDK ( Software Development Kit ) for creating games on Windows and Xbox using C++ ( not be confused with XNA ).  Unlike OpenGL, DirectX also supports Input and Sound.  Microsoft has provided some fairly good tutorials.  One thing to be aware of, DirectX 10 and 11 require Vista or higher, so no XP support!  That said, DirectX is no doubt the most popular SDK to use for commercial Windows games.  Beginning Game Programming is probably the best beginner friendly DirectX book, but keep in mind, you do need to understand C++ already!

 

Ogre 3D

Ogre3D sits in a weird spot.  It is not a full game engine, but it is not like OpenGL or DirectX either.  In fact OGRE uses both.  Ogre is a 3D rendering engine.  Written in very clean object oriented C++,  Ogre handles a number of tasks that neither DirectX or OpenGL do, like a scene graph ( the data structure your world is stored in ), importers for almost all major 3D modeling applications, landscapes, LOD ( level of detail ) support, etc.  If you are using DirectX or OpenGL to create a 3D game, these are all things you would have to write yourself.  Ogre is cross platform and has been used to create a number of published games.  The have a pretty good manual online.  There are also a beginner and a pro book available, neither of which I have read though.

 

Other Libraries

 

ODE - Open Dynamics Engine

nVidia PhysX

Are two freely available physics engines for accurately modeling real world physics in your game.  ODE is open sourced as well.  There is also Havok which is included in Unreal (UDK), but it’s licensing isn’t so straight forward.

 

Box2D

A physics engine for 2D games.  Free, powerful and quite a bit easier than working in 3D.

 

Boost

Boost is the future of C++, 10 of the boost libraries are already part of the C++ standard, with more coming soon.  Boost libraries perform dozens of common tasks and make up for a giant flaw in the C++ language ( the standard libraries are crap compared to other languages ).  That said, they aren’t the easiest to learn and even harder to understand.  Many Boost programmers are amongst the best in the field, and it shows. There are books available for Boost too, although the website actually has extremely good documentation for the majority of the libraries.

 

Game Engines

 

I will cover this off in a different post, as Engines aren’t really tied to a particular language.  For example, the popular Unreal engine, is very much written and programmable in C++, but also can be programmed in UnrealScript.  Unity is primarily C# based, but can be extended with C++ and scripting with Javascript and Boo.  Panda can be scripted in Python but can also be programmed in C++.  Engines don’t really fit in by language.

 

Still too many choices, tell me exactly what to do!

 

Alright, keep in mind this is all entirely my opinion, but as a game developer learning C++ you should:

 

Go here to download and install Visual C++ Express.

Take the guided tour that will introduce you to using the IDE and language.

At this point I would recommend buying a C++ book such as this one.  There are a ton of resources on the web, but many are outdated or wrong and the sheer volume is overwhelming. Having at least one good beginners guide is ideal.

Go through that book and do some basic exercise, create a few console applications and get a feel for the language.

Now go and download SFML ( Visual Studio 2008 ) <- until 2010 update occurs.

Run through the SFML configuration/starting tutorial.

Now start running through the other tutorials.

At this point, you should be ready to consider making a game.  Start with something small, like creating a PacMan clone or something similar.

Now start making more complex games, or using or creating a game engine.

Congratulations, if you got to this point, you are now a game programmer!

 

EDIT: This site now has a complete game from scratch using SFML tutorial available.  You need to have the basics of C++ down, but it will hopefully teach you quite a bit.  It is a good place to go once you’ve run through a couple C++ tutorials or a few chapters of a book.

 

 

 

 

 

 

C# is the language for me!

 

The C# section is a lot easier to right than C++, as it’s a newer language, there are fewer tools and one library dominates the game ecosystem.

 

Freely available resources for learning the language ( Books and Tutorials )

 

MSDN Visual C# Developer Center

One really nice thing about working with Microsoft technologies is Microsoft know documentation!  The number of tutorials and how to videos they make available is extremely vast.   This link alone should have everything you need to know to get up and running.  They also have more resources, including this introduction video available at the Beginner Developer Learning Center.  Once you are ready to move on to XNA give this tutorial a shot.  To be honest, they probably provide everything you need to succeed.

C# Essentials

A free e-book, covers the basics of C# pretty well.  A bit dated but still free.  Nicely many of the changes to C# over its evolution are complementary to the “old ways”, so not as many ways of doing things have been deprecated.

 

Rob Miles' C# Yellow Book

A free book from a professor at the University of Hull about learning to program using C#.  It’s actually pretty good and he updates annually.  Very good first step for a C# developer that doesn’t want to spend money.

 

Introduction to Programming Through Game Development Using Microsoft XNA Game Studio

Rob Miles also made this ebook available for free download as well.  It is all about learning how to program by creating games in XNA.  Personally I think this is kinda a bad idea, but the price is right!  Definitely give it a shot, it is a very thorough text and if it works for you, you will be up and “doing the fun stuff” at a much quicker pace.  It does cover just about everything you need to know to program a full featured 2D game.

Gang of Four Design Patterns

Truth is, this site is probably not going to make a lick of sense for you starting out, but bookmark it and come back every once in a while.  One of the best sites on design patterns, and design patterns are “a very good thing to know”™.  They will change the way you code, for the better.

 

Recommended books ( Not free )

 

 

.C# Programming Language 4th Edition ( Covering C# 4.0 )

One of the primary writers of this book is the language author.  Just like in C++, with C# I recommend the book by the language creator.  Unlike the C++ equivalent, this book is more beginner friendly although still comprehensive.  As a C# developer, this is probably “the bible” of C# books.  Unlike C++, C# has changed extensively in a short period of time, so be sure you get a copy covering version 4!

 

Headfirst C# 2nd edition

This one is a bit different, as the name implies, it just sorta jumps in and documents as it goes.  Instead of working on console applications, you are actually develop real GUI apps right from the start.  For those that learn by doing, this is an excellent book.  It is very conversational and easy to read, although a little chaotic in its formatting ( check out the preview and you will see what I mean! ).  If this is how you learn, this book will be godsend, but I know it is not for everyone!

 

C# 4 In A Nutshell

I just love this series of books.  These books are very concise and cover the entire language, but can also make for a useful reference well after you’ve got the hang of things.  The downside to this conciseness is, there is not a lot of hand holding, it covers the language only ( no talk of the IDE for example ) and there is no continuity of examples to “tie it all together”.  It describes a language feature, gives an example and moves on.  This may or may not work for you, especially if you have no prior language experience.

 

 

I looked at a number of learn XNA programming books to see if any of them were suitable to a new developer including Learning XNA 4, Microsoft XNA Game Studio 4.0: Learn Programming Now! and Beginning XNA Game Programming and none do a good job of covering the C# language.  My recommendation is to get a grasp of the language basics from another source before jumping into a XNA specific book.

 

Tools

 

This area should be extremely straight forward, as there are really only two ideal IDEs for C# development, Visual C# and Monodevelop.  That said, Microsoft have muddied the waters by letting their marketing department get involved, so you have Visual C#, XNA Game Studio and now Game Studio is included as part of Windows Phone Development Tools… yeah, that makes a ton of sense to me too!  Just to add to the stupidity, Windows Phone Development Tools ( just rolls off the tongue… ) only works on Vista and Windows 7, so if you are running Windows XP, you need to download the standalone version.

 

So…

Visual C# / GameStudio instructions

If you are running Windows 7 or Vista, download this or if you are interested in running the newest and beta-est download this.

 

However, if you are running Windows XP download this. ( Direct Link to EXE )

 

MonoDevelop / SharpDevelop instructions

Finally, if you are running on non-Microsoft platform or for some reason don’t want to use Visual C#, MonoDevelop is the IDE of choice.  ( Download Page )

 

There is also SharpDevelop if MonoDevelop isn’t for you.  ( Download Page ).  It is Windows only however.

 

One key thing to note, if you are working with and want full support for XNA, you will need to use GameStudio/Windows Phone Development Tools. A

 

 

Gaming related stuff

 

XNA

 

Instead of repeating this one in the 2D and 3D libraries section, I’ll just address it first.  XNA is well regarded and is seen as a big reason to use C# and for good reason, it really is a wonderful development environment.  At the most basic level, XNA is a C# friendly version of Direct X, but that is selling it far too short.

XNA handles most of the common tasks for game development.  2D graphics, 3D graphics, audio, asset loading and the content pipeline.  It is also a hell of a lot easier to get up to speed on than OpenGL or DirectX.  The downside is, it is supported on Windows, Xbox and ( a subset) on Windows Phone 7. A number of released games, including every Indy game on Xbox, have been released using XNA tools.

There are however projects to port XNA to other platforms or like this one.

For more details check it out.

 

2D Libraries

 

SDL.Net

It’s SDL, the C++ library, with C# bindings. Therefore it is capable of 2D graphics, sound, loading files, fonts, etc… just like SDL.  C# specific documentation can be found here.

 

3D Libraries

 

OpenTK

OpenTK is a wrapper around OpenGL ( 3d graphics ) , OpenCL ( allows code to run across CPU and GPU’s) and OpenAL ( audio ).  If you want to do cross platform 3D, OpenTK is the way to go.

 

SlimDX

This is a wrapper around all things DirectX 9/11.  So, if for some reason you don’t want to use XNA, you can use full Direct X.  For a beginner, there is probably very little reason, as XNA is a fair bit easier to use.

 

Tao

Tao brings OpenGL ( 3D Graphics ), OpenAL ( audio), ODE ( physics ) and a number of other libraries to C#. Sadly, it’s mostly been abandoned so OpenTK is probably a better bet at this point.

 

Axiom

This is a port of OGRE 3D to .NET.  Sadly it too doesn’t appear to be that active anymore.

 

Other Libraries

 

Box2D.NET

Box2D physics library, for .NET. A pretty impressive 2D only physics library.

 

BEPU Physics

Is a full 3D physics library for .NET that also support Xbox360 and Windows Phone 7.  In the developers words “It’s fast and has a bunch of cool features like constraints, terrain, static and instanced meshes, continuous collision detection, custom collision rules, vehicles, easy multithreading, yadda yadda yadda.”.

 

Still too many choices, tell me exactly what to do!

 

Alright, due to it’s youth and the excellence of XNA, this is an easy one to write.

 

First off, go and download the newest XNA Gamestudio.

Watch some of the Microsoft training materials.

Create a few console apps, get a feeling for the language. It would be a very good idea to buy a good introductory book right now if you can afford it, run through their examples.

Now it’s time to get your feet wet with XNA. Run through the 2D game tutorial.

Use XNA to create all manner of simple 2D then 3D games.

Congrats, you are now a game programmer!

 

 

 

 

 

 

 

 

Java is the language for me!

 

Freely available resources for learning the language ( Books and Tutorials )

 

Oracle's Tutorial Site

Sun ( and now Oracle ) put together a very comprehensive set of tutorials for learning the language.  Start with the getting started tutorials and go from there.  You can download the whole wack of them for offline reading here.

 

IBM Tutorials

IBM also has a huge list of Java tutorials available, running the gamut of subjects, some of which would really surprise you coming from big blue!  Keeping in mind, IBM was the source of Eclipse, they are probably the second most involved company in the Java ecosystem, aside from Oracle.  Lots of their tutorials are very enterprise oriented, but you will find many that are useful.  Here is their introductory tutorial, but perhaps coolest of all, they have a tutorial built around a game for teaching the language!  IBM really is a weird beast. Smile

 

Thinking In Java 3rd Edition

It’s a bit out dated ( 2002 ) at this point in time.  It is however a book that is very easy to read, following along and will help you learn the language.  You will need other resources, but this book is a very good guide down the path of learning Java.  Plus the whole free thing is very nice!

 

 

Recommended books ( Not free )

 

 

The Java Programming Language ( Forth Edition )

In keeping with my trend of recommending books by the language creator, this book is co-authored by James Gosling.  It is a comprehensive and relatively beginner friendly introduction to the Java programming language.  Unfortunately, it is getting a bit old, and only covers up to J2SE 5, while J2SE 6 is the most current release.  That said, this shouldn’t be much of a handicap.

 

Head First Java

This book is an easy read, incredibly easy.  Dare I say it, it is actually kind of fun.  I already knew Java to a degree and didn’t really need a “beginners book”, but I noticed this one was always trending in Safari’s top 10 list ( out of over 14K books! ) and couldn’t figure out why so I gave it a read.  It was a genuinely amusing book to read, it did a very good job of getting the technical information across in a way that didn’t feel so dry and stuffy like many texts do.  It may not be your style, but you should definitely check it out!  Amazon offers a “look inside” preview, and I suggest you do.

 

Java How To Program 9th Edition

A VERY comprehensive introduction to Java at a whopping 1500 pages, it also comes with a whopping price tag.  It is however the text of choice for many java courses and it covers pretty much all of the language aspects, including many common libraries and frameworks, which to you as a game programmer may not matter.  Again though, the price tag is a kick in the teeth.

 

Effective Java

This is not a beginners book, in that it won’t teach you the language basics.  This book, hands down, will make you a better Java programmer.  Once you’ve mastered the basics of the language, pick this up!

“I sure wish I had this book ten years ago. Some might think that I don’t need any Java books, but I need this one.”

Who said that about Effective Java?  James Gosling… the language creator!  I simply cannot think of higher praise.

 

Tools

 

This is an area where Java has always got it right, tools.  There over the years have been a number of great IDEs for Java, but three have really jumped to the forefront and fortunately all 3 are available freely.

 

Java SDK

When developing in Java, your first step is to install the SDK ( software development kit ).  In some cases it may be included in your IDE’s install, but it is safest to start here.  Just like all things Java there are bewildering number of options and flavors.  There is Java SE ( standard edition ), EE ( Enterprise Edition ), ME ( Micro Edition ), Embedded as well as various versions for very specific device devices and profiles.  Hell, even the Java used for Android development is completely different!  ( And frankly isn’t exactly Java, but that’s neither here nor there ).  Long story short though, unless you know a reason not to, what you want is Java SE Development Kit 7, at least as of writing it is.  You will also see this referred to as the JDK or as J2SE on occasion because, well… it’s Java.  You will start noticing a trend very soon!

 

Eclipse

Originally developed by IBM, the now open source Eclipse is the most popular Java IDE in use today.  Available across many platforms and sporting a pluggable UI, Eclipse has everything and the kitchen sink for features.  I would say it is the most capable of the IDEs but on the same token, it is also the most confusing.  If you are working on Android development it is Google’s preferred environment, so that’s where the native tools are for authoring Android apps.  That said, I recently worked on an Android app and I HATED the experience.  Eclipse kept fouling up my projects again and again and again, if I was a new developer I might have quit in frustration!  Get to know the –clean parameter, you are going to use it… a lot.  In all honesty, for a new developer who isn’t doing Android work, stay away from Eclipse to start would be my advice. If you must use Eclipse, be sure not to go wild installing plugins unless you absolutely need them!  Even figuring out which version of Eclipse to download can be a daunting task!  If you don’t know, download this version.

 

 

Netbeans

In that special sort of way that Java has of making things confusing as hell, Netbeans is both the name of an IDE and the name of a platform for developing Swing applications.  In this case we are talking about the IDE.  Originally started as a student project ( in 96! ), Sun purchased and open sourced it in 99.  Since then, Sun (and now Oracle) have made continuous new releases.  It, like Eclipse, supports plugins although nowhere near as extensive ( or annoying! ).  That said, it just works.  For a new developer this is the one I recommend starting with.  Again like Eclipse, there are many different versions and if you choose the wrong one it installs a TON of crap you don’t need and probably don’t want ( like web and database servers! ).  On this download page, unless you have a very good reason otherwise, it’s the JavaSE version you want.  ** I should note, you can do Android development using NetBeans, it’s just not supported or documented by Google.

 

 

IntelliJ IDEA

This incredibly popular IDE, well to be completely honest, I have almost no experience with.  See, it used to cost money and Eclipse/Netbeans were always “good enough”.  That said, in a world full of free tools, people were still willing to pay for IntelliJ IDEA, that says something!  Now though, they have a completely free edition!  Again, I have no direct experience with IntelliJ beyond reading the website, but come time for my next Java project, I will definitely check it out.

 

 

 

Gaming related stuff

 

2D Libraries

 

Slick

I believe this is the most commonly used 2D game library on Java these days.  It is built on lwjgl ( details below ) and uses OpenGL or Java2D for fast 2D rendering.  Additionally it supports fonts, sound, input and image loading.  There is also support for spritesheets, tilemaps and 2D collision detection, all very common requirements in creating a 2D game.  The tutorials even walk you through creating a complete game. A very clean and beginner friendly library.

 

LibGDX

This library handles not only graphics, but sound, file handling, logging and input.  You can also create Android apps with very minimal code changes.  Like slick it uses lwjgl, as well as jogl behind the scenes.  The design seems remarkably clean, but the documentation is a bit lacking.

 

Java2D

This is Java’s standard 2D drawing library.  I am just mentioning it for completeness, as I see no reason to use it over Slick or LibGDX.

 

3D Libraries

 

Jogamp/jogl

These provide Java language bindings for OpenGL, OpenCL, OpenAL and OpenMAX libraries.  This can provide you with low level access to all your graphic and audio needs.  Additionally it can work with Java2D, Swing and AWT. A tutorial for getting started is available here.  Jogamp is completely up to date with the latest OpenGL implementation and is the underlying technology in many higher level Java graphics libraries.

 

lwjgl - Lightweight Java Game Library

Much like jogl, lwjgl is a library built on top of OpenGL and OpenAL.  Additionally it supports game controllers like gamepads and steering wheels.  It has been used to make a number of games and is the underlying technology powering the jMonkeyEngine.

 

jMonkeyEngine

Ok, it’s not technically a library, it’s a full game engine.  What does that mean?  Well instead of accomplishing one task, it accomplishes all the various tasks you need to create a game ( and as just mentioned, uses the lwjgl library to do it ). So in addition to graphics and sound, it provides a full scene graph, mesh and graphics importing methods, a GUI, networking library and much more.  If you are planning to work on a 3D game on Java, start here.  There’s a good selection of tutorials available to get you started.

 

 

Other Libraries

 

jBullet / jbox2D

The popular Bullet 3D and Box 2D physics libraries also have Java implementations.

 

 

Still too many choices, tell me exactly what to do!

 

Ok, first step is to download and install the Java tools.

Next up, go ahead and get NetBeans and install it.

Now download and start reading Thinking in Java, giving silent thanks to Bruce Eckel for his generosity.  If you can’t follow this book, or need a print one, consider purchasing Head First Java.

Run through the first few chapters, do the examples and learn the basics of the language.

Once you grasp the language basics, download and install Slick.

Run through the "Spiegel" tutorial.

At this point, you should probably be capable of creating your own 2D games.  If you are interested in 3D programming, consider checking out the jMonkeyEngine.

Finally, go out and get Effective Java and read it, twice.  It will make you a better Java programmer.

Congratulations, if you got to this point, you are now a game programmer!

 

 

 

 

Python is the language for me!

 

Alright, this section is totally getting the shaft.  Why?  Frankly because I don’t really know Python all that well and don’t feel comfortable giving advice on a subject I am not educated on!

So, instead I am going to give a number of links that will be of use.

 

First, you need to download and install Python itself.  If you don’t know which to pick, go with Python 2.7.

 

Now, picking an IDE out for Python is a right confusing task.  If you follow that thread’s (incredibly bad) advice of choosing Vim or Emacs, I will personally come to your house and smack you!  That said, an easy alternative doesn’t spring to mind.  Personally if I was working with Python today I would use Eclipse with the PyDev plugin.  That said, I am not really comfortable recommending that to a new developer.  Komodo edit is perhaps as good a (free) choice as any to start with, but it does not support integrated debugging.

 

Now that the messy business of choosing an IDE is all over with things get much easier.  There is one dominant 2D game library and that is the PyGame which may just be the most new user friendly game library available.  Tutorial support is quite good, as is the documentation.  Python really handles everything you could need to create a 2D game, graphics, sound, controls, fonts, etc…

 

However, if 2D isn’t your thing, check out Panda3D.  Stupid name aside, this is a powerful engine that has been used to create commercial games.  Again, like PyGame, it handles everything you could possibly need to create a full 3D game.

 

There are even a couple free books like Dive Into Python 3 and A Byte of Python ( good beginner text ). There is also a freely downloadable book Invent Your Own Computer Game With Python.

 

The most important piece of advice I can give you, don’t let people convince you that Python isn’t “a real language”.  It has been used in a number of shipping, high quality games and will continue to be used as such.

 

 

 

 

 

 

 

Now what?

------------------------------

 

So, you’ve picked a language, the libraries you want to use and now you need to, you know… do something.  This is a list of suggested projects for a new developer interested in games, in ( fully my opinion ) order of difficulty. I am always open to new suggestions here, so send them in!  Also, if you want to share the results of your efforts, let me know and I will make that available too!

 

 

… and everything else!

 

If you are looking at getting into 3D development check this list of 3D engines to get started.  If you are struggling with the art side of the equation, be sure to check out A programmer's guide to creating art for your game.

 

Good luck with your game development career!

Programming


GFS On YouTube

See More Tutorials on DevGa.me!

Month List