Action Game In JavaScript

This action game is a simple browser-based 2D game built using HTML, CSS, and JavaScript where the player controls a green square at the bottom of the screen using the left and right arrow keys to avoid falling red enemy blocks. The game area is created with HTML and styled using CSS, while JavaScript handles the game logic, including player movement, enemy creation, animation, collision detection, and scoring. Enemies are continuously generated at random horizontal positions and move downward at a fixed speed, and if an enemy collides with the player, the game stops and a game-over screen is displayed. The player’s score increases each time an enemy successfully passes off the screen without hitting the player, encouraging quick reactions and precise movement to survive as long as possible.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Character encoding -->
  <meta charset="UTF-8" />

  <!-- Page title -->
  <title>Action Game - Avoid Enemies</title>

  <!-- Responsive layout for mobile -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <!-- Game styling -->
  <style>
    /* Remove default margin and set background */
    body {
      margin: 0;
      background: #111;
      color: #fff;
      font-family: Arial, sans-serif;
      text-align: center;
    }

    /* Heading spacing */
    h2 {
      margin: 10px 0;
    }

    /* Main game container */
    #game {
      position: relative;          /* Needed for absolute children */
      width: 400px;
      height: 500px;
      background: #222;
      margin: 0 auto;              /* Center horizontally */
      overflow: hidden;            /* Hide enemies outside area */
      border: 3px solid #fff;
    }

    /* Player block */
    #player {
      position: absolute;
      width: 40px;
      height: 40px;
      background: lime;
      bottom: 10px;                /* Place near bottom */
      left: 180px;                 /* Start in center */
      border-radius: 6px;
    }

    /* Enemy blocks */
    .enemy {
      position: absolute;
      width: 40px;
      height: 40px;
      background: red;
      top: -40px;                  /* Start above screen */
      border-radius: 6px;
    }

    /* Game over overlay */
    #gameOver {
      display: none;               /* Hidden until game ends */
      position: absolute;
      inset: 0;                    /* Cover entire game area */
      background: rgba(0,0,0,0.8);
      color: white;
      font-size: 24px;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }

    /* Restart button */
    button {
      padding: 10px 20px;
      font-size: 16px;
      margin-top: 10px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <!-- Game title -->
  <h2>🔥 Action Game: Avoid the Enemies</h2>

  <!-- Controls info -->
  <p>Use ◀ ▶ arrow keys to move</p>

  <!-- Score display -->
  <h3>Score: <span id="score">0</span></h3>

  <!-- Game area -->
  <div id="game">

    <!-- Player element -->
    <div id="player"></div>

    <!-- Game over screen -->
    <div id="gameOver">
      <div>💀 Game Over</div>
      <button onclick="location.reload()">Restart</button>
    </div>
  </div>

  <!-- JavaScript game logic -->
  <script>
    // Get references to DOM elements
    const game = document.getElementById("game");
    const player = document.getElementById("player");
    const scoreDisplay = document.getElementById("score");
    const gameOverScreen = document.getElementById("gameOver");

    // Game variables
    let score = 0;                 // Player score
    let playerX = 180;             // Player horizontal position
    let gameRunning = true;        // Game state

    // Listen for keyboard input
    document.addEventListener("keydown", (e) => {
      if (!gameRunning) return;    // Stop movement if game over

      // Move left
      if (e.key === "ArrowLeft" && playerX > 0) {
        playerX -= 20;
      }

      // Move right
      if (e.key === "ArrowRight" && playerX < 360) {
        playerX += 20;
      }

      // Apply movement to player
      player.style.left = playerX + "px";
    });

    // Function to create a falling enemy
    function createEnemy() {
      if (!gameRunning) return;

      // Create enemy element
      const enemy = document.createElement("div");
      enemy.classList.add("enemy");

      // Random horizontal position
      enemy.style.left = Math.random() * 360 + "px";

      // Add enemy to game area
      game.appendChild(enemy);

      let enemyY = -40;            // Starting vertical position

      // Move enemy downward repeatedly
      const fallInterval = setInterval(() => {
        if (!gameRunning) {
          clearInterval(fallInterval);
          enemy.remove();
          return;
        }

        // Move enemy down
        enemyY += 5;
        enemy.style.top = enemyY + "px";

        // Check collision with player
        if (
          enemyY > 440 &&
          Math.abs(playerX - enemy.offsetLeft) < 40
        ) {
          gameOver();
          clearInterval(fallInterval);
        }

        // Remove enemy if it leaves screen
        if (enemyY > 500) {
          enemy.remove();
          clearInterval(fallInterval);
          score++;                 // Increase score
          scoreDisplay.textContent = score;
        }
      }, 30); // Speed of enemy fall
    }

    // Game over function
    function gameOver() {
      gameRunning = false;
      gameOverScreen.style.display = "flex";
    }

    // Create enemies repeatedly
    setInterval(createEnemy, 800);
  </script>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *