Untitled

Anonymous
plain_text
02/11/2026 1:20 PM
3.3 KB
11
Indexable
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mini Football Game</title>
<style>
  body { margin: 0; overflow: hidden; background: #0a5c2f; }
  canvas { display: block; margin: auto; background: #1e8c3a; }
</style>
</head>
<body>
<canvas id="game" width="800" height="500"></canvas>

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

let player = { x: 100, y: 250, size: 20, speed: 4 };
let ball = { x: 150, y: 250, size: 10, dx: 0, dy: 0 };
let goal = { x: 750, y: 200, width: 40, height: 100 };
let score = 0;

let keys = {};

document.addEventListener("keydown", e => keys[e.key] = true);
document.addEventListener("keyup", e => keys[e.key] = false);

function update() {
  // Di chuyển cầu thủ
  if (keys["ArrowUp"]) player.y -= player.speed;
  if (keys["ArrowDown"]) player.y += player.speed;
  if (keys["ArrowLeft"]) player.x -= player.speed;
  if (keys["ArrowRight"]) player.x += player.speed;

  // Sút bóng (phím Space)
  if (keys[" "]) {
    ball.dx = 6;
  }

  // Bóng di chuyển
  ball.x += ball.dx;
  ball.y += ball.dy;

  // Ma sát
  ball.dx *= 0.98;
  ball.dy *= 0.98;

  // Va chạm cầu thủ với bóng
  let dist = Math.hypot(player.x - ball.x, player.y - ball.y);
  if (dist < player.size + ball.size) {
    ball.dx = (ball.x - player.x) * 0.3;
    ball.dy = (ball.y - player.y) * 0.3;
  }

  // Ghi bàn
  if (
    ball.x > goal.x &&
    ball.y > goal.y &&
    ball.y < goal.y + goal.height
  ) {
    score++;
    resetBall();
  }

  // Giữ trong sân
  ball.x = Math.max(0, Math.min(canvas.width, ball.x));
  ball.y = Math.max(0, Math.min(canvas.height, ball.y));
}

function resetBall() {
  ball.x = 150;
  ball.y = 250;
  ball.dx = 0;
  ball.dy = 0;
}

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

  // Vẽ cầu môn
  ctx.fillStyle = "white";
  ctx.fillRect(goal.x, goal.y, goal.width, goal.height);

  // Vẽ cầu thủ
  ctx.fillStyle = "blue";
  ctx.beginPath();
  ctx.arc(player.x, player.y, player.size, 0, Math.PI * 2);
  ctx.fill();

  // Vẽ bóng
  ctx.fillStyle = "white";
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.size, 0, Math.PI * 2);
  ctx.fill();

  // Điểm số
  ctx.fillStyle = "white";
  ctx.font = "24px Arial";
  ctx.fillText("Score: " + score, 20, 30);
}

function gameLoop() {
  update();
  draw();
  requestAnimationFrame(gameLoop);
}

gameLoop();
</script>
</body>
</html>
Editor is loading...
Leave a Comment