My Snake game seems to have a bug that causes some strange behavior whenever an apple is collected. Upon collision, the apple disappears and a new one spawns in a new location, but then the original apple reappears in its initial spot. Subsequently, when the newly spawned second apple is collected, the first two apples vanish and a third one appears in a new location. This cycle continues with the previous apples reappearing in their original locations.
It appears that only the newest spawned apple is capable of detecting collisions with the snake and triggering the spawning of new apples.
In my code, I have an Apple
class that keeps track of its x and y coordinates, and a SnakeGame
class which consists of an apple and a snake. When an apple is collected, I set the SnakeGame.apple
property to null and create a new Apple
object with new x,y coordinates to set it as the new SnakeGame.apple
object.
If you have any ideas on how to solve this issue, I would greatly appreciate your input!
If you wish to experiment with my code, here is a fiddle link: https://jsfiddle.net/gabewest1/knuxsa5t/1/
Apple Class:
class Apple {
constructor(x, y) {
this.xPos = x;
this.yPos = y;
this.radius = 10;
}
draw(ctx) {
ctx.fillStyle = "black";
ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI);
ctx.fill();
}
position(x, y) {
if (x > -100 && y > -100) {
this.xPos = x;
this.yPos = y;
} else {
return {
x: this.xPos,
y: this.yPos
};
}
}
}
SnakeGame Class:
class SnakeGame {
constructor(snake) {
this.ctx = $("#myCanvas")[0].getContext("2d");
this.canvas = $("#myCanvas")[0];
this.init();
this.frameLength = 500;
this.apple = this.createApple();
this.snake = snake;
this.score = 0;
this.gameloop();
}
createApple() {
var xPos = Math.floor(Math.random() * this.canvas.width);
var yPos = Math.floor(Math.random() * this.canvas.height);
var apple = new Apple(xPos, yPos);
return apple;
}
gameloop() {
var ctx = this.ctx;
this.snake.move();
if (this.collision()) {
console.log("There was a collision!");
this.score++;
this.increaseSnake();
this.apple = null;
}
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.snake.draw(ctx);
if (this.apple) {
this.apple.draw(ctx);
} else {
this.apple = this.createApple();
}
setTimeout($.proxy(this.gameloop, this), this.frameLength);
}
}