UNPKG

by-idb

Version:

A simple terminal snake game library with no external dependencies

96 lines (81 loc) 2.38 kB
class Snake { constructor(width, height) { this.width = width; this.height = height; this.reset(); } reset() { // Initialize snake position in the center const startX = Math.floor(this.width / 2); const startY = Math.floor(this.height / 2); this.body = [ { x: startX, y: startY }, { x: startX - 1, y: startY }, { x: startX - 2, y: startY } ]; this.direction = 'right'; this.nextDirection = 'right'; } move(food) { // Update direction this.direction = this.nextDirection; // Get head position const head = { ...this.body[0] }; // Move head based on direction switch (this.direction) { case 'up': head.y--; break; case 'down': head.y++; break; case 'left': head.x--; break; case 'right': head.x++; break; } // Check if food is eaten const ateFood = head.x === food.x && head.y === food.y; // Add new head to the beginning of body array this.body.unshift(head); // Remove tail if no food was eaten if (!ateFood) { this.body.pop(); } return ateFood; } changeDirection(newDirection) { // Prevent 180-degree turns const opposites = { 'up': 'down', 'down': 'up', 'left': 'right', 'right': 'left' }; if (opposites[newDirection] !== this.direction) { this.nextDirection = newDirection; } } checkCollision() { const head = this.body[0]; // Check wall collision if ( head.x < 0 || head.x >= this.width || head.y < 0 || head.y >= this.height ) { return true; } // Check self collision for (let i = 1; i < this.body.length; i++) { if (head.x === this.body[i].x && head.y === this.body[i].y) { return true; } } return false; } } module.exports = Snake;