Write a Snake game in HTML5
- User
Write a Snake game in HTML5
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Write a Snake game in HTML5
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a simple but fully functional Snake game implemented in HTML5 using the <canvas> element and JavaScript. You can copy this code into an .html file and open it in any modern browser to play.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game</title>
<style>
body {
background: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
color: #eee;
font-family: Arial, sans-serif;
user-select: none;
}
canvas {
background: #000;
display: block;
margin: 0 auto;
border: 2px solid #0f0;
}
#score {
text-align: center;
margin-top: 10px;
font-size: 1.2rem;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20; // size of each cell in pixels
const tileCount = canvas.width / gridSize; // number of cells per row/column
let snake = [
{ x: 9, y: 9 },
];
let velocity = { x: 0, y: 0 };
let food = { x: 0, y: 0 };
let score = 0;
let gameOver = false;
function placeFood() {
food.x = Math.floor(Math.random() * tileCount);
food.y = Math.floor(Math.random() * tileCount);
// Make sure food doesn't spawn on the snake
for (let segment of snake) {
if (segment.x === food.x && segment.y === food.y) {
placeFood();
return;
}
}
}
function draw() {
// Clear the canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the food
ctx.fillStyle = '#f00';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
// Draw the snake
ctx.fillStyle = '#0f0';
for (let segment of snake) {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
}
}
function update() {
if (gameOver) return;
// Move snake by adding new head based on velocity
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
// Wrap around the edges (optional, comment out if you want wall collision)
if (head.x < 0) head.x = tileCount - 1;
if (head.x >= tileCount) head.x = 0;
if (head.y < 0) head.y = tileCount - 1;
if (head.y >= tileCount) head.y = 0;
// Check collision with self
for (let segment of snake) {
if (segment.x === head.x && segment.y === head.y) {
gameOver = true;
alert('Game Over! Your score: ' + score);
resetGame();
return;
}
}
snake.unshift(head);
// Check if snake ate the food
if (head.x === food.x && head.y === food.y) {
score++;
document.getElementById('score').textContent = 'Score: ' + score;
placeFood();
} else {
// Remove tail if no food eaten
snake.pop();
}
}
function resetGame() {
snake = [{ x: 9, y: 9 }];
velocity = { x: 0, y: 0 };
score = 0;
gameOver = false;
document.getElementById('score').textContent = 'Score: 0';
placeFood();
}
// Handle keyboard input
window.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (velocity.y === 1) break; // prevent reverse
velocity = { x: 0, y: -1 };
break;
case 'ArrowDown':
case 's':
case 'S':
if (velocity.y === -1) break;
velocity = { x: 0, y: 1 };
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (velocity.x === 1) break;
velocity = { x: -1, y: 0 };
break;
case 'ArrowRight':
case 'd':
case 'D':
if (velocity.x === -1) break;
velocity = { x: 1, y: 0 };
break;
}
});
// Game loop
function gameLoop() {
update();
draw();
}
placeFood();
setInterval(gameLoop, 100); // 10 frames per second
})();
</script>
</body>
</html>
If you want the snake to die when hitting the wall instead of wrapping, just comment out or remove the wrap-around code in the update() function.
Let me know if you want me to add features like levels, speed increase, or mobile controls!
Give me full single-file code
Sure! The code I provided earlier is already a full single-file HTML document that you can save as snake.html and open directly in your browser.
For your convenience, here it is again in one complete block — just copy and paste into a file and run:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake Game</title>
<style>
body {
background: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
color: #eee;
font-family: Arial, sans-serif;
user-select: none;
flex-direction: column;
}
canvas {
background: #000;
display: block;
margin: 0 auto;
border: 2px solid #0f0;
}
#score {
text-align: center;
margin-top: 10px;
font-size: 1.2rem;
}
</style>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20; // size of each cell in pixels
const tileCount = canvas.width / gridSize; // number of cells per row/column
let snake = [
{ x: 9, y: 9 },
];
let velocity = { x: 0, y: 0 };
let food = { x: 0, y: 0 };
let score = 0;
let gameOver = false;
function placeFood() {
food.x = Math.floor(Math.random() * tileCount);
food.y = Math.floor(Math.random() * tileCount);
// Make sure food doesn't spawn on the snake
for (let segment of snake) {
if (segment.x === food.x && segment.y === food.y) {
placeFood();
return;
}
}
}
function draw() {
// Clear the canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the food
ctx.fillStyle = '#f00';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
// Draw the snake
ctx.fillStyle = '#0f0';
for (let segment of snake) {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
}
}
function update() {
if (gameOver) return;
// Move snake by adding new head based on velocity
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
// Wrap around the edges (optional, comment out if you want wall collision)
if (head.x < 0) head.x = tileCount - 1;
if (head.x >= tileCount) head.x = 0;
if (head.y < 0) head.y = tileCount - 1;
if (head.y >= tileCount) head.y = 0;
// Check collision with self
for (let segment of snake) {
if (segment.x === head.x && segment.y === head.y) {
gameOver = true;
alert('Game Over! Your score: ' + score);
resetGame();
return;
}
}
snake.unshift(head);
// Check if snake ate the food
if (head.x === food.x && head.y === food.y) {
score++;
document.getElementById('score').textContent = 'Score: ' + score;
placeFood();
} else {
// Remove tail if no food eaten
snake.pop();
}
}
function resetGame() {
snake = [{ x: 9, y: 9 }];
velocity = { x: 0, y: 0 };
score = 0;
gameOver = false;
document.getElementById('score').textContent = 'Score: 0';
placeFood();
}
// Handle keyboard input
window.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (velocity.y === 1) break; // prevent reverse
velocity = { x: 0, y: -1 };
break;
case 'ArrowDown':
case 's':
case 'S':
if (velocity.y === -1) break;
velocity = { x: 0, y: 1 };
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (velocity.x === 1) break;
velocity = { x: -1, y: 0 };
break;
case 'ArrowRight':
case 'd':
case 'D':
if (velocity.x === -1) break;
velocity = { x: 1, y: 0 };
break;
}
});
// Game loop
function gameLoop() {
update();
draw();
}
placeFood();
setInterval(gameLoop, 100); // 10 frames per second
})();
</script>
</body>
</html>
snake.html.If you want me to add any features or explain how it works, just ask!