Classic Bricks Breaker Game

 Hi there, I'm Karthik!

Presented below is a comprehensive article that delves into the development process of a classic Bricks Breaker game, skillfully crafted as part of my exploration in web development. 



LOGIC

In this Breakout game, the goal is to clear levels by bouncing a ball off a paddle to destroy bricks. The game canvas displays the action.

- Setup: The game starts with a canvas bordered in black. The ball, paddle, bricks, score, and level are defined as variables.

- Brick Layouts and Levels: Different levels are stored with specific brick layouts, forming patterns on the screen.

- Creating Bricks: The game initializes the brick array based on the current level's layout. This sets up the positions and states (intact or destroyed) of the bricks.

- Player Control: Players use arrow keys to move the paddle left or right. This controls the paddle's horizontal movement.

- Updating Game State: The game's core logic is managed by the `update()` function. It moves the paddle and ball and checks for various collisions.

- Paddle and Ball Movement: The paddle moves based on user input, while the ball moves autonomously. The ball bounces off walls and the paddle, and it also hits bricks.

- Collision Detection: The game checks if the ball collides with the walls, the paddle, or the bricks. If a collision occurs, appropriate actions are taken.

- Brick Destruction: When the ball hits a brick, the brick is marked as "destroyed." The player's score increases. If all bricks are destroyed, the player advances to the next level.

- Resetting: After each level, the ball and paddle positions are reset, and the next level's brick layout is  loaded.

- Drawing the Scene: The `draw()` function is responsible for rendering the game's elements. It draws the bricks, paddle, ball, score, and level on the canvas.

- Game Loop:The `gameLoop()` keeps the game running smoothly. It updates the game state using `update()` and renders the scene with `draw()` in a continuous loop, creating fluid animation.

- Game Start: The game begins by creating the initial brick layout and starting the `gameLoop()`.

- Keyboard Input Handling: Arrow key events are used to control the paddle's movement. Pressing an arrow key moves the paddle in the corresponding direction.

- Conclusion: This Breakout game offers an interactive experience where players control a paddle to bounce a ball and clear levels by destroying bricks.

CODE:

<!DOCTYPE html>
<html>
  <head>
    <title>Breakout Game</title>
    <style>
      #gameCanvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="gameCanvas" width="480" height="320"></canvas>
    <script>
      // Game variables
      const canvas = document.getElementById("gameCanvas");
      const ctx = canvas.getContext("2d");
      const ball = {
        x: canvas.width / 2,
        y: canvas.height - 30,
        radius: 10,
        dx: 2,
        dy: -2,
      };
      const paddle = {
        x: (canvas.width - 75) / 2,
        width: 75,
        height: 10,
        dx: 0,
      };
      const brickRowCount = 3;
      const brickColumnCount = 5;
      const brickWidth = 75;
      const brickHeight = 20;
      const brickPadding = 10;
      const brickOffsetTop = 30;
      const brickOffsetLeft = 30;
      let bricks = [];
      let score = 0;
      let level = 1;

      // Brick layout for each level
      const brickLayouts = [
        // Level 1
        [
          [1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1],
        ],
        // Level 2
        [
          [1, 0, 1, 0, 1],
          [1, 0, 1, 0, 1],
          [1, 0, 1, 0, 1],
        ],
        // Level 3
        [
          [1, 0, 0, 0, 1],
          [0, 1, 0, 1, 0],
          [1, 0, 1, 0, 1],
        ],
        // Level 4
        [
          [1, 0, 1, 0, 1],
          [0, 1, 1, 1, 0],
          [1, 0, 1, 0, 1],
        ],
        // Level 5
        [
          [1, 1, 0, 1, 1],
          [1, 0, 1, 0, 1],
          [1, 1, 0, 1, 1],
        ],
        // Level 6
        [
          [1, 1, 1, 1, 1],
          [1, 0, 0, 0, 1],
          [1, 1, 1, 1, 1],
        ],
      ];

      // Create bricks
      function createBricks() {
        bricks = [];
        for (let c = 0; c < brickColumnCount; c++) {
          bricks[c] = [];
          for (let r = 0; r < brickRowCount; r++) {
            bricks[c][r] = {
              x: 0,
              y: 0,
              status: brickLayouts[level - 1][r][c],
            };
          }
        }
      }

      // Handle keyboard input
      document.addEventListener("keydown", handleKeyPress);
      document.addEventListener("keyup", handleKeyRelease);

      // Update game state
      function update() {
        // Move the paddle
        paddle.x += paddle.dx;
        if (paddle.x < 0) {
          paddle.x = 0;
        }
        if (paddle.x > canvas.width - paddle.width) {
          paddle.x = canvas.width - paddle.width;
        }

        // Move the ball
        ball.x += ball.dx;
        ball.y += ball.dy;

        // Check collision with walls
        if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
          ball.dx = -ball.dx;
        }
        if (ball.y - ball.radius < 0) {
          ball.dy = -ball.dy;
        }
        if (ball.y + ball.radius > canvas.height) {
          // Ball hits the bottom, game over
          alert("Game Over!");
          document.location.reload();
        }

        // Check collision with paddle
        if (
          ball.y + ball.radius > canvas.height - paddle.height &&
          ball.x > paddle.x &&
          ball.x < paddle.x + paddle.width
        ) {
          ball.dy = -ball.dy;
        }

        // Check collision with bricks
        for (let c = 0; c < brickColumnCount; c++) {
          for (let r = 0; r < brickRowCount; r++) {
            const brick = bricks[c][r];
            if (brick.status === 1) {
              if (
                ball.x > brick.x &&
                ball.x < brick.x + brickWidth &&
                ball.y > brick.y &&
                ball.y < brick.y + brickHeight
              ) {
                ball.dy = -ball.dy;
                brick.status = 0;
                score++;
                if (score === brickRowCount * brickColumnCount) {
                  // All bricks destroyed, level complete
                  if (level === 6) {
                    alert("Congratulations! You completed all levels!");
                    document.location.reload();
                  } else {
                    level++;
                    score = 0;
                    createBricks();
                    resetBallAndPaddle();
                  }
                }
              }
            }
          }
        }
      }

      // Reset ball and paddle position
      function resetBallAndPaddle() {
        ball.x = canvas.width / 2;
        ball.y = canvas.height - 30;
        paddle.x = (canvas.width - paddle.width) / 2;
      }

      // Draw game objects
      function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Draw bricks
        for (let c = 0; c < brickColumnCount; c++) {
          for (let r = 0; r < brickRowCount; r++) {
            if (bricks[c][r].status === 1) {
              const brickX = c * (brickWidth + brickPadding) + brickOffsetLeft;
              const brickY = r * (brickHeight + brickPadding) + brickOffsetTop;
              bricks[c][r].x = brickX;
              bricks[c][r].y = brickY;
              ctx.fillStyle = "blue";
              ctx.fillRect(brickX, brickY, brickWidth, brickHeight);
            }
          }
        }

        // Draw paddle
        ctx.fillStyle = "red";
        ctx.fillRect(
          paddle.x,
          canvas.height - paddle.height,
          paddle.width,
          paddle.height
        );

        // Draw ball
        ctx.beginPath();
        ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
        ctx.fillStyle = "green";
        ctx.fill();
        ctx.closePath();

        // Draw score and level
        ctx.font = "16px Arial";
        ctx.fillStyle = "black";
        ctx.fillText("Score: " + score, 8, 20);
        ctx.fillText("Level: " + level, canvas.width - 80, 20);
      }

      // Game loop
      function gameLoop() {
        update();
        draw();
        requestAnimationFrame(gameLoop);
      }

      // Handle key presses
      function handleKeyPress(event) {
        if (event.key === "ArrowLeft") {
          paddle.dx = -7;
        }
        if (event.key === "ArrowRight") {
          paddle.dx = 7;
        }
      }

      // Handle key releases
      function handleKeyRelease(event) {
        if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
          paddle.dx = 0;
        }
      }

      // Start the game
      createBricks();
      gameLoop();
    </script>
  </body>
</html>



The above code is written using HTML, CSS & Java Script by implementing core game mechanics, user controls, and score tracking.



Comments

Popular posts from this blog

Smart Irrigation System Using IoT

Classic Snake Game