gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Fix this: <!DOCTYPE html> <html> <head> <title>Touchscreen Snake Game</title> <style>…
- User
Fix this:
- Assistant
Your code needs the missing game functions (
drawSnake,drawFood,moveSnake, andcheckCollision) and some fixes to make the snake move properly and respond to touch swipe controls. I've completed and fixed your Snake game based on your structure and touch support. Here's a full working example:<!DOCTYPE html> <html> <head> <title>Touchscreen Snake Game</title> <style> canvas { background-color: #000; display: block; margin: 0 auto; border: 2px solid #0f0; touch-action: none; /* Important for touch events */ } body { text-align: center; color: #0f0; font-family: monospace; } #score { font-size: 20px; margin-bottom: 10px; } </style> </head> <body> <div id="score">Score: 0</div> <canvas id="gameCanvas" width="400" height="400"></canvas> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const gridSize = 20; const gridWidth = canvas.width / gridSize; const gridHeight = canvas.height / gridSize; let snake = [{ x: Math.floor(gridWidth/2), y: Math.floor(gridHeight/2) }]; let food = generateFood(); let dx = 1; let dy = 0; let score = 0; let gameOver = false; let touchStartX = null; let touchStartY = null; const swipeThreshold = 30; function generateFood() { let foodX, foodY; // Generate food, but make sure it does not appear inside snake while(true) { foodX = Math.floor(Math.random() * gridWidth); foodY = Math.floor(Math.random() * gridHeight); if(!snake.some(segment => segment.x === foodX && segment.y === foodY)) break; } return { x: foodX, y: foodY }; } function draw() { // Clear canvas ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); drawFood(); drawSnake(); } function drawSnake() { ctx.fillStyle = '#0f0'; snake.forEach((segment, index) => { ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize); // Optionally, add a darker shade for the tail or gradient for style if(index === 0) { // Head: draw a different color or border ctx.strokeStyle = '#fff'; ctx.lineWidth = 1; ctx.strokeRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize); } }); } function drawFood() { ctx.fillStyle = '#f00'; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); } function moveSnake() { // Compute new head position let head = { x: snake[0].x + dx, y: snake[0].y + dy }; // Wrap around the edges if(head.x < 0) head.x = gridWidth - 1; else if(head.x >= gridWidth) head.x = 0; if(head.y < 0) head.y = gridHeight - 1; else if(head.y >= gridHeight) head.y = 0; // Check collision with self if(snake.some(segment => segment.x === head.x && segment.y === head.y)) { gameOver = true; alert('Game Over! Your score: ' + score); resetGame(); return; } snake.unshift(head); // Check if food eaten if(head.x === food.x && head.y === food.y) { score++; document.getElementById('score').textContent = 'Score: ' + score; food = generateFood(); } else { // Remove tail snake.pop(); } } // Reset game on game over function resetGame() { snake = [{ x: Math.floor(gridWidth/2), y: Math.floor(gridHeight/2) }]; dx = 1; dy = 0; score = 0; document.getElementById('score').textContent = 'Score: ' + score; gameOver = false; food = generateFood(); } // Touch input handler function handleTouch(e) { e.preventDefault(); if(gameOver) return; if(e.type === 'touchstart'){ const touch = e.changedTouches[0]; touchStartX = touch.clientX; touchStartY = touch.clientY; } else if (e.type === 'touchend') { const touch = e.changedTouches[0]; const deltaX = touch.clientX - touchStartX; const deltaY = touch.clientY - touchStartY; if(Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > swipeThreshold) { // Horizontal swipe if(deltaX > 0 && dx !== -1) { dx = 1; dy = 0; } else if(deltaX < 0 && dx !== 1) { dx = -1; dy = 0; } } else if(Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > swipeThreshold) { // Vertical swipe if(deltaY > 0 && dy !== -1) { dx = 0; dy = 1; } else if(deltaY < 0 && dy !== 1) { dx = 0; dy = -1; } } } } canvas.addEventListener('touchstart', handleTouch, {passive:false}); canvas.addEventListener('touchend', handleTouch, {passive:false}); canvas.addEventListener('touchmove', e => e.preventDefault(), {passive:false}); // Add keyboard controls as well (optional) window.addEventListener('keydown', e => { if(gameOver) return; switch(e.key) { case 'ArrowUp': case 'w': case 'W': if(dy !== 1) { dx = 0; dy = -1; } break; case 'ArrowDown': case 's': case 'S': if(dy !== -1) { dx = 0; dy = 1; } break; case 'ArrowLeft': case 'a': case 'A': if(dx !== 1) { dx = -1; dy = 0; } break; case 'ArrowRight': case 'd': case 'D': if(dx !== -1) { dx = 1; dy = 0; } break; } }); let lastMoveTime = 0; const moveInterval = 100; // milliseconds between moves function gameLoop(timestamp) { if(gameOver) return; if(!lastMoveTime) lastMoveTime = timestamp; if(timestamp - lastMoveTime > moveInterval) { moveSnake(); draw(); lastMoveTime = timestamp; } requestAnimationFrame(gameLoop); } draw(); requestAnimationFrame(gameLoop); </script> </body> </html>What was fixed/added:
- Implemented missing functions:
drawSnake,drawFood,moveSnake. - Snake moves on a fixed interval, independent of your
requestAnimationFramerefresh rate, which is smoother and consistent speed. - Prevents snake from reversing direction into itself.
- Added wrapping around edges (snake appears on opposite side).
- Snake collision with itself triggers game over, with reset capability.
- Food never spawns on the snake.
- Touch controls detect swipes (left/right/up/down) to change direction.
- Score displayed above canvas and updates when eating food.
- Optional: keyboard controls added so you can control with arrow keys or WASD.
- Prevent default scrolling on touch events.
Try it on your device — swipe inside the black canvas to change direction! Let me know if you want to add difficulty levels or enhancements.
- Implemented missing functions: