html
html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="game-container">
<canvas id="gameCanvas"></canvas>
</div>
<div class="dpad">
<button id="up">▲</button>
<div class="horizontal-buttons">
<button id="left">◀</button>
<button id="right">▶</button>
</div>
<button id="down">▼</button>
</div>
<script src="script.js"></script>
</body>
</html>
Enter to Rename, Shift+Enter to Preview
css
css
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
/* style.css */
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #333;
color: #fff;
font-family: Arial, sans-serif;
}
.game-container {
display: flex;
justify-content: center;
align-items: center;
border: 2px solid #444;
background-color: #222;
}
canvas {
background-color: #000;
}
.dpad {
display: flex;
flex-direction: column;
Enter to Rename, Shift+Enter to Preview
js
js
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
// script.js
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Set canvas size
const tileSize = 20;
canvas.width = tileSize * 20;
canvas.height = tileSize * 20;
let snake = [{ x: tileSize * 5, y: tileSize * 5 }];
let direction = { x: tileSize, y: 0 };
let nextDirection = { x: tileSize, y: 0 };
let food = { x: tileSize * 10, y: tileSize * 10 };
let score = 0;
let lastTime = 0;
const speed = 100; // Speed in pixels per second
// Event listeners for controls using touchstart for fast response on mobile
document.getElementById("up").addEventListener("touchstart", () => setDirection(0, -1));
document.getElementById("down").addEventListener("touchstart", () => setDirection(0, 1));
document.getElementById("left").addEventListener("touchstart", () => setDirection(-1, 0));
document.getElementById("right").addEventListener("touchstart", () => setDirection(1, 0));
// Smooth game loop using requestAnimationFrame
function gameLoop(timestamp) {
const deltaTime = timestamp - lastTime;
if (deltaTime > speed) {
update();
Enter to Rename, Shift+Enter to Preview
BROWSER
Console
Run