Game Development Reference
In-Depth Information
It's useful to place comments in your code to explain groups of instructions belonging together, the
meaning of parameters, or complete classes. If you use comments, do it to clarify the code, not
to write the code again in words: you can assume the reader of your code knows JavaScript.
To illustrate this, the following comment line adds to the clarity of the instruction:
// Set the background color to green.
canvasContext.fillStyle = "green";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
This is also a comment, but it doesn't clarify what the instruction does:
/* Pass the value "green" to the fillStyle variable of canvasContext and call the fillRect method of
canvasContext with the parameters 0, 0, canvas.width and canvas. */
canvasContext.fillStyle = "green";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
While testing your program, you can also use comment symbols to temporarily remove instructions from
the program. Don't forget to remove the parts of your code that are commented out once you finish the
program, because they can lead to confusion when other developers look at your source code.
Instructions vs. Lines
There are no strict rules about how to distribute the text of a JavaScript program over the lines in a
text file. Usually you write every instruction on a separate line, even though this isn't necessary for
the compiler to understand the program. Sometimes, if it makes a program clearer, the programmer
writes multiple instructions on a single line. Also, sometimes a single instruction that is very long
(containing function/method calls and many different parameters) can be distributed over multiple
lines (you see this later in this topic as well).
Whitespace and Indentation
As you can see, the BasicGame example uses whitespace liberally. There is an empty line between
each function, as well as spaces between each equals sign and the expressions on either side of it.
Spacing can help to clarify the code for the programmer. For the browser/interpreter, spaces have
no meaning. The only place where a space is really important is between separate words: you aren't
allowed to write function update() as functionupdate() . And similarly, you aren't allowed to write
an extra space in the middle of a word. In text that is interpreted literally, spaces are also taken
literally. There is a difference between
canvasContext.fillStyle = "blue";
and
canvasContext.fillStyle = "b l u e";
 
Search WWH ::




Custom Search