o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
make a simple snake game in html
- User
make a simple snake game in html
- Assistant
Certainly! Below is a simple implementation of the classic Snake game using HTML, CSS, and JavaScript. You can copy the code into a single HTML file and run it in a web browser.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Simple Snake Game</title> <style> body { margin: 0; background: #000; } canvas { display: block; margin: 0 auto; background: #111; border: 1px solid #fff; } </style> </head> <body> <canvas id="gameCanvas" width="400" height="400"></canvas> <script> // Get the canvas and context const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Game variables const gridSize = 20; // Size of each grid cell let snake = [{ x: 200, y: 200 }]; // Initial snake position let dx = gridSize; // Horizontal velocity let dy = 0; // Vertical velocity let food = getRandomFoodPosition(); let score = 0; // Listen to keyboard events to move the snake document.addEventListener('keydown', changeDirection); // Start the game loop let game = setInterval(main, 100); function main() { if (gameEnded()) { clearInterval(game); alert('Game Over! Your score was: ' + score); return; } clearCanvas(); drawFood(); moveSnake(); drawSnake(); } function clearCanvas() { ctx.fillStyle = '#111'; ctx.fillRect(0, 0, canvas.width, canvas.height); } function drawSnake() { ctx.fillStyle = '#0f0'; snake.forEach(part => { ctx.fillRect(part.x, part.y, gridSize, gridSize); }); } function moveSnake() { // Create new head const head = { x: snake[0].x + dx, y: snake[0].y + dy }; // Add new head to the front of snake body snake.unshift(head); // Check if snake has eaten the food if (head.x === food.x && head.y === food.y) { score += 10; food = getRandomFoodPosition(); } else { // Remove the last part of snake body snake.pop(); } } function changeDirection(event) { const LEFT_KEY = 37; const UP_KEY = 38; const RIGHT_KEY = 39; const DOWN_KEY = 40; const keyPressed = event.keyCode; const goingUp = dy === -gridSize; const goingDown = dy === gridSize; const goingRight = dx === gridSize; const goingLeft = dx === -gridSize; if (keyPressed === LEFT_KEY && !goingRight) { dx = -gridSize; dy = 0; } if (keyPressed === UP_KEY && !goingDown) { dx = 0; dy = -gridSize; } if (keyPressed === RIGHT_KEY && !goingLeft) { dx = gridSize; dy = 0; } if (keyPressed === DOWN_KEY && !goingUp) { dx = 0; dy = gridSize; } } function drawFood() { ctx.fillStyle = '#f00'; ctx.fillRect(food.x, food.y, gridSize, gridSize); } function getRandomFoodPosition() { const foodX = Math.floor((Math.random() * canvas.width) / gridSize) * gridSize; const foodY = Math.floor((Math.random() * canvas.height) / gridSize) * gridSize; // Prevent food from appearing under the snake for (let i = 0; i < snake.length; i++) { if (snake[i].x === foodX && snake[i].y === foodY) { return getRandomFoodPosition(); } } return { x: foodX, y: foodY }; } function gameEnded() { // Check if snake hits the wall const head = snake[0]; const hitLeftWall = head.x < 0; const hitRightWall = head.x >= canvas.width; const hitTopWall = head.y < 0; const hitBottomWall = head.y >= canvas.height; if (hitLeftWall || hitRightWall || hitTopWall || hitBottomWall) { return true; } // Check if snake runs into itself for (let i = 1; i < snake.length; i++) { if (head.x === snake[i].x && head.y === snake[i].y) { return true; } } return false; } </script> </body> </html>How the Code Works
- Canvas Setup: A
<canvas>element is used for drawing the game graphics. - Game Variables:
snake: An array of objects representing the snake's body parts.dxanddy: The current velocity of the snake.food: The position of the current food item.score: The player's score.
- Event Listener:
- The
keydownevent is used to change the snake's direction.
- The
- Main Game Loop (
mainfunction):- Checks for game over conditions.
- Clears the canvas.
- Draws the food and snake.
- Moves the snake.
- Movement and Drawing:
- The snake moves by adding a new head in the direction of movement and removing the tail unless it has eaten food.
- The snake and food are drawn as colored rectangles on the canvas.
- Collision Detection:
- The game ends if the snake collides with the walls or itself.
Running the Game
- Copy the Code: Copy the entire code above into a text editor and save it with an
.htmlextension, for example,snake_game.html. - Open in Browser: Double-click the saved file or open it in a web browser like Chrome, Firefox, or Edge.
- Play: Use the arrow keys on your keyboard to control the snake:
- Left Arrow: Move left.
- Up Arrow: Move up.
- Right Arrow: Move right.
- Down Arrow: Move down.
Customization Ideas
- Change Speed: Adjust the interval in
setInterval(main, 100);to make the game faster or slower. - Increase Difficulty: As the score increases, decrease the interval time to make the game progressively faster.
- Add Sound Effects: Play sounds when the snake eats food or when the game ends.
- Scoring Display: Display the current score on the canvas or on the webpage.
Feel free to experiment with the code to add new features or improve the game's appearance. Enjoy coding and have fun playing your own Snake game!
- Canvas Setup: A