🎮ArcadeLab

Mobile Dodge Game

by QuantumDolphin87
137 lines2.4 KB
▶ Play
<!DOCTYPE html>
<html>
<head>
  <title>Mobile Dodge Game</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      background: black;
      color: white;
      font-family: Arial;
      text-align: center;
    }

    #player {
      width: 50px;
      height: 50px;
      background: cyan;
      position: absolute;
      bottom: 20px;
      left: 175px;
      border-radius: 10px;
    }

    .enemy {
      width: 40px;
      height: 40px;
      background: red;
      position: absolute;
      top: 0;
      border-radius: 8px;
    }

    #score {
      position: fixed;
      top: 10px;
      left: 10px;
      font-size: 20px;
    }

    #controls {
      position: fixed;
      bottom: 0;
      width: 100%;
      height: 120px;
      display: flex;
    }

    .btn {
      flex: 1;
      opacity: 0.1;
    }
  </style>
</head>
<body>

<div id="score">Score: 0</div>
<div id="player"></div>

<!-- mobile controls -->
<div id="controls">
  <div class="btn" id="left"></div>
  <div class="btn" id="right"></div>
</div>

<script>
let player = document.getElementById("player");
let scoreText = document.getElementById("score");

let x = 175;
let score = 0;

function move() {
  if (x < 0) x = 0;
  if (x > window.innerWidth - 50) x = window.innerWidth - 50;
  player.style.left = x + "px";
}

// keyboard controls
document.addEventListener("keydown", (e) => {
  if (e.key === "ArrowLeft") x -= 20;
  if (e.key === "ArrowRight") x += 20;
  move();
});

// mobile touch controls
document.getElementById("left").addEventListener("touchstart", () => {
  x -= 30;
  move();
});

document.getElementById("right").addEventListener("touchstart", () => {
  x += 30;
  move();
});

function createEnemy() {
  let enemy = document.createElement("div");
  enemy.classList.add("enemy");

  let ex = Math.random() * (window.innerWidth - 40);
  enemy.style.left = ex + "px";

  document.body.appendChild(enemy);

  let y = 0;

  let fall = setInterval(() => {
    y += 6;
    enemy.style.top = y + "px";

    let px = x;

    // collision
    if (
      y > window.innerHeight - 100 &&
      ex < px + 50 &&
      ex + 40 > px
    ) {
      alert("Game Over! Score: " + score);
      location.reload();
    }

    if (y > window.innerHeight) {
      enemy.remove();
      clearInterval(fall);
      score++;
      scoreText.innerText = "Score: " + score;
    }
  }, 30);
}

setInterval(createEnemy, 900);
</script>

</body>
</html>

Game Source: Mobile Dodge Game

Creator: QuantumDolphin87

Libraries: none

Complexity: moderate (137 lines, 2.4 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: mobile-dodge-game-quantumdolphin87" to link back to the original. Then publish at arcadelab.ai/publish.