const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
class Snake {
constructor() {
this.segments = [{ x: 100, y: 100 }];
this.dir = { x: 0, y: 0 };
this.growBy = 0;
this.score = 0;
}
draw() {
for (let i = 0; i < this.segments.length; i++) {
ctx.fillStyle = i ? '#000' : '#fff';
ctx.fillRect(this.segments[i].x, this.segments[i].y, 10, 10);
}
}
update() {
for (let i = this.segments.length - 1; i > 0; i--) {
this.segments[i].x = this.segments[i - 1].x;
this.segments[i].y = this.segments[i - 1].y;
}
this.segments[0].x += this.dir.x;
this.segments[0].y += this.dir.y;
if (this.segments[0].x < 0 || this.segments[0].x > canvas.width - 10 || this.segments[0].y < 0 || this.segments[0].y > canvas.height - 10) {
clearInterval(gameLoop);
alertHisa('Game over!');
return;
}
for (let i = 1; i < this.segments.length; i++) {
if (this.segments[0].x === this.segments[i].x && this.segments[0].y === this.segments[i].y) {
clearInterval(gameLoop);
alertHisa('Game over!');
return;
}
}
}
eat() {
const maxX = canvas.width / 10;
const maxY = canvas.height / 10;
const foodX = Math.floor(Math.random() * maxX) * 10;
const foodY = Math.floor(Math.random() * maxY) * 10;
if (this.segments[0].x === foodX && this.segments[0].y === foodY) {
this.score++;
document.getElementById('score').innerHTML = this.score;
this.growBy++;
return true;
}
return false;
}
grow() {
this.segments.push({ x: this.segments[this.segments.length - 1].x, y
*This prompt didn't get me into the game this time. Plz try to generate it a few times.