Learning 05: Using the debugger

When writing any type of program, it’s useful to be able to watch what’s going on in your code as it runs. The Perlenspiel debugger gives you one way to do this.

Go back to PS.touch() and uncomment the call to PS.debug():

PS.touch = function( x, y, data, options ) {
 // Uncomment the following code line
 // to inspect x/y parameters:

 PS.debug( "PS.touch() @ " + x + ", " + y + "\n" );

 // Add code here for mouse clicks/touches
 // over a bead.

 PS.color( x, y, PS.COLOR_RED );
 PS.audioPlay( "fx_click" );
 PS.glyph( x, y, "P" );
};

The PS.debug() command sends a text string to the debugger, which is a special text box that is normally hidden under the message line.

Re-save the game.js file and run game.html again. When you click on a bead, you should now see its coordinates on the grid being reported in the debugger box.

Error alert!

The debugger box will open automatically if an error occurs in your code, with a message reporting the nature and location of the problem.

Constructing a debugger string

Take a closer look at that PS.debug() command.

PS.debug( "PS.touch() @ " + x + ", " + y + "\n" );

This example uses JavaScript’s string concatenation syntax to report the x and y position of the bead that was clicked. The + sign constructs a string consisting of five elements:

  1. The fixed string "PS.touch() @ ", to remind you where the debug message is originating. Note the space character at the end of the string, which makes the following value easier to read.
  2. The value of the x coordinate.
  3. The fixed string ", ", to separate the two coordinates. Again, a space character at the end of the string improves readability.
  4. The value of the y coordinate.
  5. The fixed string "\n" (newline), which insures that this message will occupy a separate line in the debugger box.

If a piece of code is giving you trouble, try adding a PS.debug() message to report the value of related variables. It’s a useful diagnostic technique that can help you quickly pinpoint problems.

However, the Perlenspiel debugger isn’t the only tool you should rely on when writing code. Any modern JavaScript IDE or browser will offer a range of professional debugging features, including interactive breakpoints, expression evaluation and variable watching. These capabilities can save you many, many hours of work. Consult your IDE and browser documentation for details.

 

Terms to know

Next: Color Expression