Skip to content

Commit 5c01520

Browse files
committed
Implement Game Over on Snake Biting Itself #4
1 parent 4dc72d0 commit 5c01520

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

index.js

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,26 @@ function main(ctime) {
2929
gameEngine();
3030
// console.log(ctime);
3131
}
32+
// Function to check if snake collides with itself
3233
function isCollide(snake) {
33-
// return false;
34-
//if you into yourself
35-
34+
// Check collision with walls
3635
if (snake[0].x > 18 || snake[0].x < 0 || snake[0].y > 18 || snake[0].y < 0) {
3736
return true;
3837
}
38+
39+
// Check collision with itself
40+
for (let i = 1; i < snake.length; i++) {
41+
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
42+
return true;
43+
}
44+
}
45+
46+
return false;
3947
}
48+
49+
50+
51+
4052
function gameEngine() {
4153
//part1: updating the snake array and food
4254
if (isCollide(snakeArr)) {
@@ -47,6 +59,7 @@ function gameEngine() {
4759
snakeArr = [{ x: 13, y: 15 }];
4860
// musicSound.play();
4961
}
62+
5063

5164
//IF you have eaten the food, increment the score and regenerate the food
5265
if (snakeArr[0].y === food.y && snakeArr[0].x === food.x) {

0 commit comments

Comments
 (0)