by-idb
Version:
A simple terminal snake game library with no external dependencies
32 lines (27 loc) • 783 B
JavaScript
class Food {
constructor(width, height) {
this.width = width;
this.height = height;
this.position = { x: 0, y: 0 };
this.generate();
}
generate(snakeBody = []) {
let newPosition;
do {
newPosition = {
x: Math.floor(Math.random() * this.width),
y: Math.floor(Math.random() * this.height)
};
} while (this.isOnSnake(newPosition, snakeBody));
this.position = newPosition;
}
isOnSnake(position, snakeBody) {
return snakeBody.some(segment =>
segment.x === position.x && segment.y === position.y
);
}
getPosition() {
return this.position;
}
}
module.exports = Food;