Skip to content

Commit

Permalink
extract collision check
Browse files Browse the repository at this point in the history
  • Loading branch information
mwillerich committed Apr 15, 2023
1 parent 3de77aa commit 5978a92
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions snake.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,8 @@ var Snake = {
break;
}

if (
newHead.x < 0 ||
newHead.x >= this.gridSize ||
newHead.y < 0 ||
newHead.y >= this.gridSize ||
this.snake.some(function(segment) {
return segment.x === newHead.x && segment.y === newHead.y;
})
) {
// Check for collision
if (this.checkCollision(newHead)) {
clearInterval(this.gameLoop);
alert("Game Over!");
return;
Expand All @@ -67,6 +60,23 @@ var Snake = {
}
},

checkCollision: function(newHead) {
// Check if the new head is outside the game grid
if (
newHead.x < 0 ||
newHead.x >= this.gridSize ||
newHead.y < 0 ||
newHead.y >= this.gridSize
) {
return true;
}

// Check if the new head collided with the snake's body
return this.snake.some(function(segment) {
return segment.x === newHead.x && segment.y === newHead.y;
});
},

drawFood: function() {
context.fillStyle = "red";
this.drawSquare(this.food.x, this.food.y);
Expand Down

0 comments on commit 5978a92

Please sign in to comment.