create a snake game in web browser
- User
create a snake game in web browser
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
create a snake game in web browser
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a complete implementation of the classic Snake game using HTML, CSS, and JavaScript. You can copy this code into an HTML file and open it in any modern web browser to play the game.
<!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>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
margin-bottom: 10px;
}
.game-container {
position: relative;
}
#game-board {
border: 2px solid #333;
background-color: #fff;
}
.score-display {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
.controls {
margin-top: 20px;
text-align: center;
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 0 5px;
}
button:hover {
background-color: #45a049;
}
.game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
display: none;
}
.game-over h2 {
margin-top: 0;
}
</style>
</head>
<body>
<h1>Snake Game</h1>
<div class="game-container">
<canvas id="game-board" width="400" height="400"></canvas>
<div class="game-over" id="game-over">
<h2>Game Over!</h2>
<p id="final-score">Your score: 0</p>
<button id="restart-btn">Play Again</button>
</div>
</div>
<div class="score-display">
Score: <span id="score">0</span>
</div>
<div class="controls">
<p>Use arrow keys or WASD to control the snake</p>
<button id="start-btn">Start Game</button>
</div>
<script>
// Game variables
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('score');
const finalScoreDisplay = document.getElementById('final-score');
const gameOverDisplay = document.getElementById('game-over');
const startBtn = document.getElementById('start-btn');
const restartBtn = document.getElementById('restart-btn');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [];
let food = {};
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let gameSpeed = 100; // milliseconds
let gameRunning = false;
let gameLoop;
// Initialize the game
function initGame() {
snake = [
{x: 5, y: 10},
{x: 4, y: 10},
{x: 3, y: 10}
];
direction = 'right';
nextDirection = 'right';
score = 0;
scoreDisplay.textContent = score;
gameSpeed = 100;
gameRunning = true;
placeFood();
gameOverDisplay.style.display = 'none';
}
// Place food at random position
function placeFood() {
food = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
// Make sure food doesn't appear on snake
for (let segment of snake) {
if (segment.x === food.x && segment.y === food.y) {
return placeFood();
}
}
}
// Draw the game elements
function draw() {
// Clear the canvas
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the snake
ctx.fillStyle = '#4CAF50';
for (let segment of snake) {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 1, gridSize - 1);
}
// Draw the food
ctx.fillStyle = '#f44336';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 1, gridSize - 1);
}
// Update the game state
function update() {
// Update direction
direction = nextDirection;
// Calculate new head position
const head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
// Check for collisions
if (
head.x < 0 || head.x >= tileCount ||
head.y < 0 || head.y >= tileCount ||
snake.some(segment => segment.x === head.x && segment.y === head.y)
) {
gameOver();
return;
}
// Add new head
snake.unshift(head);
// Check if snake ate food
if (head.x === food.x && head.y === food.y) {
score++;
scoreDisplay.textContent = score;
// Increase speed slightly every 5 points
if (score % 5 === 0 && gameSpeed > 50) {
gameSpeed -= 5;
clearInterval(gameLoop);
gameLoop = setInterval(gameStep, gameSpeed);
}
placeFood();
} else {
// Remove tail if no food was eaten
snake.pop();
}
}
// Game step (update + draw)
function gameStep() {
update();
draw();
}
// Game over
function gameOver() {
gameRunning = false;
clearInterval(gameLoop);
finalScoreDisplay.textContent = `Your score: ${score}`;
gameOverDisplay.style.display = 'block';
}
// Event listeners
document.addEventListener('keydown', (e) => {
if (!gameRunning) return;
// Prevent opposite direction movement
switch (e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (direction !== 'down') nextDirection = 'up';
break;
case 'ArrowDown':
case 's':
case 'S':
if (direction !== 'up') nextDirection = 'down';
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (direction !== 'right') nextDirection = 'left';
break;
case 'ArrowRight':
case 'd':
case 'D':
if (direction !== 'left') nextDirection = 'right';
break;
}
});
startBtn.addEventListener('click', () => {
if (!gameRunning) {
initGame();
draw();
startBtn.textContent = 'Restart Game';
} else {
// If game is already running, restart it
clearInterval(gameLoop);
initGame();
draw();
}
gameLoop = setInterval(gameStep, gameSpeed);
});
restartBtn.addEventListener('click', () => {
clearInterval(gameLoop);
initGame();
draw();
gameLoop = setInterval(gameStep, gameSpeed);
});
// Initial draw
draw();
</script>
</body>
</html>
.html extension (e.g., snake-game.html)You can customize the game by modifying the CSS styles or adjusting the JavaScript variables like gridSize or gameSpeed.