-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.html
More file actions
370 lines (332 loc) · 11.9 KB
/
Copy pathsnake.html
File metadata and controls
370 lines (332 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Snake</title>
<style>
:root {
--bg: #0e0f12;
--surface: #151821;
--border: rgba(255,255,255,0.08);
--text: #e8ecf1;
--muted: #9aa4b2;
--accent: #5bd0ff;
--good: #2ecc71;
--bad: #ff6b6b;
--focus: 2px solid #ffd166;
--radius: 14px;
--shadow: 0 10px 30px rgba(0,0,0,0.35);
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
background: radial-gradient(1200px 600px at 20% -10%, #1a2030 0%, var(--bg) 55%),
radial-gradient(1200px 600px at 120% 120%, #121622 0%, var(--bg) 35%);
color: var(--text);
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji", "Segoe UI Emoji";
display: grid;
grid-template-rows: auto 1fr auto;
min-height: 100dvh;
}
header, footer { display: grid; place-items: center; padding: 18px 12px; }
header {
background: linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0));
border-bottom: 1px solid rgba(255,255,255,0.06);
position: sticky; top: 0; backdrop-filter: blur(6px);
}
header h1 { margin: 0; font-size: 1.2rem; letter-spacing: 0.04em; font-weight: 700; }
header h1 span { color: var(--accent); }
main { display: grid; place-items: center; padding: 24px; }
.game-card {
background: linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.02));
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px;
width: 100%;
max-width: 560px;
}
.top-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.status { color: var(--muted); font-weight: 600; }
.status strong { color: var(--text); }
.board-wrap { position: relative; }
canvas {
width: 100%;
height: auto;
border-radius: 12px;
border: 1px solid var(--border);
background: repeating-linear-gradient(45deg, rgba(255,255,255,0.02) 0 8px, rgba(255,255,255,0.01) 8px 16px),
var(--surface);
display: block;
}
.controls { display: flex; justify-content: space-between; align-items: center; margin-top: 14px; gap: 12px; }
.btn {
background: linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
border: 1px solid rgba(255,255,255,0.12);
color: var(--text);
padding: 10px 14px;
border-radius: 10px;
cursor: pointer;
font-weight: 600; letter-spacing: 0.02em;
transition: transform 120ms ease, background 120ms ease, border-color 120ms ease;
}
.btn:hover { transform: translateY(-1px); border-color: rgba(255,255,255,0.22); }
.legend { color: var(--muted); font-size: 0.9rem; }
.overlay {
position: absolute; inset: 0; display: grid; place-items: center;
text-align: center; padding: 16px; pointer-events: none;
}
.overlay .panel {
background: rgba(0,0,0,0.45);
border: 1px solid rgba(255,255,255,0.12);
border-radius: 12px;
padding: 14px 16px;
backdrop-filter: blur(4px);
}
.panel h2 { margin: 0 0 8px 0; font-size: 1.1rem; }
.panel p { margin: 6px 0 0 0; color: var(--muted); }
footer { color: var(--muted); font-size: 0.9rem; }
</style>
</head>
<body>
<header>
<h1><span>◆</span> Snake</h1>
</header>
<main>
<section class="game-card" aria-labelledby="gameTitle">
<div class="top-row">
<div id="gameTitle" class="status" aria-live="polite">
Score: <strong id="score">0</strong> · High: <strong id="high">0</strong>
</div>
<div>
<button id="pauseBtn" class="btn" type="button" aria-pressed="false" aria-label="Pause or resume">Pause</button>
<button id="restartBtn" class="btn" type="button" aria-label="Restart game">Restart</button>
</div>
</div>
<div class="board-wrap">
<canvas id="game" role="img" aria-label="Snake game board" aria-live="off"></canvas>
<div id="overlay" class="overlay" hidden>
<div class="panel">
<h2 id="overlayTitle">Paused</h2>
<p>Press Space/P or click Pause to resume</p>
</div>
</div>
</div>
<div class="controls">
<div class="legend">Use arrows or WASD. Avoid walls and yourself.</div>
</div>
</section>
</main>
<footer>
<div>Built with ❤️. Stay hungry.</div>
</footer>
<script>
(function() {
// DOM
const canvas = document.getElementById('game');
const overlay = document.getElementById('overlay');
const overlayTitle = document.getElementById('overlayTitle');
const scoreEl = document.getElementById('score');
const highEl = document.getElementById('high');
const pauseBtn = document.getElementById('pauseBtn');
const restartBtn = document.getElementById('restartBtn');
// Settings
const GRID_SIZE = 20; // board cells per row/col
const CELL_PX = 24; // CSS pixel size per cell (scaled for DPR later)
const TICK_MS_START = 140; // starting speed
const SPEEDUP_EVERY = 5; // speed up every N food eaten
const SPEED_FACTOR = 0.92; // multiply tick interval by this
// Colors
const COLOR_BG = '#12151e';
const COLOR_GRID = 'rgba(255,255,255,0.04)';
const COLOR_SNAKE = '#5bd0ff';
const COLOR_SNAKE_HEAD = '#a1eafb';
const COLOR_FOOD = '#2ecc71';
// State
let snake = [];
let dir = { x: 1, y: 0 }; // moving right
let nextDir = { x: 1, y: 0 };
let food = null;
let score = 0;
let high = 0;
let tickMs = TICK_MS_START;
let lastTick = 0;
let running = true;
let gameOver = false;
function loadHighScore() {
const v = Number(localStorage.getItem('snake.high') || '0');
high = Number.isFinite(v) ? v : 0;
highEl.textContent = String(high);
}
function saveHighScore() {
if (score > high) {
high = score;
localStorage.setItem('snake.high', String(high));
highEl.textContent = String(high);
}
}
function setupCanvas() {
const dpr = Math.max(1, Math.floor(window.devicePixelRatio || 1));
const displaySize = GRID_SIZE * CELL_PX;
canvas.style.width = displaySize + 'px';
canvas.style.height = displaySize + 'px';
canvas.width = displaySize * dpr;
canvas.height = displaySize * dpr;
const ctx = canvas.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // scale drawing to CSS pixels
return ctx;
}
const ctx = setupCanvas();
function reset() {
snake = [
{ x: 8, y: 10 },
{ x: 7, y: 10 },
{ x: 6, y: 10 }
];
dir = { x: 1, y: 0 };
nextDir = { x: 1, y: 0 };
placeFood();
score = 0;
tickMs = TICK_MS_START;
running = true;
gameOver = false;
scoreEl.textContent = '0';
pauseBtn.setAttribute('aria-pressed', 'false');
overlay.hidden = true;
overlayTitle.textContent = 'Paused';
lastTick = 0;
}
function randInt(n) { return Math.floor(Math.random() * n); }
function placeFood() {
let x, y, tries = 0;
do {
x = randInt(GRID_SIZE);
y = randInt(GRID_SIZE);
tries++;
if (tries > 1000) break;
} while (snake.some(s => s.x === x && s.y === y));
food = { x, y };
}
function drawCell(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * CELL_PX, y * CELL_PX, CELL_PX - 1, CELL_PX - 1);
}
function drawGrid() {
ctx.fillStyle = COLOR_BG;
ctx.fillRect(0, 0, GRID_SIZE * CELL_PX, GRID_SIZE * CELL_PX);
ctx.strokeStyle = COLOR_GRID;
ctx.lineWidth = 1;
ctx.beginPath();
for (let i = 1; i < GRID_SIZE; i++) {
ctx.moveTo(i * CELL_PX + 0.5, 0);
ctx.lineTo(i * CELL_PX + 0.5, GRID_SIZE * CELL_PX);
ctx.moveTo(0, i * CELL_PX + 0.5);
ctx.lineTo(GRID_SIZE * CELL_PX, i * CELL_PX + 0.5);
}
ctx.stroke();
}
function draw() {
drawGrid();
// food
if (food) drawCell(food.x, food.y, COLOR_FOOD);
// snake
for (let i = 0; i < snake.length; i++) {
const s = snake[i];
drawCell(s.x, s.y, i === 0 ? COLOR_SNAKE_HEAD : COLOR_SNAKE);
}
}
function step() {
if (!running || gameOver) return;
dir = nextDir; // commit input at tick
const head = { x: snake[0].x + dir.x, y: snake[0].y + dir.y };
// wall collision
if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
return endGame();
}
// self collision
if (snake.some((s, i) => i > 0 && s.x === head.x && s.y === head.y)) {
return endGame();
}
snake.unshift(head);
if (food && head.x === food.x && head.y === food.y) {
score++;
scoreEl.textContent = String(score);
if (score % SPEEDUP_EVERY === 0) tickMs = Math.max(50, Math.floor(tickMs * SPEED_FACTOR));
placeFood();
saveHighScore();
} else {
snake.pop();
}
}
function endGame() {
gameOver = true;
running = false;
overlay.hidden = false;
overlayTitle.textContent = 'Game Over';
}
function gameLoop(ts) {
if (!lastTick) lastTick = ts;
const dt = ts - lastTick;
if (dt >= tickMs) {
lastTick = ts;
step();
draw();
}
requestAnimationFrame(gameLoop);
}
function setPause(state) {
running = !state;
pauseBtn.textContent = state ? 'Resume' : 'Pause';
pauseBtn.setAttribute('aria-pressed', state ? 'true' : 'false');
overlay.hidden = !state;
overlayTitle.textContent = state ? 'Paused' : 'Paused';
}
function togglePause() {
if (gameOver) return; // don't unpause game over
setPause(running);
}
function handleKey(e) {
const k = e.key;
if (k === 'p' || k === 'P' || k === ' ') {
e.preventDefault();
togglePause();
return;
}
if (!running) return;
const cur = dir; // only prevent 180 turn relative to current movement
switch (k) {
case 'ArrowUp':
case 'w': case 'W':
if (cur.y !== 1) nextDir = { x: 0, y: -1 };
break;
case 'ArrowDown':
case 's': case 'S':
if (cur.y !== -1) nextDir = { x: 0, y: 1 };
break;
case 'ArrowLeft':
case 'a': case 'A':
if (cur.x !== 1) nextDir = { x: -1, y: 0 };
break;
case 'ArrowRight':
case 'd': case 'D':
if (cur.x !== -1) nextDir = { x: 1, y: 0 };
break;
default:
return;
}
e.preventDefault();
}
pauseBtn.addEventListener('click', togglePause);
restartBtn.addEventListener('click', () => { reset(); draw(); });
window.addEventListener('keydown', handleKey);
window.addEventListener('resize', () => { setupCanvas(); draw(); });
loadHighScore();
reset();
draw();
requestAnimationFrame(gameLoop);
})();
</script>
</body>
</html>