Create a HTML snake game complex
- User
Create a HTML snake game complex
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 HTML snake game complex
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's create a more complex HTML Snake game using HTML, CSS, and JavaScript.
"Complex" here will include features like:
Here's the code structure:
index.html: The structure of the page, containing the canvas and score display.style.css: Basic styling for layout and appearance.script.js: The core game logic (drawing, movement, collisions, game state).1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Complex Snake Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="game-container">
<h1>Snake Game</h1>
<div id="score">Score: 0</div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div id="gameOverScreen" class="hidden">
<h2>Game Over!</h2>
<p id="finalScore"></p>
<button id="restartButton">Play Again</button>
</div>
<p>Use Arrow Keys or WASD to move.</p>
</div>
<script src="script.js"></script>
</body>
</html>
2. style.css
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #222;
color: #eee;
font-family: sans-serif;
margin: 0;
}
.game-container {
text-align: center;
background-color: #333;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
}
h1 {
margin-top: 0;
color: #0f0; /* Snake green */
}
#score {
font-size: 1.2em;
margin-bottom: 10px;
}
#gameCanvas {
border: 2px solid #0f0; /* Green border */
display: block; /* Remove extra space below canvas */
margin: 0 auto 15px auto;
background-color: #1a1a1a; /* Dark canvas background */
}
#gameOverScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 10; /* Above canvas */
}
#gameOverScreen h2 {
color: #f00; /* Red for game over */
font-size: 2em;
}
#gameOverScreen p {
font-size: 1.5em;
margin: 10px 0;
}
#restartButton {
padding: 10px 20px;
font-size: 1.2em;
cursor: pointer;
background-color: #0f0;
color: #333;
border: none;
border-radius: 5px;
transition: background-color 0.3s ease;
}
#restartButton:hover {
background-color: #0c0;
}
.hidden {
display: none !important;
}
3. script.js
How to Run:
index.html, style.css, and script.js in the same folder.index.html file in your web browser.Explanation of Complexity:
<canvas> element and its 2D context (ctx) for pixel-perfect drawing of the game state, rather than relying on multiple HTML elements.setInterval and updateGame): The heart of the game. setInterval repeatedly calls updateGame, which handles all game logic for one frame (move, check collisions, eat, draw). The interval time controls the speed.snake (an array of coordinates), food (an object with coordinates), score, direction, currentSnakeSpeed, and gameIntervalId track the complete state of the game.generateFood function ensures that food is placed in a random, empty cell that is not currently occupied by the snake.increaseSpeed function checks the score and, if a threshold is met, it clears the existing setInterval and starts a new one with a shorter delay, making the game faster.changingDirection flag and the logic in the keydown listener prevent the player from turning the snake 180 degrees (e.g., pressing 'down' immediately after pressing 'up'), which would cause instant self-collision.checkCollision returns true, endGame is called, stopping the loop, showing the score, and revealing the game over screen with a restart button. The restartButton click listener calls initGame, which resets all variables and starts a new game loop.keydown) to change the direction. Supports both Arrow Keys and WASD.This version is significantly more robust and features-rich than a basic "hello world" Snake game.
// --- Game Constants ---
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('score');
const gameOverScreen = document.getElementById('gameOverScreen');
const finalScoreDisplay = document.getElementById('finalScore');
const restartButton = document.getElementById('restartButton');
const canvasSize = 400;
const gridSize = 20; // Size of each grid cell (and snake/food segment)
const cellCount = canvasSize / gridSize; // Number of cells across/down
let gameIntervalId; // To store the interval ID for the game loop
let initialSnakeSpeed = 150; // Milliseconds per game frame (lower is faster)
let currentSnakeSpeed = initialSnakeSpeed;
// --- Game State Variables ---
let snake = [];
let food = {};
let score = 0;
let direction = 'right'; // Initial direction
let changingDirection = false; // Flag to prevent rapid direction changes
// --- Game Initialization ---
function initGame() {
// Reset game state
score = 0;
scoreDisplay.textContent = `Score: ${score}`;
direction = 'right';
changingDirection = false;
currentSnakeSpeed = initialSnakeSpeed;
gameOverScreen.classList.add('hidden');
// Create initial snake
snake = [
{ x: 10, y: 10 }, // Head
{ x: 9, y: 10 },
{ x: 8, y: 10 } // Tail
];
// Place initial food
generateFood();
// Start the game loop
if (gameIntervalId) {
clearInterval(gameIntervalId); // Clear any existing interval
}
gameIntervalId = setInterval(updateGame, currentSnakeSpeed);
}
// --- Game Loop ---
function updateGame() {
changingDirection = false; // Reset flag at the start of the frame
moveSnake();
if (checkCollision()) {
endGame();
return; // Stop updating if game over
}
if (checkFoodCollision()) {
score += 10;
scoreDisplay.textContent = `Score: ${score}`;
generateFood();
increaseSpeed(); // Check and potentially increase speed
} else {
// Remove tail if no food was eaten (snake moves)
snake.pop();
}
drawGame(); // Redraw everything
}
// --- Drawing Functions ---
function drawGame() {
// Clear canvas
ctx.fillStyle = '#1a1a1a'; // Canvas background color
ctx.fillRect(0, 0, canvasSize, canvasSize);
// Draw grid (optional, helpful for debugging/visuals)
// ctx.strokeStyle = '#333';
// for (let i = 0; i < cellCount; i++) {
// ctx.beginPath();
// ctx.moveTo(i * gridSize, 0);
// ctx.lineTo(i * gridSize, canvasSize);
// ctx.stroke();
// ctx.beginPath();
// ctx.moveTo(0, i * gridSize);
// ctx.lineTo(canvasSize, i * gridSize);
// ctx.stroke();
// }
// Draw snake
ctx.fillStyle = '#0f0'; // Snake color (green)
snake.forEach((segment, index) => {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
// Optional: Add a slight border or head indicator
if (index === 0) { // Head
ctx.strokeStyle = '#0c0'; // Darker green border for head
ctx.strokeRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
}
});
// Draw food
ctx.fillStyle = '#f00'; // Food color (red)
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}
// --- Game Logic Functions ---
function moveSnake() {
// Get the current head position
const head = { x: snake[0].x, y: snake[0].y };
// Update head position based on direction
switch (direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
// Add the new head to the beginning of the snake array
snake.unshift(head);
}
function generateFood() {
let foodX, foodY;
let foodOnSnake;
do {
// Generate random coordinates within the grid
foodX = Math.floor(Math.random() * cellCount);
foodY = Math.floor(Math.random() * cellCount);
// Check if the generated position is on the snake's body
foodOnSnake = snake.some(segment => segment.x === foodX && segment.y === foodY);
} while (foodOnSnake); // Keep generating until food is NOT on the snake
food = { x: foodX, y: foodY };
}
function checkFoodCollision() {
// Check if the snake's head is at the same position as the food
const head = snake[0];
return head.x === food.x && head.y === food.y;
}
function checkCollision() {
const head = snake[0];
// Check wall collision
const hitWall = head.x < 0 || head.x >= cellCount || head.y < 0 || head.y >= cellCount;
// Check self collision
// Check if the head's position is the same as any segment *after* the head
const hitSelf = snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y);
return hitWall || hitSelf;
}
function increaseSpeed() {
// Increase speed every 5 points, but not infinitely fast
if (score % 50 === 0 && currentSnakeSpeed > 50) { // Increase every 50 points, minimum speed 50ms
currentSnakeSpeed -= 10; // Decrease interval time
clearInterval(gameIntervalId); // Clear the old interval
gameIntervalId = setInterval(updateGame, currentSnakeSpeed); // Start new interval with faster speed
}
}
function endGame() {
clearInterval(gameIntervalId); // Stop the game loop
gameOverScreen.classList.remove('hidden'); // Show game over screen
finalScoreDisplay.textContent = `Your Final Score: ${score}`;
}
// --- Event Listeners ---
document.addEventListener('keydown', (event) => {
// Prevent rapid direction changes within the same frame
if (changingDirection) return;
changingDirection = true;
const keyPressed = event.key;
// Map keys to directions and prevent reversing
const newDirection = (() => {
if ((keyPressed === 'ArrowUp' || keyPressed === 'w') && direction !== 'down') return 'up';
if ((keyPressed === 'ArrowDown' || keyPressed === 's') && direction !== 'up') return 'down';
if ((keyPressed === 'ArrowLeft' || keyPressed === 'a') && direction !== 'right') return 'left';
if ((keyPressed === 'ArrowRight' || keyPressed === 'd') && direction !== 'left') return 'right';
return direction; // If not a valid move, keep current direction
})();
// Update direction only if it's a valid change
if (newDirection !== direction) {
direction = newDirection;
} else {
changingDirection = false; // Allow changing direction again if invalid key was pressed
}
});
restartButton.addEventListener('click', initGame);
// --- Start the game on page load ---
initGame();