diff --git a/static/js/pacman.js b/static/js/pacman.js index 9a25542..0068d63 100644 --- a/static/js/pacman.js +++ b/static/js/pacman.js @@ -213,6 +213,75 @@ function movePacman(e) { if (k === "ArrowRight") { pacman.dx = PACMAN_SPEED; pacman.dy = 0; } } +// Add touch controls +let touchStartX = 0; +let touchStartY = 0; + +function handleTouchStart(e) { + touchStartX = e.touches[0].clientX; + touchStartY = e.touches[0].clientY; + e.preventDefault(); +} + +function handleTouchMove(e) { + if (!touchStartX || !touchStartY) return; + + const touchEndX = e.touches[0].clientX; + const touchEndY = e.touches[0].clientY; + + const diffX = touchStartX - touchEndX; + const diffY = touchStartY - touchEndY; + + // Determine the dominant direction + if (Math.abs(diffX) > Math.abs(diffY)) { + // Horizontal swipe + if (diffX > 0) { + // Left swipe + pacman.dx = -PACMAN_SPEED; + pacman.dy = 0; + } else { + // Right swipe + pacman.dx = PACMAN_SPEED; + pacman.dy = 0; + } + } else { + // Vertical swipe + if (diffY > 0) { + // Up swipe + pacman.dx = 0; + pacman.dy = -PACMAN_SPEED; + } else { + // Down swipe + pacman.dx = 0; + pacman.dy = PACMAN_SPEED; + } + } + + e.preventDefault(); +} + +function handleTouchEnd() { + touchStartX = 0; + touchStartY = 0; +} + +// Add touch event listeners +canvas.addEventListener('touchstart', handleTouchStart, { passive: false }); +canvas.addEventListener('touchmove', handleTouchMove, { passive: false }); +canvas.addEventListener('touchend', handleTouchEnd, { passive: false }); + +// Add mobile-specific styles +const style = document.createElement('style'); +style.textContent = ` + #pacmanCanvas { + touch-action: none; /* Prevent default touch behaviors */ + -webkit-touch-callout: none; + -webkit-user-select: none; + user-select: none; + } +`; +document.head.appendChild(style); + function moveChar(ch) { const nx = ch.x + ch.dx; const ny = ch.y + ch.dy;