Fix this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake…
- User
Fix this:
- Assistant
Fix this:
Your code is mostly fine, but there is a small issue with touch event handling: you're using touchmove to detect swipes, which causes repeated direction changes as the finger moves, instead of detecting the swipe once per gesture. Swipe detection is typically done on touchend to measure the total distance moved during the touch.
Also, the condition that checks if startX or startY is falsy (if (!startX || !startY) return;) can cause problems if the swipe starts near coordinate 0 (which is valid on the screen).
Here is a fixed version with these improvements:
touchend to detect swipe direction instead of touchmove.startX and startY.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Snake Game (Swipe Only)</title>
<style>
body {
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
background: #000;
color: #fff;
font-family: sans-serif;
user-select: none;
-webkit-user-select: none;
}
canvas {
background: #111;
margin-top: 10px;
touch-action: none;
}
#score {
font-size: 18px;
margin-top: 10px;
}
</style>
</head>
<body>
<h2>Snake Game</h2>
<div id="score">Score: 0</div>
<canvas id="game" width="300" height="300"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const box = 15;
const rows = canvas.height / box;
const cols = canvas.width / box;
const scoreText = document.getElementById('score');
let snake = [{x: 5, y: 5}];
let direction = 'right';
let apples = spawnApples(3);
let score = 0;
function spawnApples(count) {
let result = [];
while (result.length < count) {
let apple = {
x: Math.floor(Math.random() * cols),
y: Math.floor(Math.random() * rows)
};
if (!result.some(a => a.x === apple.x && a.y === apple.y) &&
!snake.some(s => s.x === apple.x && s.y === apple.y)) {
result.push(apple);
}
}
return result;
}
function changeDirection(dir) {
if (dir === 'up' && direction !== 'down') direction = 'up';
else if (dir === 'down' && direction !== 'up') direction = 'down';
else if (dir === 'left' && direction !== 'right') direction = 'left';
else if (dir === 'right' && direction !== 'left') direction = 'right';
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? 'lime' : 'green';
ctx.fillRect(snake[i].x * box, snake[i].y * box, box, box);
}
for (const apple of apples) {
ctx.fillStyle = 'red';
ctx.fillRect(apple.x * box, apple.y * box, box, box);
}
}
function update() {
const head = {...snake[0]};
if (direction === 'up') head.y--;
if (direction === 'down') head.y++;
if (direction === 'left') head.x--;
if (direction === 'right') head.x++;
if (head.x < 0 || head.x >= cols || head.y < 0 || head.y >= rows) {
resetGame();
return;
}
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
resetGame();
return;
}
}
snake.unshift(head);
const eaten = apples.findIndex(a => a.x === head.x && a.y === head.y);
if (eaten >= 0) {
apples.splice(eaten, 1);
apples = apples.concat(spawnApples(1));
score += 10;
scoreText.textContent = 'Score: ' + score;
} else {
snake.pop();
}
draw();
}
function resetGame() {
snake = [{x: 5, y: 5}];
direction = 'right';
apples = spawnApples(3);
score = 0;
scoreText.textContent = 'Score: 0';
}
setInterval(update, 150);
// Swipe gesture support only - use touchstart and touchend to detect swipe
let startX = null;
let startY = null;
canvas.addEventListener('touchstart', e => {
const t = e.touches[0];
startX = t.clientX;
startY = t.clientY;
}, {passive: true});
canvas.addEventListener('touchend', e => {
if (startX === null || startY === null) return;
const t = e.changedTouches[0];
const dx = t.clientX - startX;
const dy = t.clientY - startY;
const threshold = 30; // minimum distance to count as a swipe
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > threshold) changeDirection('right');
else if (dx < -threshold) changeDirection('left');
} else {
if (dy > threshold) changeDirection('down');
else if (dy < -threshold) changeDirection('up');
}
startX = null;
startY = null;
}, {passive: true});
</script>
</body>
</html>
Summary of fixes:
touchmove to touchend event to avoid multiple direction changes per swipe.changedTouches[0] on touchend to get finger position at the end of the swipe.startX === null and startY === null instead of falsy, so that positions near 0 are handled correctly.else if in changeDirection to avoid multiple direction changes from one call.Try this updated code on your device; swipe gestures should now change direction only once per swipe, and the detection should be more reliable.
Not yet included in a published release.