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

3. 당근게임 - 타이머 만드는 법

by warrior.p 2022. 4. 4.

1. 얼마나 오래 게임을 할것인지 변수(상수)로 지정해줌

const GAME_DURATION_SEC = 5;

 

2. startGameTimer()

function startGame() {
  initGame();
  showStopButton();
  showTimerAndScore();
  startGameTimer();
} 스타트게임 안에 startGameTimer()이 있으니 ~함수를 만들어주자.


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

 

3. updateTimerText()
function updateTimerText(time) {
  const minutes = Math.floor(time / 60); // 나머지 버리고 integer만.
  const seconds = time % 60; //나머지만 표시
  timerIndicator.innerHTML = `${minutes}:${seconds}`;
}

 

 

'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');

//게임 상태를 기억하고 있는 변수
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() {}

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

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

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

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

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);
}

 

 

 

  • setInterval(a, X000)

X초마다 a를 실행 무한히. 멈추기 위해서듣 clearInterval을 넣어줘야함.

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

 

setInterval() - Web APIs | MDN

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

developer.mozilla.org