플레이버튼을 눌르게 되면 카운트가 시작되면서 시간내에 벌레와 당근을 잡는 게임
플레이버튼을 누르게 될때
벌레와 당근 생성
카운트 시작
벌레나 당근 잡는 갯수 카운트
다시시작 버튼
querySelector(.cssclass) - class를 찾아 선택한다.
element.getBoundingClientRect() - 위 셀렉터로 정의된 범위의 창 크기정보를 불러온다.
createElement('htmltag') - html태그요소를 생성
setAttribute('class', className) - 생성된 엘리먼트의 추가요소를 생성 ex-
radomNumber - 내장함수 random()을 이용한 랜덤함수
setInterval - 설정한 시간동안 지정된 함수를 반복 실행
element.innerText - htmltag사이 텍스트 삽입
element.style.type - style 타입과 값 삽입
element.appendChild() - element 하위 생성된child값 붙혀넣기
function radomNumber(min, max){
return Math.random() * (max - min) + min;
}
function initGame() {
console.log(fieldRect)
addItem('carrot', 5, 'img/carrot.png')
addItem('bug', 5, 'img/bug.png')
}
function addItem(className, count, imgPath){
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 = radomNumber(x1, x2);
const y = radomNumber(y1, y2);
item.style.left = `${x}px`;
item.style.top = `${y}px`;
field.appendChild(item);
}
}
함수 클래스이름, 오브젝트갯수, 이미지경로를 인자값에 할당시켜 위에 지정한 갯수만큼 html, style값을 생성하는 함수를 만들어 설정. 랜덤함수를 사용하여 x y값을 각 오브젝트에 스타일값이 할당되도록 하여 벌레와 당근이 윈도우 내에 임의의 좌표로 출력되도록 구현
const GAME_DURATION_SEC = 5;
function startGameTimer(){
let remainingTimeSec = GAME_DURATION_SEC;
upadteTimerText(remainingTimeSec);
timer = setInterval(()=>{
if(remainingTimeSec <= 0){
clearInterval(timer);
return;
}
upadteTimerText(--remainingTimeSec);
}, 1000)
}
function upadteTimerText(time){
const minutes = Math.floor(time / 60);
const seconds = time % 60
gameTimer.innerText = `${minutes}:${seconds}`
}
코드 내용.
setInterval를 사용해 반복되면서 remainingTimeSec로 할당된 5초를 줄여나가면서 upadteTimerText()함수 실행 카운트가 0이 되면 타이머 종료 api를 호출하고clearInterval(timer) return을 이용해서 조건문 탈출
function stopGame(){
stopGameTimer();
hideGameButton();
showPopupWithText('REPLAY');
}
function stopGameTimer(){
clearInterval(timer);
}
function hideGameButton(){
gameBtn.style.visibility = 'hidden';
}
function showPopupWithText(text){
popUpText.innerHTML = text;
popUp.classList.remove('pop-up--hide')
}
스톱타이머의 경우 앞서 셋타이머에서 생성된 clearInterval api를 다시 호출,
게임버튼을 숨기기 위해 css visibility 값 지정했던 것을 변경
위의 텍스트값을 전달받아 해당값이 태그에 쒸어지면서 보여지고 기본값으로 hide 처리 되어있던 class지정값을 삭제(삭제되면서 css지정되있던 display: none이 삭제).
field.addEventListener('click', (event) =>onFieldClick(event))
function onFieldClick(event){
if(!started){
return;
}const target = event.target;
if(target.matches('.carrot')){
target.remove();
score++;
updateScoreBoard()}
if(score === CARROT_COUNT){
finishGame(true)
}
else if (target.matches('.bug')){
stopGameTimer();
finishGame(false)
}
};
function updateScoreBoard(){
gameScore.innerText = CARROT_COUNT - score;
}
function finishGame(win) {
started = false;
hideGameButton();
showPopupWithText(win ? 'WIN💯' : 'LOSE🖕')
}
function hideGameButton(){
gameBtn.style.visibility = 'hidden';
}