Created
January 18, 2024 15:45
-
-
Save ssaurel/857a654c2b6dd065a15bfdb5751cdcab to your computer and use it in GitHub Desktop.
Step 5 for creating a Snake on SSaurel's Blog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
move() { | |
var dirx = this.dirx; | |
var diry = this.diry; | |
// if the snake eats the food | |
if (this.head.x == this.food.x && this.head.y == this.food.y) { | |
// add a new tail | |
var newtail = { x: this.head.x - dirx, y: this.head.y - diry }; | |
this.elements.unshift(newtail); | |
this.tail = newtail; | |
this.food = this.generatefood(this.nbx, this.nby); | |
this.points++; | |
if (this.points % this.level == 0) { | |
this.fps++; | |
this.fpsinterval = 1000 / this.fps; | |
} | |
} | |
// if the head touch one part of the elements | |
var self = this; | |
var touch = false; | |
this.elements.every((element) => { | |
if (self.head != element && self.head.x == element.x && self.head.y == element.y) { | |
touch = true; | |
return false; | |
} | |
return true; | |
}); | |
if (touch) { | |
// we restart the game | |
this.init(); | |
return; | |
} | |
var newx = this.head.x + dirx; | |
var newy = this.head.y + diry; | |
if (newx >= this.nbx) { | |
newx = 0; | |
} else if (newx < 0) { | |
newx = this.nbx - 1; | |
} | |
if (newy >= this.nby) { | |
newy = 0; | |
} else if (newy < 0) { | |
newy = this.nby - 1; | |
} | |
var newhead = { x: newx, y: newy }; | |
this.elements.shift(); // remove last | |
this.elements.push(newhead); // add new head | |
this.head = newhead; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment