Game Development Reference
In-Depth Information
#chessboard > div
&.current, &.current.lighter
background-color: #beb
results in the following CSS:
#chessboard > div.current, #chessboard > div.current.lighter {
background-color: #bbeebb;
}
Game logic
We will now implement the game logic in the game.js JavaScript file.
Before writing it, we need to know some best practices for good code organization, such as scope and
namespace .
Scope and namespacing
Scope refers to where variables and functions are accessible, and in what context it is being executed.
You have two kinds of scopes: the global scope (like window, document, etc.) and the local scope , which
you can define. Any variables or functions put in the global scope can be accessed anywhere in the code.
For instance the alert() function defined in window.alert is available anywhere. On the other hand, the
local scope means some variables can only be accessed in a particular context; for instance, a variable
defined in a function can only be accessed in this function.
On a browser, the default scope used is window (a global object representing the window itself). Hence,
variables or functions you define without scoping are defined in this window object.
It's a bad (and old school) practice to define all your variables and functions in the window scope. It's a bit
like defining all your C variables in the global scope. You should avoid polluting the global scope.
Hence, a good practice is to isolate the code from the window scope. You can put it in your own scope
with a closure. However, you still need to access to some of your objects. Let's look at how to achieve it.
The following is a code skeleton to isolate some source code from a global scope:
(function(){
// put your code here
}());
We just have defined an anonymous function that is instantly called.
Now let's look at the closure power, as follows:
(function(ns){
// ...
ns.Service = function(){
var private = "something";
// inaccessible code and scoped inside ns.Service
return {
publicFunctionGetter: function(){ return private; }
 
Search WWH ::




Custom Search