Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Join
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am currently trying learn javascript in form of HTML5 games. Stuff that I've done so far isn't too fancy since I'm still a beginner. My biggest concern so far has been that I don't really know what is the best way to code since I don't know the pros and cons of different methods, nor I've found any good explanations about them. So far I've been using the worst (and propably easiest) method of all (I think) since I'm just starting out, for example like this:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 640;
var height = 480;
var player = new Player("pic.png", 100, 100, ...);
also some other global vars...

function Player(imgSrc, x, y, ...) {
   this.sprite = new Image();
   this.sprite.src = imgSrc;
   this.x = x;
   this.y = y;
   ...
}
Player.prototype.update = function() {
    // blah blah...
}
Player.prototype.draw = function() {
    // yada yada...
}

function GameLoop() {
   player.update();
   player.draw();
   setTimeout(GameLoop, 1000/60);
}

However, I've seen a few examples on the internet that look interesting, but I don't know how to properly code in these styles, nor do I know if there are names for them. These might not be the best examples but hopefully you'll get the point:

1:

Game = {
   variables: {
      width: 640,
      height: 480,
      stuff: value
      },
   init: function(args) {
      // some stuff here
      },
   update: function(args) {
      // some stuff here
      },
   draw: function(args) {
      // some stuff here
      },
};
// from http://codeincomplete.com/posts/2011/5/14/javascript_pong/

2:

function Game() {
    this.Initialize = function () {

    }
    this.LoadContent = function () {
        this.GameLoop = setInterval(this.RunGameLoop, this.DrawInterval);
    }

    this.RunGameLoop = function (game) {
        this.Update();
        this.Draw();
    }

    this.Update = function () {
        // update
    }

    this.Draw = function () {
        // draw game frame
    }
}
    // from http://www.felinesoft.com/blog/index.php/2010/09/accelerated-game-programming-with-html5-and-canvas/

3:

var engine = {};
engine.canvas = document.getElementById('canvas');
engine.ctx = engine.canvas.getContext('2d');

engine.map = {};
engine.map.draw = function() {
    // draw map
}

engine.player = {};
engine.player.draw = function() {
    // draw player
}
// from http://that-guy.net/articles/

So I guess my questions are:

  • Which is most CPU efficient, is there any difference between these styles at runtime?
  • Which one allows for easy expandability?
  • Which one is the most safe, or at least harder to hack?
  • Are there any good websites where stuff like this is explained?

or...

  • Does it all come to just personal preferance? :)
share|improve this question

closed as not constructive by Byte56, Josh Petrie, Noctrine Oct 31 '12 at 18:19

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

2  
I don't believe there's a correct answer to this question. You can try something like the code review stack exchange, but this is not directly related to game development. – Byte56 Oct 31 '12 at 0:47
1  
I'd actually be interested in the answers to this question: although I use the blah.prototype syntax, I'm rather curious what's going on with options 1 and 2. But yeah this question doesn't belong here; maybe this should be migrated to stackoverflow or programmers.se? – jhocking Oct 31 '12 at 2:12
1  
I'm currently using TypeScript for browser games and it works quite well. You can take a look at it if you like OOP. :) – Kikaimaru Oct 31 '12 at 10:30
    
I'll get you a concise answer when I get home, but as for safety, there is none. If you design good, then you shouldn't have such problems. – jcora Oct 31 '12 at 11:57
2  
i suggest migration to SO or closing, this isn't a game related question, besides this is too big of a topic to cover in an answer, whole book chapters are devoted to patterns, whatever's going to be posted it's going to be a mess of people trying to teach javascript programming, it's out of place for this site – dreta Oct 31 '12 at 16:32
up vote 5 down vote accepted

In JavaScript, functions can imitate classes. In my opinion, they're more logical than classes too.

To have a function imitate a class (be a constructor function), you need to use the this and new keywords. this refers to the object being created by the function, so if you write this.a = 5 inside the function, your newly created object will have a property a with the value of 5. this in JavaScript is analogous to this in C++ or self in Python or Java.

The new keyword is used when instantiating objects. var obj = new Class() instantiates a new object of type Class, and assigns a reference to it in the obj variable.

However, there is one important thing you should know. If you assign functions to objects inside the constructor (this.f = function(){...}), this will create a new instance of this function for each object, something that isn't very efficient. This is where prototypes come into play.

To demonstrate:

var Class = function(a)
{
    this.a = a
    this.b = 34
}

Class.prototype.f = function(a)
{
    return this.a + a //this.a != a!!!
}

var obj = new Class(5)

obj.a //5
obj.b //34
obj.f(4) //9

Now, each time you create an instance of Class, and try to call its f function, JavaScript will traverse the prototype chain and get to the prototype of Class, which does have the f function. That's another feature of the new keyword, it sets the newly created object's prototype to its class' prototype.

Also, you might want to check out closures, they are much slower than prototyping (did the research myself), but provide a sort of access modification.


Now, to answer your concrete questions...

  • Which is most CPU efficient, is there any difference between these styles at runtime?

Depends on the implementation, but you want to go with the prototypes (as you are doing).

  • Which one allows for easy extensibillity?

Well, you can add anything you want to any object, really, but I suggest that you don't go with the singleton pattern. It's generally not a very good thing to have objects in global scope in JavaScript, and even the pattern itself has some issues.

  • Which one is the most safe, or at least harder to hack?

As I said in the comment, you shouldn't care about this. Anyone can fire up a console and mess with your game. JavaScript wasn't built for safety, heck, clients are inherently unsafe, so you'll need to implement such stuff on the server.

  • Are there any good websites where stuff like this is explained?

Sure:

codeproject.com/Articles/247241/Javascript-Module-Pattern
developer.mozilla.org/en-US/docs/Canvas_tutorial
stackoverflow.com/questions/4650513/why-is-javascript-prototyping
codethinked.com/preparing-yourself-for-modern-javascript-development
addyosmani.com/resources/essentialjsdesignpatterns/book/ (You simply must read this.)
javascriptpatterns.org/
nodejs.org/ (For JavaScript servers.)
socket.io/ (For multiplayer.)

share|improve this answer
    
Very nice and informative answer! Seems like I have plenty of reading to do before I can master JS, so thanks for the links :) – fnx Oct 31 '12 at 18:22
    
No problem man, you can just mail me if you have dilemas. – jcora Oct 31 '12 at 18:59

Their are indeed differences between these at runtime.

  1. In OOP terms, this is directly an instantiated object, or if you prefer this is a singleton. If you want more instances of those you'll have to clone that object but this isn't native in JavaScript.

  2. This is probably the most common way to define a class. This allows creating as many instances as necessary using var game = new Game();. The drawback is that your class methods are duplicated each time you create a new instance, this can become a concern if you need a lot of them. A workaround is to add methods to the class prototype, as you're doing yourself for your Player class.

  3. This is virtually the same thing as option 1., except the object is defined bit by bit instead of all at once.

You could check this blog entry for details.

So for a game, the best is probably to use what you've used for your Player class, and maybe use option 1. or 3. for singletons. Another option might be to use a proper OOP language and compile it to JavaScript.

share|improve this answer
    
Would this syntax be doing the same thing as 1: Game.init = function() {yada yada} ? I ask because I use the object.prototype.name syntax and that looks more similar. – jhocking Oct 31 '12 at 12:07
1  
Well following the OP classification, that's 3. – Laurent Couvidou Oct 31 '12 at 12:50
    
@jhocking But yeah basically that's the same thing, you end up with the same data structure at the end. – Laurent Couvidou Oct 31 '12 at 13:18
    
oh right that's 3, the way it says engine.map.draw() instead of engine.draw() threw me off. – jhocking Oct 31 '12 at 14:16

there is no fit-all answer. Search the web for "javascript patterns" and you will find great resources. Invest the time in this before you get too far into things.

On suggestion that I can make - we used the "Self-Executing Anonymous Function" in this article http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ to hide private members and that worked out well for us. we have, of course, spent significant amount of time researching and experimenting and arrived at this as the best option after 2 months of development, so do your homework as well

If you want to mimic OOP, i suggest you look into higher level languages like typescript or others or you will be doing a lot of boiler plate/pluming code that makes the code hard to read and error prone

Here is an example of our code. these are not classes/objects in OOP sense, they are more like namespaces, or singletons

(function (ROE) {
} (window.ROE = window.ROE || {}));

(function (obj) {

    var CONST = { popupName: "Building" },
        CACHE = {};

    CONST.Enum = {};

    CONST.Enum.CanUpgrade = {
        Yes: 0,
        No_LackFood: 1,
        No_LackSilver: 2,
    };

    var _load = function () {        
    }      

    var _showBuildingPagePopup = function (buildingID) {
    }

    //public function definition
    obj.showBuildingPagePopup = _showBuildingPagePopup;

} (window.ROE.Building = window.ROE.Building || {}));
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.