HTML and CSS Reference
In-Depth Information
Here, you are going to clear the map, which you will add later on, and then set up some local variables to
represent the values that you will need as you loop through the tiles in the array to draw them. It's always good
practice, and it helps with performance, to precalculate and predefine variables used in for loops, especially the
nested for loop you are about to write. Now, add the following loops to your draw method:
for (row = 0; row < total; row++) {
for (column = 0; column < rowWidth; column++) {
currentTile = tiles[row][column];
this.drawTile(column, row, currentTile);
}
}
As you can see, you are simply looping through the rows, and, at each row, you loop through the column to get
the tile. This will in essence render out each tile in the grid. You can access any tile from your two-dimensional array
by calling tiles[row][column] . As you run through the loop, you get a reference to your tile, which is either "#" or
" " , to represent walls or floors. Then, you pass the column, row, and tile values over to your drawTile method.
Let's add the following code to that now:
//Change tileRect's x,y position
this.tileRect.x = column * this.tileRect.width;
this.tileRect.y = row * this.tileRect.height;
//Draw tile to the canvas
this.target.fillStyle = this.tileColor(currentTile);
this.target.fillRect(this.tileRect.x, this.tileRect.y, this.tileRect.width, this.tileRect.height);
//Draw outline around tile
this.target.strokeStyle = "black";
this.target.strokeRect(this.tileRect.x, this.tileRect.y, this.tileRect.width, this.tileRect.height);
This should be very standard stuff if you have ever worked with the canvas before. The target is your two-dimensional
context, which you defined at the top of the class, and you are simply modifying the tileRect , which represents the size of
your map's tile to update its x, y position according to where you want to render it next. You use fillRect and strokeRect
with the x, y width and height values of your tileRect to render your map.
You may have noticed the method in there called tileColor . This will represent your lookup table for
determining what color to use on each tile, based on its type. Let's add the following method to the end of the
CanvasMapRenderer :
private tileColor(value: string): string {
switch (value) {
case " ":
return "#ffffff";
break;
case "@":
return "#ff0000";
break;
default:
return "#333333";
}
}
 
Search WWH ::




Custom Search