Po_tta_tt0
콩심콩 팥심팥 🌱
Po_tta_tt0
전체 방문자
오늘
어제
  • 분류 전체보기 (266)
    • 🐛 회고 (14)
    • 💭 생각 (2)
    • 🤸‍♀️ 내 프로젝트 (16)
      • FISH-NEWS (8)
      • MBTI 과몰입 테스트 (2)
      • twitter clonecoding with TS (4)
      • pilzagenda (2)
    • 👨‍👩‍👧‍👦 팀 프로젝트 (2)
      • 피우다 프로젝트 (0)
      • SEMO(세상의 모든 모임) (1)
      • 마음을 전하는 텃밭 (1)
      • Stackticon (0)
    • 👨‍💻 CS지식 (11)
    • ✍ 공부 (94)
      • JavaScript (21)
      • TypeScript (39)
      • Html (0)
      • CSS (2)
      • React (18)
      • NextJS (7)
      • Vue (1)
      • Python (1)
      • Django (0)
      • 개발환경 & 그 외 (2)
    • 🏄‍♀️ 코딩테스트 (99)
      • 🐍 Python (99)
    • 🐙 Git & GitHub (3)
    • 📑 오류기록 (8)
    • 📚 우리를 위한 기록 (9)
    • 수업 (3)
    • 강의 등 (2)
    • 👩‍🎓 SSAFY (0)
    • 👋 우테코 (0)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

  • 플로이드 워셜
  • 시뮬레이션
  • 자바스크립트
  • 백준 숨바꼭질
  • 문자열
  • 백준
  • DP
  • BFS + DP
  • 파이썬 감시 피하기
  • 파이썬
  • js
  • dfs
  • React
  • 파이썬 다익스트라
  • Next.js
  • 구현
  • react-router-dom
  • bfs
  • 백준 파이썬
  • 이분탐색

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Po_tta_tt0

콩심콩 팥심팥 🌱

[드림코딩 : browser101] 게임 만들기 실전 2 🎇
수업

[드림코딩 : browser101] 게임 만들기 실전 2 🎇

2021. 11. 2. 13:32
반응형

새로운 js 파일을 만들어서 스파게티 코드 탈출을 노렸다

 

수업을 한번 듣고 다시 만들어본 파일이라서 엘리님의 코드를 많이 참고했다.

역시 나 혼자 한번 해보고 수업을 들으니까 코드 전개가 더 쉽게 이해되고

이런 방법이 있었구나! 놀라기도 한다.

 

동생이 흉작이라고 이름지어준 사진

 

 

 

 

밑으로는 새로운 js 파일

* 깃허브 링크를 올리기에는 아직 부끄러워서 내용만 복붙

"use strict";

const gameStartBtn = document.querySelector(".game__startBtn");

const playShape = `<i class="fas fa-play"></i>`;

const stopShape = `<i class="fas fa-stop"></i>`;

const gameTime = document.querySelector(".game__time");

const ground = document.querySelector(".ground");

const groundHeight = ground.offsetHeight;

const groundWidth = ground.offsetWidth;

const popup = document.querySelector(".popup");

const popupBtn = document.querySelector(".popup__btn");

const popupResult = document.querySelector(".result");

const itemNum = 5;

const soundAlert = new Audio("sound/alert.wav");

const soundBg = new Audio("sound/bg.mp3");

const soundBug = new Audio("sound/bug_pull.mp3");

const soundCarrot = new Audio("sound/carrot_pull.mp3");

const soundWin = new Audio("sound/game_win.mp3");

let start = false;

let carrotNum = itemNum;



gameStartBtn.addEventListener("click", gameState);

function gameState() {

  if (!start) {

    gameStart();

  } else {

    gameStop();

  }

  start = !start;

}

 

let start = false를 선언해놓고

gameStartBtn을 누르면 선언한 start 값이 true/false로 변경되게 하였다.

이렇게 let을 잘 이용하면 값이 계속 업데이트(변경)될 수 있기 때문에 버튼을 눌러서 껐다 키는 등의 역할을 수행할 수도 있다.

 

이 안에 들어있는

gameStart()

와

gameStop()

는

다른 함수들을 모아두는 함수로 이해했다.

 

간단하게 말하면

function 일본에 간다

function 베트남에 간다

안에

function 라멘을 먹는다

function 쌀국수를 먹는다

function 비행기를 탄다

function 오사카에 간다

등을 퍼즐맞추기처럼 맞는 자리에 집어넣는 것이다.

 

즉

function 일본에 간다

- function 라멘을 먹는다

- function 비행기를 탄다

- function 오사카에 간다

function 베트남에 간다

- function 쌀국수를 먹는다

- function 비행기를 탄다

 

이런 느낌

 

 

 

function gameStart() {

  carrotNum = itemNum;

  buttonShape(stopShape);

  displayItems();

  intervalTime();

  Sound(soundBg);

  visibility(gameStartBtn, "visible");

  console.log("시작");

}

function gameStop() {

  buttonShape(playShape);

  bgSoundPause();

  deleteItems();

  intervalTimeStop();

  visibility(gameStartBtn, "hidden");

  console.log("끝");

}

function buttonShape(shape) {

  gameStartBtn.innerHTML = `${shape}`;

}



function displayItems() {

  deleteItems();

  for (let i = 0; i < itemNum; i++) {

    bringItems("bug", 50);

    bringItems("carrot", 80);

  }

}



function bringItems(item, size) {

  const x = Math.floor(Math.random() * (groundWidth - size));

  const y = Math.floor(Math.random() * (groundHeight - size));

  const img = document.createElement("img");

  img.setAttribute("class", item);

  img.setAttribute("src", `img/${item}.png`);

  ground.appendChild(img);

  img.style.left = `${x}px`;

  img.style.top = `${y}px`;

}

function deleteItems() {

  ground.innerHTML = "";

}



let interval = false;

const playTime = 3;

 

여기소 볼 수 있는 let interval = false

도 let start = false와 비슷하다

일단 처음 시작했을 때는 버튼을 누르기 전까지 false를 유지해야 하기 때문이다.

 

function intervalTime() {

  let countTime = playTime;

  interval = setInterval(() => {

    displayTime(countTime);

    countTime--;

    if (countTime < 0) {

      bgSoundPause();

      intervalTimeStop();

    }

  }, 1000);

}

function intervalTime()이 시행되었을 때

interval은 false에서 setInterval()이 된다.

=> 평소에 interval을 꺼놓고 있다가(false) 필요할 때 작동시킬 수 있다

 

function intervalTimeStop() {

  clearInterval(interval);

  showResult("RETURN❔", soundAlert);

}

function displayTime(countTime) {

  const minute = Math.floor(countTime / 60);

  const second = countTime % 60;

  gameTime.innerHTML = `${minute}:${second}`;

}



function showResult(message, alert) {

  Sound(soundAlert);

  visibility(popup, "visible");

  visibility(gameStartBtn, "hidden");

  popupResult.innerHTML = message;

  buttonShape(playShape);

}



popupBtn.addEventListener("click", () => {

  visibility(popup, "hidden");

  start = true;

  gameStart();

});



function visibility(things, state) {

  things.style.visibility = state;

}



const gameCarrotsNum = document.querySelector(".game__numOfCarrots");

ground.addEventListener("click", (e) => {

  const target = e.target;

  console.dir(target);

  if (target.matches(".ground")) {

    return;

  } else if (target.matches(".carrot")) {

    Sound(soundCarrot);

    target.remove();

    carrotNum--;

    if (carrotNum <= 0) {

      gameStop();

      showResult("🥕🐇");

      Sound(soundWin);

    }

  } else {

    Sound(soundBug);

    gameStop();

    showResult("🐛");

  }

});



function Sound(sound) {

  sound.play();

}

function bgSoundPause() {

  soundBg.pause();

  soundBg.currentTime = 0;

}

 

반응형

'수업' 카테고리의 다른 글

[ study ] 웹 게임을 만들며 배우는 react  (0) 2022.03.18
[드림코딩 : browser101] 게임 만들기 실전 1 🍝  (0) 2021.10.24
    '수업' 카테고리의 다른 글
    • [ study ] 웹 게임을 만들며 배우는 react
    • [드림코딩 : browser101] 게임 만들기 실전 1 🍝
    Po_tta_tt0
    Po_tta_tt0
    감자의 코딩하는 블로그 콩심은데 콩나고 팥심은데 팥난다

    티스토리툴바