Creating the Player¶
It's time to create our player! Since a snake is a collection of tiles, let's use an array to model our player. Each element in the array can be an object with an (x,y) coordinate.
let player = [
{
x: 4,
y: 5
},
{
x: 3,
y: 5
},
{
x: 2,
y: 5
},
{
x: 1,
y: 5
}
];
Rendering the Player¶
In the last chapter, we made a handy loop to draw each tile in our grid. We want the tile to be blue if it is empty, and green if the snake is in that tile. To test if the player is in the current tile, we must loop through the player
array to see if any element in the array has the same (x,y) coordinates as the current tile we are rendering. If we find the element in the player array that is in the current tile, we can set the color to green
and break
out of the loop, since we know each tile can only be inhabited once.
for(let i = 0; i < tilesX; ++i) {
for(let j = 0; j < tilesY; ++j) {
// Detect if the player is in this tile
for(let k = 0; k < player.length; ++k) {
// Test if the x coordinate == i and the y coordinate == j
if(player[k].x == i && player[k].y == j) {
ctx.fillStyle = "green";
break;
}
}
// Draw the tile
}
}
So the entire render function should now look like this:
function render() {
// Draw background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw grid
for(let i = 0; i < tilesX; ++i) {
for(let j = 0; j < tilesY; ++j) {
// Set the default tile color
ctx.fillStyle = "blue";
// Detect if the player is in this tile
for(let k = 0; k < player.length; ++k) {
if(player[k].x == i && player[k].y == j) {
ctx.fillStyle = "green";
break;
}
}
// Calculate the x, y, w, h for each tile
let x = i * tileWidth + borderWidth;
let y = j * tileHeight + borderWidth;
let w = tileWidth - borderWidth * 2;
let h = tileHeight - borderWidth * 2;
// Draw each tile
ctx.fillRect(x, y, w, h);
}
}
}
Success!
Our grid now has a snake in it! But what good is a static image when we want to create a game? In the next chapter, we learn how to control the player.