Spaces:
Running
Running
| 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 | |
| ); | |
| } |