Skip to content

Commit

Permalink
13.12.2024 | Anpassung High Score Fenster
Browse files Browse the repository at this point in the history
  • Loading branch information
ubodigat authored Dec 13, 2024
1 parent 3674741 commit 437c94e
Showing 1 changed file with 47 additions and 29 deletions.
76 changes: 47 additions & 29 deletions games/snake/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,24 @@ let direction = 'LEFT';
let foodCollected = false;
let score = 0;
let highScores = JSON.parse(localStorage.getItem('highScores')) || [];
let gameInterval;
let isPaused = false;

placeFood();

setInterval(gameLoop, 300);
startGame();
document.addEventListener('keydown', keyDown);

draw();

function startGame() {
gameInterval = setInterval(gameLoop, 300);
}

function pauseGame() {
clearInterval(gameInterval);
}

function draw() {
ctx.fillStyle = '#066e46';
ctx.fillRect(0, 0, canvas.width, canvas.height);
Expand Down Expand Up @@ -76,34 +86,36 @@ function shiftSnake() {
}

function gameLoop() {
testGameOver();
if (foodCollected) {
snake = [{ x: snake[0].x, y: snake[0].y }, ...snake];
foodCollected = false;
score++;
}

shiftSnake();

if (direction == 'LEFT') {
snake[0].x--;
}

if (direction == 'RIGHT') {
snake[0].x++;
}

if (direction == 'UP') {
snake[0].y--;
}

if (direction == 'DOWN') {
snake[0].y++;
}

if (snake[0].x == food.x && snake[0].y == food.y) {
foodCollected = true;
placeFood();
if (!isPaused) {
testGameOver();
if (foodCollected) {
snake = [{ x: snake[0].x, y: snake[0].y }, ...snake];
foodCollected = false;
score++;
}

shiftSnake();

if (direction == 'LEFT') {
snake[0].x--;
}

if (direction == 'RIGHT') {
snake[0].x++;
}

if (direction == 'UP') {
snake[0].y--;
}

if (direction == 'DOWN') {
snake[0].y++;
}

if (snake[0].x == food.x && snake[0].y == food.y) {
foodCollected = true;
placeFood();
}
}
}

Expand All @@ -123,6 +135,8 @@ function keyDown(e) {
}

document.getElementById('highScoresLink').onclick = function() {
isPaused = true;
pauseGame();
let modal = document.getElementById('highScoresModal');
let allHighScores = document.getElementById('allHighScores');
allHighScores.innerHTML = '';
Expand All @@ -135,12 +149,16 @@ document.getElementById('highScoresLink').onclick = function() {
}

document.getElementsByClassName('close')[0].onclick = function() {
isPaused = false;
startGame();
document.getElementById('highScoresModal').style.display = 'none';
}

window.onclick = function(event) {
let modal = document.getElementById('highScoresModal');
if (event.target == modal) {
isPaused = false;
startGame();
modal.style.display = 'none';
}
}

0 comments on commit 437c94e

Please sign in to comment.