본문 바로가기
Front-end/Javascript 실습

4. 당근게임 - pause, replay 팝업

by warrior.p 2022. 4. 4.

 

1. pause 버튼 생성을 위해 function stopGame() 안에 stopGameTimer()를 넣고 

function stopGame() {
  stopGameTimer();

}

function stopGameTimer를 선언해준다.

function stopGameTimer() {
  clearInterval(timer);
} - 타이머 중지.

 

2. 타이머가 중지되면, pause버튼은 사라지고 다시하기 팝업을 생성한다.

function stopGame() {
  stopGameTimer();
  hideGameButton();
  showPopUpWithText('REPLAY?');
}

 

3. 팝업창의 DOM요소를 모두 가져와준다.

const popUp = document.querySelector('.pop-up');
const popUpText = document.querySelector('.pop-up__message');
const popUpRefresh = document.querySelector('.pop-up__refresh');

 

4. showPopUpWithText 함수를 선언한다.

function showPopUpWithText(text) {
  popUpText.innerText = text;  // REPLAY?
  popUp.classList.remove('pop-up--hide'); - html요소 삭제
}

 

 

 

'use strict';

const CARROT_SIZE = 80;
const CARROT_COUNT = 5;
const BUG_COUNT = 5;
const GAME_DURATION_SEC = 5;

const field = document.querySelector('.game__field');
const fieldRect = field.getBoundingClientRect();
const gameBtn = document.querySelector('.game__button');
const timerIndicator = document.querySelector('.game__timer');
const gameScore = document.querySelector('.game__score');

const popUp = document.querySelector('.pop-up');
const popUpText = document.querySelector('.pop-up__message');
const popUpRefresh = document.querySelector('.pop-up__refresh');

//게임 상태를 기억하고 있는 변수
let started = false; //게임이 시작 되었는지 안 되었는지
let score = 0; //최종 점수가 몇인지
let timer = undefined; //시간이 얼마 남았는지(시작하지 않으면 undefined)

function initGame() {
  field.innerHTML = ''; //게임을 새로시작할때 늘 필드는 빈곳으로~
  gameScore.innerText = CARROT_COUNT;
  //벌레와 당근을 생성한 뒤 필드에 추가해줌.
  addItem('carrot', CARROT_COUNT, 'img/carrot.png');
  addItem('bug', BUG_COUNT, 'img/bug.png');
}
gameBtn.addEventListener('click', () => {
  if (started) {
    stopGame();
  } else {
    startGame();
  }
  started = !started; //??
});

function startGame() {
  initGame();
  showStopButton();
  showTimerAndScore();
  startGameTimer();
}

function stopGame() {
  stopGameTimer();
  hideGameButton();
  showPopUpWithText('REPLAY?');
}

function showStopButton() {
  const icon = gameBtn.querySelector('.fas');
  icon.classList.add('fa-stop');
  icon.classList.remove('fa-play');
  gameBtn.style.visibility = 'visible';
}

function hideGameButton() {
  gameBtn.style.visibility = 'hidden';
}

function showTimerAndScore() {
  timerIndicator.style.visibility = 'visible';
  gameScore.style.visibility = 'visible';
}

function startGameTimer() {
  let remainingTimeSec = GAME_DURATION_SEC; //게임이 남아있는 시간동안 타이머 지속시키기위한 변수
  updateTimerText(remainingTimeSec);
  //지역변수로 설정하는 것이 아니라 게임 전체에 필요하므로 27번째 줄에 전역변수로 미리 선언해둠.target
  timer = setInterval(() => {
    if (remainingTimeSec <= 0) {
      clearInterval(timer);
      finishGame(score === CARROT_COUNT);
      return;
    }
    updateTimerText(--remainingTimeSec);
  }, 1000);
}

function stopGameTimer() {
  clearInterval(timer);
}

function updateTimerText(time) {
  const minutes = Math.floor(time / 60);
  const seconds = time % 60;
  timerIndicator.innerHTML = `${minutes}:${seconds}`;
}

function showPopUpWithText(text) {
  popUpText.innerText = text;  // REPLAY?
  popUp.classList.remove('pop-up--hide');
}

function addItem(className, count, imgPath) {
  //필드 안에서 아이템들을 absolute로 설정해서 랜덤하게 뿌려주기
  const x1 = 0;
  const y1 = 0;
  const x2 = fieldRect.width - CARROT_SIZE;
  const y2 = fieldRect.height - CARROT_SIZE;
  for (let i = 0; i < count; i++) {
    const item = document.createElement('img');
    item.setAttribute('class', className);
    item.setAttribute('src', imgPath);
    item.style.position = 'absolute';
    const x = randomNumber(x1, x2);
    const y = randomNumber(y1, y2);
    item.style.left = `${x}px`;
    item.style.top = `${y}px`;
    field.appendChild(item);
  }
}

function randomNumber(min, max) {
  return Math.random() * (max - min + min);
}

 

  • element.innerText;

이 속성은 element 안의 text 값들만을 가져옵니다.

 

  • element.innerHTML;

innerText와는 달리 innerHTML은 element 안의 HTML이나 XML을 가져옵니다.