Skip to content

Commit 0dd36d8

Browse files
committed
Add mobile support for touch
1 parent 59651a5 commit 0dd36d8

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

Day #12 - 2048 Game/script.js

+43-1
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,53 @@ document.addEventListener('keydown', (e) => {
127127
handleMove(e.keyCode);
128128
});
129129

130+
// Add touch event listeners for mobile support
131+
let touchStartX = 0;
132+
let touchStartY = 0;
133+
let touchEndX = 0;
134+
let touchEndY = 0;
135+
136+
function handleTouchStart(e) {
137+
touchStartX = e.touches[0].clientX;
138+
touchStartY = e.touches[0].clientY;
139+
}
140+
141+
function handleTouchMove(e) {
142+
touchEndX = e.touches[0].clientX;
143+
touchEndY = e.touches[0].clientY;
144+
}
145+
146+
function handleTouchEnd() {
147+
const dx = touchEndX - touchStartX;
148+
const dy = touchEndY - touchStartY;
149+
const absDx = Math.abs(dx);
150+
const absDy = Math.abs(dy);
151+
152+
if (Math.max(absDx, absDy) > 20) { // Swipe threshold
153+
if (absDx > absDy) {
154+
if (dx > 0) {
155+
handleMove(39); // Swipe right
156+
} else {
157+
handleMove(37); // Swipe left
158+
}
159+
} else {
160+
if (dy > 0) {
161+
handleMove(40); // Swipe down
162+
} else {
163+
handleMove(38); // Swipe up
164+
}
165+
}
166+
}
167+
}
168+
169+
document.addEventListener('touchstart', handleTouchStart, false);
170+
document.addEventListener('touchmove', handleTouchMove, false);
171+
document.addEventListener('touchend', handleTouchEnd, false);
172+
130173
function initGame() {
131174
generateRandom();
132175
generateRandom();
133176
createGrid();
134177
}
135178

136-
137179
initGame();

Day #12 - 2048 Game/style.css

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,4 @@ body {
6060
margin-top: 20px;
6161
font-size: 24px;
6262
font-weight: bold;
63-
}
63+
}

0 commit comments

Comments
 (0)