Program snake in html make it good
- User
Program snake in html make it good
- Assistant
Sure! Here's a simple yet nicely functional Snake game implemented with HTML, CSS, and JavaScript. You can copy and paste this into an
.htmlfile and open it in your browser to play.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Snake Game</title> <style> body { background: #222; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #eee; user-select: none; } .game-container { background-color: #111; border: 3px solid #0f0; border-radius: 10px; padding: 20px; text-align: center; width: max-content; } canvas { background-color: #000; display: block; margin: 0 auto; border-radius: 8px; } #scoreboard { margin-top: 10px; font-size: 18px; letter-spacing: 1px; } #game-over { color: #f00; font-size: 24px; margin-top: 10px; display: none; } button { margin-top: 15px; padding: 8px 16px; font-size: 16px; cursor: pointer; border: none; border-radius: 6px; background-color: #0f0; color: #000; transition: background-color 0.3s ease; } button:hover { background-color: #0c0; } </style> </head> <body> <div class="game-container"> <canvas id="game" width="400" height="400"></canvas> <div id="scoreboard">Score: 0</div> <div id="game-over">Game Over! Press Restart to play again.</div> <button id="restart-btn" style="display:none;">Restart</button> </div> <script> (() => { const canvas = document.getElementById('game'); const ctx = canvas.getContext('2d'); const scoreboard = document.getElementById('scoreboard'); const gameOverText = document.getElementById('game-over'); const restartBtn = document.getElementById('restart-btn'); const gridSize = 20; const tileCount = canvas.width / gridSize; let snake = [ {x: 9, y: 9}, ]; let velocityX = 0; let velocityY = 0; let food = spawnFood(); let score = 0; let gameRunning = false; let gameInterval; function spawnFood() { let x, y; // Ensure food doesn't spawn on the snake do { x = Math.floor(Math.random() * tileCount); y = Math.floor(Math.random() * tileCount); } while (snake.some(segment => segment.x === x && segment.y === y)); return {x, y}; } function resetGame() { snake = [ {x: 9, y: 9}, ]; velocityX = 0; velocityY = 0; food = spawnFood(); score = 0; scoreboard.textContent = `Score: ${score}`; gameOverText.style.display = 'none'; restartBtn.style.display = 'none'; gameRunning = true; if (gameInterval) clearInterval(gameInterval); gameInterval = setInterval(gameLoop, 100); } function gameLoop() { update(); draw(); } function update() { // Update snake position only if moving if (velocityX === 0 && velocityY === 0) return; const head = { x: snake[0].x + velocityX, y: snake[0].y + velocityY }; // Wall collision if ( head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount ) { endGame(); return; } // Self collision if (snake.some(segment => segment.x === head.x && segment.y === head.y)) { endGame(); return; } snake.unshift(head); // Eating food if (head.x === food.x && head.y === food.y) { score++; scoreboard.textContent = `Score: ${score}`; food = spawnFood(); } else { snake.pop(); // Remove tail if no food eaten } } function draw() { // Clear canvas ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw food ctx.fillStyle = '#f00'; ctx.shadowColor = '#f00'; ctx.shadowBlur = 10; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); ctx.shadowBlur = 0; // Draw snake for (let i = 0; i < snake.length; i++){ const segment = snake[i]; // Color gradient for snake body const greenVal = 155 + Math.round((100 * i) / snake.length); ctx.fillStyle = `rgb(0, ${greenVal}, 0)`; ctx.shadowColor = `rgb(0, ${greenVal}, 0)`; ctx.shadowBlur = 8; ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize); } ctx.shadowBlur = 0; } function changeDirection(event) { const keyPressed = event.key; const goingUp = velocityY === -1; const goingDown = velocityY === 1; const goingRight = velocityX === 1; const goingLeft = velocityX === -1; if (keyPressed === 'ArrowUp' && !goingDown) { velocityX = 0; velocityY = -1; gameRunning = true; } else if (keyPressed === 'ArrowDown' && !goingUp) { velocityX = 0; velocityY = 1; gameRunning = true; } else if (keyPressed === 'ArrowLeft' && !goingRight) { velocityX = -1; velocityY = 0; gameRunning = true; } else if (keyPressed === 'ArrowRight' && !goingLeft) { velocityX = 1; velocityY = 0; gameRunning = true; } } function endGame() { gameRunning = false; clearInterval(gameInterval); gameOverText.style.display = 'block'; restartBtn.style.display = 'inline-block'; } restartBtn.addEventListener('click', () => { resetGame(); }); window.addEventListener('keydown', changeDirection); // Initialize game draw(); // initial screen })(); </script> </body> </html>Features of this Snake game:
- 20x20 grid snake.
- Arrow keys to control turn (no reversing direction).
- Score displayed and updated.
- Food spawned randomly, not overlapping snake.
- Game ends on hitting walls or snake body.
- Restart button after game over.
- Nice green gradient snake body with glow effect.
- Responsive canvas size: fixed 400x400, easy to scale.
Open this file and use arrow keys to start moving the snake and have fun!
If you want me to add any features or polish, just ask!
- User
Make it touchscreen
- Assistant
Got it! I'll enhance the Snake game so that it supports touchscreen controls with swipe gestures, in addition to keyboard arrows.
Here’s what I’ll do:
- Detect swipe directions on the canvas (up, down, left, right).
- On swipe, change snake direction accordingly.
- Keep existing keyboard controls.
Swipe detection will be simple — track touch start position and touch end position, compute delta, and decide swipe direction if threshold exceeded.
Here’s the updated full code with touchscreen swipe support added:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <title>Snake Game (Touch & Keyboard)</title> <style> body { background: #222; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #eee; user-select: none; -webkit-tap-highlight-color: transparent; } .game-container { background-color: #111; border: 3px solid #0f0; border-radius: 10px; padding: 20px; text-align: center; width: max-content; touch-action: none; } canvas { background-color: #000; display: block; margin: 0 auto; border-radius: 8px; touch-action: none; } #scoreboard { margin-top: 10px; font-size: 18px; letter-spacing: 1px; } #game-over { color: #f00; font-size: 24px; margin-top: 10px; display: none; } button { margin-top: 15px; padding: 8px 16px; font-size: 16px; cursor: pointer; border: none; border-radius: 6px; background-color: #0f0; color: #000; transition: background-color 0.3s ease; } button:hover { background-color: #0c0; } </style> </head> <body> <div class="game-container"> <canvas id="game" width="400" height="400" aria-label="Snake game" role="img"></canvas> <div id="scoreboard">Score: 0</div> <div id="game-over" role="alert" aria-live="assertive">Game Over! Press Restart to play again.</div> <button id="restart-btn" style="display:none;">Restart</button> </div> <script> (() => { const canvas = document.getElementById('game'); const ctx = canvas.getContext('2d'); const scoreboard = document.getElementById('scoreboard'); const gameOverText = document.getElementById('game-over'); const restartBtn = document.getElementById('restart-btn'); const gridSize = 20; const tileCount = canvas.width / gridSize; let snake = [ {x: 9, y: 9}, ]; let velocityX = 0; let velocityY = 0; let food = spawnFood(); let score = 0; let gameRunning = false; let gameInterval; // Variables for touch swipe detection let touchStartX = 0; let touchStartY = 0; const swipeThreshold = 30; // minimum px required to register swipe function spawnFood() { let x, y; do { x = Math.floor(Math.random() * tileCount); y = Math.floor(Math.random() * tileCount); } while (snake.some(segment => segment.x === x && segment.y === y)); return {x, y}; } function resetGame() { snake = [ {x: 9, y: 9}, ]; velocityX = 0; velocityY = 0; food = spawnFood(); score = 0; scoreboard.textContent = `Score: ${score}`; gameOverText.style.display = 'none'; restartBtn.style.display = 'none'; gameRunning = true; if (gameInterval) clearInterval(gameInterval); gameInterval = setInterval(gameLoop, 100); } function gameLoop() { update(); draw(); } function update() { if (velocityX === 0 && velocityY === 0) return; const head = { x: snake[0].x + velocityX, y: snake[0].y + velocityY }; // Wall collision if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) { endGame(); return; } // Self collision if (snake.some(segment => segment.x === head.x && segment.y === head.y)) { endGame(); return; } snake.unshift(head); if (head.x === food.x && head.y === food.y) { score++; scoreboard.textContent = `Score: ${score}`; food = spawnFood(); } else { snake.pop(); } } function draw() { ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Food with glow ctx.fillStyle = '#f00'; ctx.shadowColor = '#f00'; ctx.shadowBlur = 10; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); ctx.shadowBlur = 0; // Snake body with gradient green glow for (let i = 0; i < snake.length; i++) { const segment = snake[i]; const greenVal = 155 + Math.round((100 * i) / snake.length); ctx.fillStyle = `rgb(0, ${greenVal}, 0)`; ctx.shadowColor = `rgb(0, ${greenVal}, 0)`; ctx.shadowBlur = 8; ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize); } ctx.shadowBlur = 0; } // Change direction for keyboard & swipe function changeDirection(eventOrDirection) { let keyPressed; if (typeof eventOrDirection === "string") { // called from swipe with direction string keyPressed = eventOrDirection; } else { keyPressed = eventOrDirection.key; } const goingUp = velocityY === -1; const goingDown = velocityY === 1; const goingRight = velocityX === 1; const goingLeft = velocityX === -1; if (keyPressed === 'ArrowUp' || keyPressed === 'up') { if (!goingDown) { velocityX = 0; velocityY = -1; gameRunning = true; } } else if (keyPressed === 'ArrowDown' || keyPressed === 'down') { if (!goingUp) { velocityX = 0; velocityY = 1; gameRunning = true; } } else if (keyPressed === 'ArrowLeft' || keyPressed === 'left') { if (!goingRight) { velocityX = -1; velocityY = 0; gameRunning = true; } } else if (keyPressed === 'ArrowRight' || keyPressed === 'right') { if (!goingLeft) { velocityX = 1; velocityY = 0; gameRunning = true; } } } function endGame() { gameRunning = false; clearInterval(gameInterval); gameOverText.style.display = 'block'; restartBtn.style.display = 'inline-block'; } restartBtn.addEventListener('click', () => { resetGame(); }); window.addEventListener('keydown', changeDirection); // Touch start canvas.addEventListener('touchstart', e => { if (e.touches.length === 1) { touchStartX = e.touches[0].clientX; touchStartY = e.touches[0].clientY; } }, {passive: true}); // Touch end canvas.addEventListener('touchend', e => { if (e.changedTouches.length === 1) { const touchEndX = e.changedTouches[0].clientX; const touchEndY = e.changedTouches[0].clientY; const dx = touchEndX - touchStartX; const dy = touchEndY - touchStartY; if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > swipeThreshold) { if (dx > 0) changeDirection('right'); else changeDirection('left'); } else if (Math.abs(dy) > swipeThreshold) { if (dy > 0) changeDirection('down'); else changeDirection('up'); } } }, {passive: true}); // Initialize game with draw only, waits for arrow or swipe to start moving draw(); })(); </script> </body> </html>
How touchscreen controls work:
- Swipe right = turn snake right (unless currently moving left)
- Swipe left = turn snake left (unless currently moving right)
- Swipe up = turn snake up (unless currently moving down)
- Swipe down = turn snake down (unless currently moving up)
- Keyboard arrows still work as before.
- Swipe threshold to avoid accidental tiny moves.
Try on a touchscreen device or emulator — swipe anywhere on the canvas to control!
Let me know if you'd like me to add on-screen buttons as another option.