o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Create Code HTML CSS Javascript For Game Snake
- User
Create Code HTML CSS Javascript For Game Snake
- Assistant
Create Code HTML CSS Javascript For Game Snake
Sure! Below is a simple implementation of the classic Snake game using HTML, CSS, and JavaScript. You can copy the entire code into a single HTML file (e.g., index.html) and open it in your web browser to play the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
background-color: #f0f0f0;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
margin: 0;
font-family: Arial, sans-serif;
}
#game-container {
position: relative;
}
#game-board {
background-color: #000;
display: block;
border: 2px solid #333;
}
#score {
position: absolute;
top: -40px;
left: 0;
color: #333;
font-size: 24px;
}
#game-over {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
color: red;
font-size: 36px;
display: none;
}
</style>
</head>
<body>
<div id="game-container">
<div id="score">Score: 0</div>
<canvas id="game-board" width="400" height="400"></canvas>
<div id="game-over">Game Over<br>Press Enter to Restart</div>
</div>
<script>
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const gameOverElement = document.getElementById('game-over');
const box = 20; // Size of each grid box
const canvasSize = 400;
const canvasBoxes = canvasSize / box;
let snake = [];
snake[0] = { x: 9 * box, y: 10 * box };
let direction = 'RIGHT';
let food = getRandomFood();
let score = 0;
let game;
// Listen to keyboard events
document.addEventListener('keydown', setDirection);
function setDirection(event) {
const key = event.keyCode;
if (key === 37 && direction !== 'RIGHT') {
direction = 'LEFT';
} else if (key === 38 && direction !== 'DOWN') {
direction = 'UP';
} else if (key === 39 && direction !== 'LEFT') {
direction = 'RIGHT';
} else if (key === 40 && direction !== 'UP') {
direction = 'DOWN';
} else if (key === 13 && gameOverElement.style.display === 'block') {
restartGame();
}
}
// Function to generate random food position
function getRandomFood() {
return {
x: Math.floor(Math.random() * canvasBoxes) * box,
y: Math.floor(Math.random() * canvasBoxes) * box
};
}
// Collision detection
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
// Draw everything
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? '#4caf50' : '#8bc34a';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = '#fff';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// Draw food
ctx.fillStyle = '#ff5252';
ctx.fillRect(food.x, food.y, box, box);
// Old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Update the head position based on direction
if (direction === 'LEFT') snakeX -= box;
if (direction === 'UP') snakeY -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'DOWN') snakeY += box;
// Wrap around the board
/*
if (snakeX < 0) snakeX = canvasSize - box;
if (snakeX >= canvasSize) snakeX = 0;
if (snakeY < 0) snakeY = canvasSize - box;
if (snakeY >= canvasSize) snakeY = 0;
*/
// Game over conditions
if (snakeX < 0 || snakeX >= canvasSize || snakeY < 0 || snakeY >= canvasSize || collision({x: snakeX, y: snakeY}, snake)) {
clearInterval(game);
gameOverElement.style.display = 'block';
return;
}
// If snake eats the food
if (snakeX === food.x && snakeY === food.y) {
score++;
scoreElement.innerHTML = "Score: " + score;
food = getRandomFood();
} else {
// Remove the last part of the snake
snake.pop();
}
// Add new head
let newHead = {
x: snakeX,
y: snakeY
};
snake.unshift(newHead);
}
function restartGame() {
snake = [];
snake[0] = { x: 9 * box, y: 10 * box };
direction = 'RIGHT';
score = 0;
scoreElement.innerHTML = "Score: 0";
food = getRandomFood();
gameOverElement.style.display = 'none';
clearInterval(game);
game = setInterval(draw, 100);
}
// Start the game
game = setInterval(draw, 100);
</script>
</body>
</html>
HTML Structure:
<canvas> element serves as the game board where the snake and food are drawn.<div> displays the current score.<div> shows the "Game Over" message when the game ends.CSS Styling:
JavaScript Logic:
Enter key restarts the game after a game over.getRandomFood(): Generates a new food position at random.collision(): Checks if the snake has collided with itself.draw(): Clears the canvas and redraws the snake and food. It also updates the snake's position, checks for collisions, and handles food consumption.restartGame(): Resets the game state to start a new game.setInterval to repeatedly call the draw() function every 100 milliseconds, controlling the game's speed.setInterval(draw, 100); to make the game faster or slower. A smaller number means a faster game.width and height attributes of the <canvas> to make the game area larger or smaller. Ensure that the box size divides evenly into the canvas size.fillStyle properties in the JavaScript and CSS to customize the colors of the snake, food, and game board.draw() function that wraps the snake around the board edges instead of ending the game when the snake hits a wall.Feel free to enhance and modify the game as per your preferences. Enjoy coding and playing your Snake game!
Not yet included in a published release.