o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
write better snake game use html
- User
write better snake game use html
- Assistant
write better snake game use html
Certainly! Below is a complete implementation of a Snake game using HTML, CSS, and JavaScript. This version includes improved features such as:
Feel free to customize and enhance it further according to your needs.
index.html):<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Snake Game</h1>
<div id="game-container">
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<button id="restart-btn" style="display:none;">Restart Game</button>
</div>
<script src="script.js"></script>
</body>
</html>
styles.css):body {
text-align: center;
background-color: #f0f0f0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
#game-container {
display: inline-block;
position: relative;
}
#gameCanvas {
background-color: #000;
border: 1px solid #333;
}
#score {
margin-top: 10px;
font-size: 20px;
}
#restart-btn {
margin-top: 10px;
padding: 10px 20px;
font-size: 16px;
}
script.js):const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score');
const restartBtn = document.getElementById('restart-btn');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let velocityX = 0;
let velocityY = 0;
let snake = [{ x: 10, y: 10 }];
let apple = { x: 5, y: 5 };
let score = 0;
let gameInterval;
let gameOver = false;
// Start the game
function startGame() {
gameOver = false;
snake = [{ x: 10, y: 10 }];
apple = { x: Math.floor(Math.random() * tileCount), y: Math.floor(Math.random() * tileCount) };
velocityX = 0;
velocityY = 0;
score = 0;
scoreEl.textContent = 'Score: 0';
restartBtn.style.display = 'none';
clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, 100);
}
function gameLoop() {
update();
draw();
if (gameOver) {
clearInterval(gameInterval);
restartBtn.style.display = 'block';
}
}
function update() {
// Move snake
const head = { x: snake[0].x + velocityX, y: snake[0].y + velocityY };
// Wrap around edges
if (head.x < 0) head.x = tileCount - 1;
if (head.x >= tileCount) head.x = 0;
if (head.y < 0) head.y = tileCount - 1;
if (head.y >= tileCount) head.y = 0;
// Check for collision with self
for (const segment of snake) {
if (head.x === segment.x && head.y === segment.y) {
gameOver = true;
return;
}
}
snake.unshift(head);
// Check for apple collision
if (head.x === apple.x && head.y === apple.y) {
score++;
scoreEl.textContent = 'Score: ' + score;
apple = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
} else {
snake.pop();
}
}
function draw() {
// Clear the canvas
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw snake
ctx.fillStyle = 'lime';
for (const segment of snake) {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
}
// Draw apple
ctx.fillStyle = 'red';
ctx.fillRect(apple.x * gridSize, apple.y * gridSize, gridSize, gridSize);
}
// Handle keyboard input
document.addEventListener('keydown', (e) => {
if (gameOver) return;
switch (e.code) {
case 'ArrowUp':
if (velocityY === 1) break;
velocityX = 0;
velocityY = -1;
break;
case 'ArrowDown':
if (velocityY === -1) break;
velocityX = 0;
velocityY = 1;
break;
case 'ArrowLeft':
if (velocityX === 1) break;
velocityX = -1;
velocityY = 0;
break;
case 'ArrowRight':
if (velocityX === -1) break;
velocityX = 1;
velocityY = 0;
break;
}
});
// Restart the game on button click
restartBtn.addEventListener('click', startGame);
// Initialize the game
startGame();
HTML Structure:
<canvas> element is used for rendering the game graphics.<div> displays the current score.<button> allows the player to restart the game after a game over.CSS Styling:
JavaScript Logic:
Variables:
canvas, ctx: For drawing on the canvas.gridSize, tileCount: Define the size of each grid cell and the number of cells.velocityX, velocityY: The current direction of the snake's movement.snake: An array representing the snake's body segments.apple: The position of the apple on the grid.score: The player's current score.gameInterval, gameOver: For controlling the game loop and game state.startGame Function:
gameLoop Function:
update() and draw() on each iteration.update Function:
draw Function:
Keyboard Input:
addEventListener on keydown events to change the snake's direction.Save the Files:
index.html, styles.css, and script.js.Open in Browser:
index.html in a modern web browser (e.g., Chrome, Firefox).Play the Game:
Add Difficulty Levels:
Improve Graphics:
Mobile Support:
Sound Effects:
High Score Tracking:
localStorage to keep track even after the browser is closed.Feel free to experiment with the code and add new features to make the game even better!
Restart Button:
startGame() to reset the game.