can you code a simple snake game in web (make sure to look out for bugs like instant game over's with the snake colliding on himself and make sure the edge doesnt kill you but brings you out the other side)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll create a complete Snake game for you with proper collision handling and edge wrapping. Here's the full HTML file:
html
<!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;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #000;
font-family: Arial, sans-serif;
}
.game-container {
text-align: center;
}
canvas {
border: 2px solid #fff;
background-color: #111;
}
.score {
color: #fff;
font-size: 24px;
margin-bottom: 10px;
}
.game-over {
color: #ff0000;
font-size: 32px;
margin-top: 10px;
}
.instructions {
color: #fff;
margin-top: 10px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="game-container">
<div class="score">Score: <span id="score">0</span></div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div class="instructions">Use arrow keys to move. Press Space to restart when game over.</div>
<div id="gameOver" class="game-over" style="display: none;">Game Over! Press Space to restart</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const gameOverElement = document.getElementById('gameOver');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [
{x: 10, y: 10}
];
let food = {};
let dx = 0;
let dy = 0;
let score = 0;
let gameRunning = true;
function randomTilePosition() {
return {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
}
function generateFood() {
food = randomTilePosition();
// Make sure food doesn't spawn on snake
while (snake.some(segment => segment.x === food.x && segment.y === food.y)) {
food = randomTilePosition();
}
}
function drawGame() {
// Clear canvas
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw snake
snake.forEach((segment, index) => {
if (index === 0) {
// Draw head slightly different
ctx.fillStyle = '#0a0';
} else {
ctx.fillStyle = '#0f0';
}
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 2, gridSize - 2);
});
// Draw food
ctx.fillStyle = '#f00';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 2, gridSize - 2);
}
function moveSnake() {
if (!gameRunning) return;
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
// Handle edge wrapping - snake appears on opposite side
if (head.x < 0) {
head.x = tileCount - 1;
} else if (head.x >= tileCount) {
head.x = 0;
}
if (head.y < 0) {
head.y = tileCount - 1;
} else if (head.y >= tileCount) {
head.y = 0;
}
snake.unshift(head);
// Check if food is eaten
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreElement.textContent = score;
generateFood();
} else {
snake.pop();
}
// Check for self collision - start from index 2 to avoid instant collision
// Index 0 is head, index 1 is neck, so we start checking from index 2
for (let i = 2; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
return;
}
}
}
function gameOver() {
gameRunning = false;
gameOverElement.style.display = 'block';
}
function resetGame() {
snake = [{x: 10, y: 10}];
dx = 0;
dy = 0;
score = 0;
gameRunning = true;
scoreElement.textContent = score;
gameOverElement.style.display = 'none';
generateFood();
}
function gameLoop() {
moveSnake();
drawGame();
}
document.addEventListener('keydown', (e) => {
if (!gameRunning && e.code === 'Space') {
resetGame();
return;
}
if (!gameRunning) return;
// Prevent snake from immediately reversing direction
switch (e.code) {
case 'ArrowUp':
if (dy !== 1) { // Can't go up if currently going down
dx = 0;
dy = -1;
}
break;
case 'ArrowDown':
if (dy !== -1) { // Can't go down if currently going up
dx = 0;
dy = 1;
}
break;
case 'ArrowLeft':
if (dx !== 1) { // Can't go left if currently going right
dx = -1;
dy = 0;
}
break;
case 'ArrowRight':
if (dx !== -1) { // Can't go right if currently going left
dx = 1;
dy = 0;
}
break;
}
});
// Initialize game
generateFood();
// Start game loop at 10 FPS
setInterval(gameLoop, 100);
</script>
</body>
</html>
This Snake game addresses both of your specific requirements:
Bug Prevention:
Self-collision protection: The collision check starts from index 2 (for (let i = 2; i < snake.length; i++)), which skips the head (index 0) and neck (index 1), preventing instant game overs when the snake turns
Direction reversal prevention: The movement controls check the current direction before allowing a new direction, so the snake can't immediately reverse into itself
Edge Wrapping:
When the snake hits any edge, it wraps around to the opposite side instead of dying
Left edge → appears on right side
Right edge → appears on left side
Top edge → appears on bottom
Bottom edge → appears on top
Additional Features:
Score tracking
Visual distinction between head and body
Food that doesn't spawn on the snake
Restart functionality with spacebar
Smooth 10 FPS gameplay
Just save this as an HTML file and open it in your browser to play!