I am working through a snake game program and have run into a really odd problem. Everything works except that the snake does not crash into itself. When the snake runs into itself the screen should turn red temporarily. The specific problem is on line 55. There is a for loop that for some reason is not running. I am really confused as I do not see the problem. Can anyone please help?
let numOfBlocks = 20;
let blockSize = 20;
let headX = 0;
let headY = 0;
let speedX = 0;
let speedY = 0;
let tailLength = 0;
let tailBlocks = [];
let appleX = 0;
let appleY = 0;
let game = true;
function setup() {
createCanvas(400, 400);
frameRate(10);
//start snake at center
headX = numOfBlocks / 2;
headY = numOfBlocks / 2;
//starting location of the apple
appleX = floor(random(0, numOfBlocks));
appleY = floor(random(0, numOfBlocks));
}
function draw() {
if (game == true) {
background("black");
// the snake
fill("white");
rect(headX * blockSize, headY * blockSize, blockSize, blockSize);
headX = headX + speedX;
headY = headY + speedY;
//the apple
fill("red");
rect(appleX * blockSize, appleY * blockSize, blockSize, blockSize);
// snake touches apple
if (headX == appleX && headY == appleY) {
appleX = floor(random(0, numOfBlocks));
appleY = floor(random(0, numOfBlocks));
tailLength = tailLength + 1;
}
// the tail
tailBlocks.push({
x: headX,
y: headY
})
for (let i = 0; i < tailBlocks.length; i++) {
fill("white");
rect(tailBlocks[i].x * blockSize, tailBlocks[i].y * blockSize, blockSize, blockSize);
}
// tail cutter
while (tailBlocks.length > tailLength) {
tailBlocks.shift();
}
// touching your own tail
for (let z = 0; z < tailLength.length; z++) {
if (headX + speedX == tailBlocks[z].x && headY + speedY == tailBlocks[z].y) {
background("red");
game = false;
}
}
// the walls
if (headX < 0) {
headX = numOfBlocks - 1;
}
if (headX > numOfBlocks - 1) {
headX = 0;
}
if (headY < 0) {
headY = numOfBlocks - 1;
}
if (headY > numOfBlocks - 1) {
headY = 0;
}
}
// what happens when the game ends
if (game == false) {
background("red");
textSize(50);
text("Game Over", 70, 200);
textSize(30);
text("Try Again?", 130, 275);
if (mouseIsPressed) {
game = true;
}
}
}
function keyPressed() {
// the controls
if (key == "w" || keyIsDown(UP_ARROW)) {
speedX = 0;
speedY = -1;
}
if (key == "a" || keyIsDown(LEFT_ARROW)) {
speedX = -1;
speedY = 0;
}
if (key == "s" || keyIsDown(DOWN_ARROW)) {
speedX = 0;
speedY = 1;
}
if (key == "d" || keyIsDown(RIGHT_ARROW)) {
speedX = 1;
speedY = 0;
}
}