Saturday, 3 June 2023

CodeQuest: The JavaScript Journey || A JavaScript Game

 


                           Create a Simple Game using javascript
 <!DOCTYPE html>
<html>
  <head>
    <title>Simple JavaScript Game</title>
    <style>
      #game-container {
        width: 400px;
        height: 400px;
        border: 1px solid black;
        position: relative;
      }
      #player {
        width: 50px;
        height: 50px;
        background-color: blue;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="game-container">
      <div id="player"></div>
    </div>
    <script >
            
// Get the player and game container elements
const player = document.getElementById("player");
const gameContainer = document.getElementById("game-container");

// Set the initial position of the player
let playerX = 0;
let playerY = 0;

// Function to handle keyboard arrow key events
function handleArrowKey(event) {
  const key = event.key;
  if (key === "ArrowUp" && playerY > 0) {
    playerY -= 10;
  } else if (key === "ArrowDown" && playerY < gameContainer.offsetHeight -
        player.offsetHeight) {
    playerY += 10;
  } else if (key === "ArrowLeft" && playerX > 0) {
    playerX -= 10;
  } else if (key === "ArrowRight" && playerX < gameContainer.offsetWidth -
        player.offsetWidth) {
    playerX += 10;
  }

  // Update the player's position
  player.style.left = playerX + "px";
  player.style.top = playerY + "px";
}

// Add event listener for arrow key events
document.addEventListener("keydown", handleArrowKey);

</script>
  </body>
</html>

No comments:

Post a Comment

This is me