HTML and CSS Reference
In-Depth Information
Listing 8-11. Setting Cells as Modified
function paintPlayer(ctx, x, y) {
var l = ((x - playerRadius) / cellWidth) >> 0, // Grab the left corner
r = ((x + playerRadius) / cellWidth) >> 0, // Grab the right corner
t = ((y - playerRadius) / cellHeight) >> 0, // Grab the top corner
b = ((y + playerRadius) / cellHeight) >> 0, // Grab the bottom corner
i = t,
j = l;
// Adding 1 more row/col for error correction
// Also, make sure that they are not bigger than gridCols and gridRows
r = ((r + 1) > gridCols) ? r : (r + 1);
b = ((b + 1) > gridRows) ? b : (b + 1);
// Set the colour to a semi-transparent blue
ctx.fillStyle = 'rgba(0, 0, 255, 0.05)';
// Cycle between left-right and top-bottom
for ( ; i < b ; ++i ) {
for ( j = l ; j < r ; ++j ) {
Grid[i][j] = 1;
}
}
// Set the colour to a dark red
ctx.fillStyle = '#CC0000';
// Draw the circle
ctx.beginPath();
ctx.arc(x, y, playerRadius, 0, 2 * Math.PI);
ctx.fill();
}
While this new code has been massively improved as compared to the last example, you will quickly notice that there
are two bottlenecks in your update loop. The first one is caused by the loop that checks each cell's flag, and the other loop
is found within the paintPlayer() function. On small grids you wouldn't even notice the bottleneck, but imagine what
would happen if your grid were to be substantially larger, which leads to the next topic wit hin this chapter.
Rendering Massive Grids
So far, your grids are not very big, so for now the performance seems to be good. However, how would this work with
a bigger grid?
A beginner might attempt to improve the performance by doing something like the code in Listing 8-12.
 
Search WWH ::




Custom Search