🎮ArcadeLab

Air Hockey Game

by SonicBear35
151 lines2.4 KB
▶ Play
<!DOCTYPE html>
<html>
<head>
<title>Air Hockey Game</title>
<style>
body {
  margin: 0;
  overflow: hidden;
  background: #0b5ed7;
}

canvas {
  display: block;
  margin: auto;
  background: #1e90ff;
}

#score {
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  font-size: 20px;
  font-family: Arial;
}
</style>
</head>
<body>

<div id="score">You: 0 | AI: 0</div>
<canvas id="game"></canvas>

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let you = 0;
let aiScore = 0;

// 🟡 puck
let puck = {
  x: canvas.width/2,
  y: canvas.height/2,
  vx: 5,
  vy: 4,
  r: 12
};

// 🧍 player paddle
let player = {
  x: canvas.width/2,
  y: canvas.height - 60,
  w: 120,
  h: 15
};

// 🤖 AI paddle
let ai = {
  x: canvas.width/2,
  y: 40,
  w: 120,
  h: 15
};

// mouse control
document.addEventListener("mousemove", (e) => {
  player.x = e.clientX;
});

function resetPuck(dir){
  puck.x = canvas.width/2;
  puck.y = canvas.height/2;
  puck.vx = 5 * (Math.random() > 0.5 ? 1 : -1);
  puck.vy = 4 * dir;
}

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

  // middle line
  ctx.fillStyle = "white";
  ctx.fillRect(0, canvas.height/2, canvas.width, 2);

  // puck
  ctx.fillStyle = "yellow";
  ctx.beginPath();
  ctx.arc(puck.x, puck.y, puck.r, 0, Math.PI*2);
  ctx.fill();

  // paddles
  ctx.fillStyle = "white";
  ctx.fillRect(player.x-60, player.y, player.w, player.h);

  ctx.fillStyle = "red";
  ctx.fillRect(ai.x-60, ai.y, ai.w, ai.h);

  // move puck
  puck.x += puck.vx;
  puck.y += puck.vy;

  // wall bounce
  if(puck.x < 0 || puck.x > canvas.width) puck.vx *= -1;

  // player hit
  if(
    puck.y + puck.r > player.y &&
    puck.x > player.x-60 &&
    puck.x < player.x+60
  ){
    puck.vy *= -1;
  }

  // AI follow (simple smart AI 🤖)
  ai.x += (puck.x - ai.x) * 0.07;

  // AI hit
  if(
    puck.y - puck.r < ai.y + ai.h &&
    puck.x > ai.x-60 &&
    puck.x < ai.x+60
  ){
    puck.vy *= -1;
  }

  // GOAL bottom (AI scores)
  if(puck.y > canvas.height){
    aiScore++;
    document.getElementById("score").innerText =
      "You: " + you + " | AI: " + aiScore;
    resetPuck(-1);
  }

  // GOAL top (you score)
  if(puck.y < 0){
    you++;
    document.getElementById("score").innerText =
      "You: " + you + " | AI: " + aiScore;
    resetPuck(1);
  }

  requestAnimationFrame(loop);
}

loop();
</script>

</body>
</html>

Game Source: Air Hockey Game

Creator: SonicBear35

Libraries: none

Complexity: moderate (151 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: air-hockey-game-sonicbear35" to link back to the original. Then publish at arcadelab.ai/publish.