top of page

Another example of how to code a game using javascript

​

Object of the game:

  • A player (blue square) moves left/right using the arrow keys.

  • Red blocks fall from the top.

  • If you get hit, it's game over.

Code (HTML + CSS + JavaScript)

Save this as dodge-game.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Dodge the Blocks</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      background: #111;
    }
    canvas {
      display: block;
      margin: auto;
      background: #222;
    }
  </style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>

<script>
  const canvas = document.getElementById("gameCanvas");
  const ctx = canvas.getContext("2d");

  const player = {
    x: 175,
    y: 550,
    width: 50,
    height: 50,
    color: "blue",
    speed: 5
  };

  const blocks = [];
  let gameOver = false;

  // Create falling blocks
  function spawnBlock() {
    const size = 40;
    const x = Math.random() * (canvas.width - size);
    const speed = 2 + Math.random() * 3;
    blocks.push({ x, y: 0, width: size, height: size, color: "red", speed });
  }

  // Handle player movement
  const keys = {};
  document.addEventListener("keydown", e => keys[e.key] = true);
  document.addEventListener("keyup", e => keys[e.key] = false);

  function update() {
    if (keys["ArrowLeft"] && player.x > 0) player.x -= player.speed;
    if (keys["ArrowRight"] && player.x + player.width < canvas.width) player.x += player.speed;

    blocks.forEach(block => block.y += block.speed);

    // Check for collisions
    blocks.forEach(block => {
      if (
        player.x < block.x + block.width &&
        player.x + player.width > block.x &&
        player.y < block.y + block.height &&
        player.y + player.height > block.y
      ) {
        gameOver = true;
      }
    });

    // Remove off-screen blocks
    for (let i = blocks.length - 1; i >= 0; i--) {
      if (blocks[i].y > canvas.height) {
        blocks.splice(i, 1);
      }
    }
  }

  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw player
    ctx.fillStyle = player.color;
    ctx.fillRect(player.x, player.y, player.width, player.height);

    // Draw blocks
    blocks.forEach(block => {
      ctx.fillStyle = block.color;
      ctx.fillRect(block.x, block.y, block.width, block.height);
    });

    // Draw Game Over
    if (gameOver) {
      ctx.fillStyle = "white";
      ctx.font = "36px Arial";
      ctx.fillText("Game Over!", 100, 300);
    }
  }

  function gameLoop() {
    if (!gameOver) {
      update();
      draw();
      requestAnimationFrame(gameLoop);
    } else {
      draw(); // Draw final state
    }
  }

  // Start block spawning
  setInterval(() => {
    if (!gameOver) spawnBlock();
  }, 800);

  gameLoop();
</script>
</body>
</html>

 

Click the box game

Object of the game is to click the red box when it appears in order to gain points.

Save the code and call it game.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Catch the Box Game</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
      background: #f0f0f0;
      text-align: center;
    }
    #gameArea {
      position: relative;
      width: 800px;
      height: 600px;
      margin: 30px auto;
      background: #ffffff;
      border: 2px solid #000;
      overflow: hidden;
    }
    #box {
      position: absolute;
      width: 50px;
      height: 50px;
      background: red;
      cursor: pointer;
    }
    #score {
      font-size: 24px;
      margin-top: 10px;
    }
  </style>
</head>
<body>

<h1>🎯 Catch the Box!</h1>
<div id="score">Score: 0</div>
<div id="gameArea">
  <div id="box"></div>
</div>

<script>
  const box = document.getElementById('box');
  const gameArea = document.getElementById('gameArea');
  const scoreDisplay = document.getElementById('score');
  let score = 0;

  function moveBox() {
    const maxX = gameArea.clientWidth - box.offsetWidth;
    const maxY = gameArea.clientHeight - box.offsetHeight;
    const randomX = Math.floor(Math.random() * maxX);
    const randomY = Math.floor(Math.random() * maxY);
    box.style.left = randomX + 'px';
    box.style.top = randomY + 'px';
  }

  box.addEventListener('click', () => {
    score++;
    scoreDisplay.textContent = 'Score: ' + score;
    moveBox();
  });

  // Move the box every second
  setInterval(moveBox, 1000);

  // Start the game
  moveBox();
</script>

</body>
</html>

 

How to Run the Game

  1. Save the file​

  2. Open in browser:

    • Double-click the file, or right-click > "Open with" > your web browser.

  3. Play!

    • Click the red box as fast as you can to gain points!

bottom of page