File tree Expand file tree Collapse file tree 1 file changed +16
-3
lines changed Expand file tree Collapse file tree 1 file changed +16
-3
lines changed Original file line number Diff line number Diff line change @@ -29,14 +29,26 @@ function main(ctime) {
29
29
gameEngine ( ) ;
30
30
// console.log(ctime);
31
31
}
32
+ // Function to check if snake collides with itself
32
33
function isCollide ( snake ) {
33
- // return false;
34
- //if you into yourself
35
-
34
+ // Check collision with walls
36
35
if ( snake [ 0 ] . x > 18 || snake [ 0 ] . x < 0 || snake [ 0 ] . y > 18 || snake [ 0 ] . y < 0 ) {
37
36
return true ;
38
37
}
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 ;
39
47
}
48
+
49
+
50
+
51
+
40
52
function gameEngine ( ) {
41
53
//part1: updating the snake array and food
42
54
if ( isCollide ( snakeArr ) ) {
@@ -47,6 +59,7 @@ function gameEngine() {
47
59
snakeArr = [ { x : 13 , y : 15 } ] ;
48
60
// musicSound.play();
49
61
}
62
+
50
63
51
64
//IF you have eaten the food, increment the score and regenerate the food
52
65
if ( snakeArr [ 0 ] . y === food . y && snakeArr [ 0 ] . x === food . x ) {
You can’t perform that action at this time.
0 commit comments