File size: 1,950 Bytes
4cc8092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const squares = [
  { id: "yellow-square", dx: 2, dy: 2 },
  { id: "blue-square", dx: -2, dy: 2 },
  { id: "red-square", dx: 2, dy: -2 },
  { id: "green-square", dx: -2, dy: -2 },
];

const gameArea = document.getElementById("game-area");
const finishLine = document.getElementById("finish-line");
const playButton = document.getElementById("play-button");
const obstacles = document.querySelectorAll(".obstacle");
let interval;

playButton.addEventListener("click", startGame);

function startGame() {
  playButton.disabled = true;
  interval = setInterval(updateGame, 20);
}

function updateGame() {
  squares.forEach((square) => {
    const element = document.getElementById(square.id);
    const rect = element.getBoundingClientRect();
    const gameRect = gameArea.getBoundingClientRect();

    // Move square
    let newX = rect.x + square.dx;
    let newY = rect.y + square.dy;

    // Check for collision with walls
    if (newX <= gameRect.left || newX + rect.width >= gameRect.right) {
      square.dx *= -1;
    }
    if (newY <= gameRect.top || newY + rect.height >= gameRect.bottom) {
      square.dy *= -1;
    }

    // Check for collision with obstacles
    obstacles.forEach((obstacle) => {
      const obstacleRect = obstacle.getBoundingClientRect();
      if (isColliding(rect, obstacleRect)) {
        square.dx *= -1;
        square.dy *= -1;
      }
    });

    // Check for reaching finish line
    const finishRect = finishLine.getBoundingClientRect();
    if (isColliding(rect, finishRect)) {
      alert(`${square.id.replace("-square", "").toUpperCase()} WINS!`);
      clearInterval(interval);
    }

    // Apply new position
    element.style.left = `${newX - gameRect.left}px`;
    element.style.top = `${newY - gameRect.top}px`;
  });
}

function isColliding(rect1, rect2) {
  return !(
    rect1.right < rect2.left ||
    rect1.left > rect2.right ||
    rect1.bottom < rect2.top ||
    rect1.top > rect2.bottom
  );
}