My latest project involves creating a Snake game using canvas in JavaScript. I've managed to set up most of the game, but I'm having trouble with the collision check. Whenever the snake hits itself or the wall, the game crashes because I can't figure out how to implement the checkCollision method I've defined.
<script>
//Code for creating the game canvas, drawing borders, and setting up the score
...
//Code for creating the Snake, Apple, and handling player input
...
//Code for detecting collisions and moving the snake
...
//Run the game loop
let snake = new Snake();
let apple = new Apple();
var aniTime = 100;
function core () {
ctx.clearRect(0, 0, width, height);
drawScore();
snake.move();
snake.draw();
apple.draw();
drawBorder();
timeOutId = setTimeout(core, aniTime);
if (snake.checkCollision() === true) { //**the PROBLEM
clearTimeout(timeOutId);
gameOver();
};
};
core();
//Handle game over condition
var gameOver = function () {
clearTimeout(timeOutId);
ctx.font = '60px Arial';
ctx.fillStyle = 'Black';
ctx.textAlign = 'center';
ctx.textBaseLine = 'middle';
ctx.fillText('Game Over', width / 2, height / 2);
};
</script>
Whenever there is a collision, I encounter the following error messages:
Uncaught TypeError: Cannot read properties of undefined (reading 'col')
at Snake.checkCollision (snake.html:148:43)
at core (snake.html:191:27)
at snake.html:196:13
Uncaught TypeError: Cannot read properties of undefined (reading 'col')
at Snake.checkCollision (snake.html:148:43)
at core (snake.html:191:27)
snake.html:129
Uncaught TypeError: gameOver is not a function
at Snake.move (snake.html:129:21)
at core (snake.html:186:23)