In programming, we often need to do something more than once. For instance, we might want to keep a running tally of a list of numbers; or search through that list to find its maximum value. Such operations involve repeating a block of code, with possible variation, until a certain condition is reached. In sequential processing, we would have to write a lengthy program that repeated those actions for each element. Fortunately, we can write the code just once, and instruct the computer to simply repeat the desired code block. This is the essence of a loop.

One type of loop is called a for loop. The for loop executes a finite number of iterations of a block of code. The syntax is as follows:

for (initialization; end-condition; increment) { code block to be executed }

The initialization is usually a statement of the initial condition of the counter variable. The end condition is an expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed; otherwise, the execution jumps to the first expression outside the curly braces. The increment is simply the amount by which the counter variable increases or decreases every time the loop is executed. It is common for this value to be 1, so there is a special syntax for it. If we wish to increase the variable x by 1, we can simply write x++ .

The canvas element

The canvas element is a very useful element that can be used alongside JavaScript to dynamically draw basic 2D graphics. This can be very useful, in designing game boards or puzzle-type games. Today, we will create a simple (albeit empty) chess board.

First off, we create a canvas element in our HTML document:

<canvas id="board" width="400" height="400"></canvas>;

This creates a blank canvas with dimensions of 500px by 500px.

Next, we have to “prepare” the canvas for drawing. This is done with the following code:

var canvas = document.getElementById("board"); var context = canvas.getContext("2d");

Now let’s try to draw one square. To draw a square we should specify its dimensions and its fill value.

context.fillStyle = "#FF0000"; context.fillRect(1,1,50,50);

The above code produces a single square, at the coordinates (1,1) on the canvas (one down and one right from the top-left corner), with the that’s 50 pixels high and 50 pixels wide. The result looks like this:

Next, we implement the loop: Since we want this to be done eight times, we use:

for (var col = 0; col <= 7; col++){ context.fillStyle = "FF0000"; context.fillRect(50*col,0,50,50); }

We start from 0 so that the corner of the image can match that of the canvas. This produces a single row, comprised of eight columns, with one square in each column, for a total of 8 squares.

In order to show that there are indeed eight squares, we can increment the fillStyle

for (var col = 0; col <= 7; col++){ $red = 0xFF - (0x1C)*col; context.fillStyle = "#" + $red.toString(16) + "0000"; context.fillRect(50*col,0,50,50); }

Now we can clearly see eight different blocks, which get progressively darker as we move to the right:

This is the first row out of eight; in order to get the other 7 rows, we shall simply nest the above code within another loop. However, this time we also have to change the second zero (line 5 in the code below) to 50*row so as not to draw the rows on top of one another. Also, we’ll progressively add green shades to the fillStyle to see things better:

for (var row = 0; row <=7; row++){ for (var col = 0; col <= 7; col++){ $red = 0xFF - (0x1C)*col; $green = 0x11 + (0x1b)*row; context.fillStyle = "#" + $red.toString(16) + $green.toString(16) + "00"; context.fillRect(50*col,50*row,50,50); } }

Now we have a square comprising 64 smaller, individual squares, as you can see:

At this point, you can either choose to revert all the squares to a single color, or to keep it as it is. Personally, I like it this way as it will help me to visualize things later on. Now, we can number the boxes. This will help to determine which squares are colored differently to get the characteristic “checkerboard” pattern. Simply insert this inside the loop:

squareNumber = ((8*row) + col) + 1; context.fillStyle = "#fff"; context.fillText(squareNumber,50*col,(row+1)*50-5);

However, in proper chess notation, the columns (files) are denoted by letters, whilst the rows (ranks) are denoted by numbers. The columns are denoted by columns a through h, going from left to right, and by numbers 1 through 8 going from bottom to top. In order to get the squares in proper “algebraic” chess notation, we first define a string str='abdcefgh' . Since this doesn’t have to be re-defined every time we run the loop, we write it outside both loops. The file is simply equivalent to the “col”-th element of str. Meanwhile, since we put in the squares backwards, the rank is equivalent to 8-row . Therefore we add context.fillText(str[col] + (8-row), 50*col, (row+1)*50-25); inside our loop. The result (with both numbers and algebraic notation) looks like this:

Now, all we have left to do is to generate the checkerboard pattern. If you look at a chessboard, you will notice that “odd numbered” ranks (that is to say, 1, 3, 5, and 9) have dark squares on ODD numbered squares, whilst even numbered ranks (that is to say, 2, 4, 6, and 8) have dark squares on even numbered ranks. Therefore, we must change a square’s color if it is either an odd numbered square in an even odd rank, or an even numbered square in an even rank. Therefore, we must find the appropriate Boolean expression for the conditional statement, which is:

if ((!(col%2) && !(squareNumber%2)) || (col%2 == 1 && squareNumber%2 == 1)) context.fillStyle = "#1218FF";

Which goes right underneath the second (col) loop, because we need to check every time whether or not the conditions are fulfilled. For the else statement, we have to re-arrange the code so that the code that describes the color scheme for the unchanged squares in inside the else statement. The resulting code looks like this:

if ((oddRank && squareNumber%2 == 1) || (evenRank && !(squareNumber%2))) context.fillStyle = "#8989FF"; else{ $red = 0xFF - (0x1C)*col; $green = 0x11 + (0x1b)*row; context.fillStyle = "#" + $red.toString(16) + $green.toString(16) + "00"; }