Skip to content

Commit

Permalink
added mobile support to snake game
Browse files Browse the repository at this point in the history
  • Loading branch information
egiday committed May 5, 2023
1 parent 1b7a0dd commit 82c4725
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Money Tycoon Game/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

body {
font-family: 'Montserrat', Arial, sans-serif;
background-color: #ffffff;
background-color: #c3c3c3;
color: #000000;
display: grid;
grid-template-rows: 1fr auto;
Expand Down
58 changes: 57 additions & 1 deletion Snake Game/Script.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ window.addEventListener("DOMContentLoaded", function () {
let blockSize = 20;
let currentGameSpeed = 100;
const powerUps = [];

let touchStartX = null;
let touchStartY = null;
let gamePaused = false;
let score = 0;
let highScore = 0;
Expand All @@ -17,6 +18,7 @@ window.addEventListener("DOMContentLoaded", function () {
let food = [];
let dx = blockSize;
let dy = 0;


const newGameButton = document.getElementById("newGameButton");
newGameButton.addEventListener("click", newGame);
Expand Down Expand Up @@ -69,6 +71,60 @@ window.addEventListener("DOMContentLoaded", function () {
draw();
}, currentGameSpeed);
});


function handleTouchStart(event) {
if (event.touches.length === 1) {
// Only deal with one finger touch
touchStartX = event.touches[0].clientX;
touchStartY = event.touches[0].clientY;
}
}

function handleTouchEnd(event) {
if (!touchStartX || !touchStartY) {
return;
}

const touchEndX = event.changedTouches[0].clientX;
const touchEndY = event.changedTouches[0].clientY;

const deltaX = touchEndX - touchStartX;
const deltaY = touchEndY - touchStartY;

if (Math.abs(deltaX) > Math.abs(deltaY)) {
// Horizontal swipe
if (deltaX > 0 && dx !== -blockSize) {
// Swipe right
dx = blockSize;
dy = 0;
} else if (deltaX < 0 && dx !== blockSize) {
// Swipe left
dx = -blockSize;
dy = 0;
}
} else {
// Vertical swipe
if (deltaY > 0 && dy !== -blockSize) {
// Swipe down
dx = 0;
dy = blockSize;
} else if (deltaY < 0 && dy !== blockSize) {
// Swipe up
dx = 0;
dy = -blockSize;
}
}

// Reset touch start coordinates
touchStartX = null;
touchStartY = null;
}

canvas.addEventListener("touchstart", handleTouchStart, { passive: true });
canvas.addEventListener("touchend", handleTouchEnd, { passive: true });



function togglePause() {
gamePaused = !gamePaused;
Expand Down

0 comments on commit 82c4725

Please sign in to comment.