<!DOCTYPE html>
<html lang="hr">
<head>
<meta charset="UTF-8">
<title>Auto igra</title>
<style>
  body {
    margin: 0;
    overflow: hidden;
    background: #87CEEB;
  }

  #game {
    width: 300px;
    height: 500px;
    background: #555;
    margin: auto;
    position: relative;
    border: 4px solid black;
  }

  #car {
    width: 50px;
    height: 80px;
    background: red;
    position: absolute;
    bottom: 10px;
    left: 125px;
    border-radius: 10px;
  }

  .obstacle {
    width: 50px;
    height: 80px;
    background: black;
    position: absolute;
    top: 0;
    border-radius: 10px;
  }
</style>
</head>

<body>

<h2 style="text-align:center;">🚗 Izbjegni prepreke!</h2>

<div id="game">
  <div id="car"></div>
</div>

<script>
let car = document.getElementById("car");
let game = document.getElementById("game");

let carLeft = 125;

// Pomicanje auta (strelice)
document.addEventListener("keydown", function(e) {
  if (e.key === "ArrowLeft" && carLeft > 0) {
    carLeft -= 25;
  }
  if (e.key === "ArrowRight" && carLeft < 250) {
    carLeft += 25;
  }
  car.style.left = carLeft + "px";
});

// Kreiranje prepreka
function createObstacle() {
  let obstacle = document.createElement("div");
  obstacle.classList.add("obstacle");
  obstacle.style.left = Math.floor(Math.random() * 6) * 50 + "px";
  game.appendChild(obstacle);

  let top = 0;

  let move = setInterval(() => {
    top += 5;
    obstacle.style.top = top + "px";

    // Sudar
    let carRect = car.getBoundingClientRect();
    let obsRect = obstacle.getBoundingClientRect();

    if (
      carRect.left < obsRect.right &&
      carRect.right > obsRect.left &&
      carRect.top < obsRect.bottom &&
      carRect.bottom > obsRect.top
    ) {
      alert("💥 Sudar! Igra gotova!");
      location.reload();
    }

    if (top > 500) {
      obstacle.remove();
      clearInterval(move);
    }
  }, 50);
}

// Pokretanje prepreka
setInterval(createObstacle, 1500);
</script>

</body>
</html>