I need urgent help with my code

Hello! I need help with my code that I am writing in HTML.

I am trying to make it so the player can move up, down, right, and left but it it is not working. I have tried writing the code in html, and javascript.

Here is the code snippet (HTML):

<!DOCTYPE html>
<html>
<head>
  <title>2D Game</title>
  <style>
    #game-container {
      width: 400px;
      height: 400px;
      background-color: #f1f1f1;
      position: relative;
    }

    .player {
      width: 50px;
      height: 50px;
      background-color: blue;
      position: absolute;
      top: 0;
      left: 0;
    }

    .obstacle {
      width: 50px;
      height: 50px;
      background-color: green;
      position: absolute;
    }

    .enemy {
      width: 50px;
      height: 50px;
      background-color: red;
      position: absolute;
      top: 200px;
      left: 300px;
    }

    .eaten {
      background-color: teal !important;
    }

    .game-over {
      background-color: rgba(0, 0, 0, 0.5);
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      z-index: 999;
      visibility: hidden;
    }

    .game-over h1 {
      color: white;
      font-size: 24px;
      margin-bottom: 20px;
    }

    .retry-button {
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
    }
  </style>
</head>
<body>
  <div id="game-container">
    <div class="player"></div>
    <div class="obstacle"></div>
    <div class="obstacle"></div>
    <div class="enemy"></div>
  </div>

  <div class="game-over">
    <h1>Game Over</h1>
    <button class="retry-button">Retry</button>
  </div>

  <script>
    const player = document.querySelector('.player');
    const obstacles = document.querySelectorAll('.obstacle');
    const enemy = document.querySelector('.enemy');
    const gameOverScreen = document.querySelector('.game-over');
    const retryButton = document.querySelector('.retry-button');
    let playerPositionX = 0;

    function movePlayer() {
      player.style.left = playerPositionX + 'px';
    }

    function handleKeyDown(event) {
      if (event.key === 'ArrowRight') {
        playerPositionX += 10;
        movePlayer();
      } else if (event.key === 'ArrowLeft') {
        playerPositionX -= 10;
        movePlayer();
      }
      checkCollision();
    }

    function checkCollision() {
      obstacles.forEach((obstacle) => {
        if (collision(player, obstacle)) {
          obstacle.classList.add('eaten');
        }
      });

      if (collision(player, enemy)) {
        gameOver();
      }
    }

    function collision(player, obstacle) {
      const playerRect = player.getBoundingClientRect();
      const obstacleRect = obstacle.getBoundingClientRect();
      
      return (
        playerRect.left < obstacleRect.right &&
        playerRect.right > obstacleRect.left &&
        playerRect.top < obstacleRect.bottom &&
        playerRect.bottom > obstacleRect.top
      );
    }

    function gameOver() {
      gameOverScreen.style.visibility = 'visible';
    }

    function retryGame() {
      gameOverScreen.style.visibility = 'hidden';
      playerPositionX = 0;
      movePlayer();
    }

    document.addEventListener('keydown', handleKeyDown);
    retryButton.addEventListener('click', retryGame);
  </script>
</body>
</html>

I have also tried using JavaScript but it doesn’t help. Here is a snippet:

document.addEventListener('keydown', function(event) {
  if (event.key === 'ArrowUp') {
    // move up
  } else if (event.key === 'ArrowDown') {
    // move down
  } else if (event.key === 'ArrowLeft') {
    // move left
  } else if (event.key === 'ArrowRight') {
    // move right
  }
});

None of these worked and just resulted in the player moving only right and left. Here is a video:


Thank you for reading and hopefully you can help me resolve this issue!

I most likely will reply tomorrow, but please be urgent.

Inside of index.html in the script tag you have a function called handleKeyDownEvent and it doesn’t look like this funciton captures and up and down movement, only left and right. Your script.js file does not do anything as it only has empty comments right now.

image

You need to add checks for up and down arrows in here and make it move the player.

1 Like

Do I fix index.html or script.js? At first I tried fixing script.js but still didn’t work.

Well you didn’t connect script.js to your HTML so no changing script.js won’t work. Change it in the script tag in your HTML

It still didn’t work. I replaced checkCollision(); with checkUp(); like how @SharkCoding said.

No, you need to go inside of handleKeyDownEvent and add this after the if else if statement.

if (event.key === 'ArrowUp') {
  playerPositionY += 10;
  movePlayer();
} else if (event.key === 'ArrowDown') {
  playerPositionY -= 10;
  movePlayer();
}

and then you need to change the movePlayer function to also update the y value

function movePlayer() {
  player.style.left = playerPositionX + "px";
  player.style.top = playerPositionY + "px";
}

and you also need to define playerPositionY at the top

let playerPositionY = 0;

SIDE NOTE: I would also recommend creating a class for each block instead of using individual variables.

1 Like

Why not just

switch (event.key) {
  case 'ArrowRight':
    playerPositionX += 10;
    break;
  case 'ArrowLeft':
    playerPositionX -= 10;
    break;
  case 'ArrowUp':
    playerPositionY += 10;
    break;
  case 'ArrowDown' {
    playerPositionY -= 10;
    break;
}
2 Likes

At first, the code gave me an unexpected error token for both of your code snippets. I used an edited version of @QwertyQwerty88

switch (event.key) {
  case 'ArrowRight':
    playerPositionX += 10;
    break;
  case 'ArrowLeft':
    playerPositionX -= 10;
    break;
  case 'ArrowUp':
    playerPositionY += 10;
    break;
  case 'ArrowDown': // Add colon here
    playerPositionY -= 10;
    break;
}
function movePlayer() {
  player.style.left = playerPositionX + "px";
  player.style.top = playerPositionY + "px";
}
let playerPositionY = 0;

This time the error said: TypeError: Cannot read properties of undefined (reading ‘key’)

Also the arrow keys in the game do not work anymore.

Is it still in the handleKeyDown function?