Skip to content

Commit

Permalink
finish handleKeyPress event listener function
Browse files Browse the repository at this point in the history
  • Loading branch information
marskimiko committed Jan 23, 2024
1 parent 253a4a5 commit 2a03b44
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions script.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function setPosition(element, position) {
}

// Testing draw function
draw();
// draw();

// Draw food function
function drawFood() {
Expand Down Expand Up @@ -105,4 +105,36 @@ function startGame() {
gameStarted = true; // Keep track of a running game
instructionText.style.display = 'none';
logo.style.display = 'none';
}
gameInterval = setInterval(() => {
move();
// checkCollision();
draw();
}, gameSpeedDelay);
}

// keypress event listener
function handleKeyPress(event) {
if (
(!gameStarted && event.code === 'Space') ||
(!gameStarted && event.key === ' ')
) {
startGame();
} else {
switch (event.key) {
case 'ArrowUp':
direction = 'up';
break;
case 'ArrowDown':
direction = 'down';
break;
case 'ArrowLeft':
direction = 'left';
break;
case 'ArrowRight':
direction = 'right';
break;
}
}
}

document.addEventListener('keydown', handleKeyPress);

0 comments on commit 2a03b44

Please sign in to comment.