<!DOCTYPE html>
<html>
<head>
<title>Simple Snake Game</title>
<style>
body {
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: sans-serif;
}
#gameCanvas {
border: 2px solid black;
background-color: #ddd;
}
#score {
position: absolute;
top: 10px;
left: 10px;
font-size: 20px;
}
#gameOver {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.7);
color: white;
padding: 20px;
border-radius: 5px;
font-size: 24px;
display: none; /* Hidden by default */
}
#restartButton {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 18px;
margin-top: 10px;
}
#controls {
position: absolute;
bottom: 10px;
right: 10px;
font-size: 14px;
text-align: right;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<div id="gameOver">
Game Over!
<button id="restartButton">Restart</button>
</div>
<div id="controls">
<b>Controls:</b><br>
Arrow Keys (Up, Down, Left, Right)
</div>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const scoreDisplay = document.getElementById("score");
const gameOverScreen = document.getElementById("gameOver");
const restartButton = document.getElementById("restartButton");
// Game settings
const gridSize = 20;
const tileCountX = canvas.width / gridSize;
const tileCountY = canvas.height / gridSize;
let snake = [{x: 10, y: 10}]; // Initial snake
let food = {x: 5, y: 5}; // Initial food
let xVelocity = 0;
let yVelocity = 0;
let score = 0;
let gameRunning = false; // Flag to indicate if the game is running
// Start the game automatically
startGame();
// Function to start or restart the game
function startGame() {
snake = [{x: 10, y: 10}];
food = {x: 5, y: 5};
xVelocity = 0;
yVelocity = 0;
score = 0;
scoreDisplay.textContent = "Score: " + score;
gameOverScreen.style.display = "none";
gameRunning = true; // Set the gameRunning flag to true
clearInterval(gameInterval); // Clear any previous interval
gameInterval = setInterval(gameLoop, 100); // Adjust interval for speed
}
// Game loop
let gameInterval;
function gameLoop() {
if (!gameRunning) return; // Stop the loop if the game isn't running
update();
draw();
}
function update() {
// Update snake position
let headX = snake[0].x;
let headY = snake[0].y;
headX += xVelocity;
headY += yVelocity;
// Wrap around the edges
if (headX < 0) headX = tileCountX - 1;
if (headX >= tileCountX) headX = 0;
if (headY < 0) headY = tileCountY - 1;
if (headY >= tileCountY) headY = 0;
// Eat the food
if (headX === food.x && headY === food.y) {
score++;
scoreDisplay.textContent = "Score: " + score;
food = {
x: Math.floor(Math.random() * tileCountX),
y: Math.floor(Math.random() * tileCountY)
};
// Prevent food from spawning inside the snake
while (snake.some(segment => segment.x === food.x && segment.y === food.y)) {
food = {
x: Math.floor(Math.random() * tileCountX),
y: Math.floor(Math.random() * tileCountY)
};
}
// Add a new segment to the snake (grow)
const newHead = { x: headX, y: headY };
snake.unshift(newHead); // Add to the beginning
} else {
// Move the snake (remove tail, add head)
const newHead = { x: headX, y: headY };
snake.unshift(newHead);
snake.pop(); //remove tail segment
}
// Check for self-collision *AFTER* moving the snake
for (let i = 1; i < snake.length; i++) {
if (headX === snake[i].x && headY === snake[i].y) {
gameOver();
return;
}
}
}
function draw() {
// Clear the canvas
ctx.fillStyle = "#ddd";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the snake
ctx.fillStyle = "green";
snake.forEach(segment => {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
});
// Draw the food
ctx.fillStyle = "red";
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}
function gameOver() {
clearInterval(gameInterval); // Stop the game loop
gameRunning = false; // Set gameRunning to false
gameOverScreen.style.display = "block";
}
// Input handling
document.addEventListener("keydown", (event) => {
switch (event.key) {
case "ArrowUp":
if (yVelocity !== 1) { // Prevent instant 180-degree turn
xVelocity = 0;
yVelocity = -1;
}
break;
case "ArrowDown":
if (yVelocity !== -1) {
xVelocity = 0;
yVelocity = 1;
}
break;
case "ArrowLeft":
if (xVelocity !== 1) {
xVelocity = -1;
yVelocity = 0;
}
break;
case "ArrowRight":
if (xVelocity !== -1) {
xVelocity = 1;
yVelocity = 0;
}
break;
}
});
restartButton.addEventListener("click", startGame);
</script>
</body>
</html>
Key improvements and explanations:
- Prevention of Instant Game Over: The crucial check
if (yVelocity !== 1) (and similar for other directions) prevents the snake from immediately colliding with itself if the player tries to reverse direction. This was the primary cause of instant game overs. The check is performed before changing the velocity.
- Edge Wrapping: The code now correctly wraps the snake around the edges of the canvas. When the snake goes out of bounds, it reappears on the opposite side. The
if (headX < 0) headX = tileCountX - 1; (and similar) handles this.
gameRunning Flag: A gameRunning boolean variable is used to control the execution of the gameLoop. This prevents the update and draw functions from running after the game is over, and also ensures that the game can be properly restarted. The interval is only running when gameRunning is true. Also stops the update from running after game over.
- Clearer Game Over Handling: The
gameOver function now explicitly stops the game loop using clearInterval(gameInterval) and sets gameRunning = false;. It also displays the game over message.
- Restart Functionality: The
restartButton click listener restarts the game correctly by calling the startGame function. This re-initializes all game variables and starts a new game loop. clearInterval(gameInterval) is called in startGame to handle any lingering intervals from previous games.
- Food Placement: The code now includes a check to prevent the food from spawning inside the snake. The
while (snake.some(segment => ...)) loop ensures that the food is placed in a valid, unoccupied location.
- Initial Game Start:
startGame() is called when the page loads to start the game immediately, instead of requiring the player to press a key first.
- Clearer Code Structure: The code is broken down into functions for better organization and readability:
startGame, gameLoop, update, draw, and gameOver.
- Comments: I've added comments to explain the purpose of each section of the code.
- Score Display: The current score is displayed in the top-left corner of the screen.
- Basic Styling: Added some CSS for basic styling and positioning of the elements, including a game over screen and restart button.
This improved version addresses the previous issues, provides a much better gameplay experience, and is more robust and easier to understand. It also incorporates best practices for web development. It fixes the game over bug, implements edge wrapping, provides a restart button, and prevents food from spawning inside the snake.