비전공자 개발일기

Dino Game 본문

Javascript

Dino Game

HiroDaegu 2022. 9. 29. 00:59
728x90
SMALL

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DINO GAME</title>
    <link rel="stylesheet" href="style.css" />
    <script defer src="main.js"></script>
  </head>
  <body>
    <div class="game">
      <div id="dino"></div>
      <div id="cactus"></div>
    </div>
  </body>
</html>
* {
  padding: 0;
  margin: 0;
}
.game {
  width: 600px;
  height: 200px;
  border: 1px solid #000000;
  margin: auto;
}
#dino {
  width: 70px;
  height: 70px;
  background-image: url(t-rex.png);
  background-size: auto 70px;
  position: relative;
  top: 143px;
}
.jump {
  animation: jump 0.3s linear;
}
@keyframes jump {
  0% {
      top: 143px; /*distance from the top of the parent element*/
  }
  30% {
      top: 115px;
  }
  50% {
      top: 70px;
  }
  80% {
      top: 115px;
  }
  100% {
      top: 143px;
  }
}
#cactus {
  width: 20px;
  height: 40px;
  position: relative;
  top: 91px;
  left: 580px; /*width of frame - width of cactus*/
  background-image: url(cactus.png);
  background-size: 20px 40px;
  animation: cactus-block 1.2s infinite linear;
}
@keyframes cactus-block {
  0% {
      left: 600px;
  }
  100% {
      left: -20px;
  }
}
const dino = document.getElementById("dino");
const cactus = document.getElementById("cactus");
function jump() {
    if (dispatchEvent.classList != "jump") {
        //first it checks if the dino is mid-jump. If not, it makes it jump.
        dino.classList.add("jump");
        setTimeout(function () {
            dino.classList.remove("jump");
            //removes the jump class from the dino once it has jumped so that it can jump again
        }, 300);
    }
}
let checkAlive = setInterval(function () {
    let dinoTop = parseInt(
        window.getComputedStyle(dino).getPropertyValue("top")
    );
    let cactusLeft = parseInt(
        window.getComputedStyle(cactus).getPropertyValue("left")
    );
    //check for collision
    if (cactusLeft > 0 && cactusLeft < 70 && dinoTop >= 143) {
        dino.style.animationPlayState = "paused";
        cactus.style.animationPlayState = "paused";
        alert("Whoops! Game Over :(");
        window.location.reload();
    }
}, 10);
document.addEventListener("keydown", function (event) {
    jump();
});
728x90
LIST

'Javascript' 카테고리의 다른 글

3D Image Carousel  (0) 2022.10.05
Toast MSG  (0) 2022.10.03
Stopwatch  (0) 2022.09.27
Image Color Picker  (0) 2022.09.24
Vertical Carousel  (0) 2022.09.19