text
stringlengths
0
1.19k
dir = {x: 1, y: 0};
nextDir = {x: 1, y: 0};
score = 0;
alive = true;
paused = false;
tickMs = 130;
pulse = 0;
placeFood();
scoreEl.textContent = '0';
}
function placeFood() {
let valid = false;
while (!valid) {
food = { x: Math.floor(Math.random() * GRID), y: Math.floor(Math.random() * GRID) };
valid = !snake.some(s => s.x === food.x && s.y === food.y);
}
}
function dirButtons(dx, dy) {
if (dir.x === -dx && dir.y === -dy) return; // no reverse
nextDir = {x: dx, y: dy};
}
window.addEventListener('keydown', (e) => {
const k = e.key.toLowerCase();
if (k === ' ') { togglePause(); e.preventDefault(); return; }
if (k === 'arrowup' || k === 'w') dirButtons(0, -1);
else if (k === 'arrowdown' || k === 's') dirButtons(0, 1);
else if (k === 'arrowleft' || k === 'a') dirButtons(-1, 0);
else if (k === 'arrowright' || k === 'd') dirButtons(1, 0);
});
// touch swipe support
let touchStart = null;
canvas.addEventListener('touchstart', (e) => {
touchStart = e.touches[0];
}, {passive: true});
canvas.addEventListener('touchend', (e) => {
if (!touchStart) return;
const dx = e.changedTouches[0].clientX - touchStart.clientX;
const dy = e.changedTouches[0].clientY - touchStart.clientY;
if (Math.abs(dx) > Math.abs(dy)) {
dirButtons(dx > 0 ? 1 : -1, 0);
} else {
dirButtons(0, dy > 0 ? 1 : -1);
}
touchStart = null;
}, {passive: true});
function togglePause() {
if (!alive) return;
paused = !paused;
hint.textContent = paused ? 'PAUSED — SPACE to resume' : 'SPACE to pause';
}
function step() {
if (!alive || paused) return;
dir = nextDir;
const head = { x: snake[0].x + dir.x, y: snake[0].y + dir.y };
if (head.x < 0 || head.x >= GRID || head.y < 0 || head.y >= GRID ||
snake.some(s => s.x === head.x && s.y === head.y)) {
return gameOver();
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreEl.textContent = score;
placeFood();
pulse = 6;
if (tickMs > 65) tickMs -= 2;
restartTimer();
} else {
snake.pop();
}
}
function gameOver() {
alive = false;
if (score > best) {
best = score;
try { localStorage.setItem('signal-best', String(best)); } catch (e) {}
bestEl.textContent = 'BEST — ' + best;
}
overlayTitle.textContent = 'SIGNAL LOST';
overlayText.innerHTML = 'Transmission terminated at score <b style="color:var(--amber)">' + score + '</b>.<br>Reconnect to try again.';
startBtn.textContent = 'RECONNECT ▸';
overlay.classList.add('show');
}
function draw() {
ctx.fillStyle = '#030d09';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// faint grid
ctx.strokeStyle = 'rgba(62, 242, 160, 0.06)';
ctx.lineWidth = 1;