namastejs
Version:
A spiritual greeting from your JavaScript code. Because every function deserves a 'Namaste 🙏'
62 lines (48 loc) • 1.49 kB
JavaScript
const { render } = require("./render");
function randomFood(WIDTH, HEIGHT, snake) {
let pos;
do {
pos = {
x: Math.floor(Math.random() * WIDTH),
y: Math.floor(Math.random() * HEIGHT),
};
} while (snake.some((p) => p.x === pos.x && p.y === pos.y));
return pos;
}
function update(state, config) {
if (state.paused || state.status !== "RUNNING") return;
const head = { ...state.snake[0] };
if (state.dir === "UP") head.y--;
if (state.dir === "DOWN") head.y++;
if (state.dir === "LEFT") head.x--;
if (state.dir === "RIGHT") head.x++;
const hitWall =
head.x < 0 ||
head.y < 0 ||
head.x >= config.WIDTH ||
head.y >= config.HEIGHT;
const hitSelf = state.snake.some((p) => p.x === head.x && p.y === head.y);
if (hitWall || hitSelf) {
state.status = "GAME_OVER";
state.collision = { ...head };
return;
}
state.snake.unshift(head);
if (head.x === state.food.x && head.y === state.food.y) {
state.score++;
state.speed = Math.max(config.MIN_SPEED, state.speed - 4);
state.food = randomFood(config.WIDTH, config.HEIGHT, state.snake);
} else {
state.snake.pop();
}
}
function startGame(state, config) {
state.food = randomFood(config.WIDTH, config.HEIGHT, state.snake);
function loop() {
update(state, config);
render(state, config);
setTimeout(loop, state.speed);
}
loop();
}
module.exports = { startGame };