■ 참고 영상
■ 게임 액션
1. 게임 시작 버튼을 눌러 카운트다운을 시작합니다.
2. 주어진 시간 안에 입장창에 나타나는 캐릭터를 입력하면 포인트가 적립됩니다.
3. 점수가 매겨지면 무작위로 단어가 주어집니다.
4. 제 시간에 받지 못하면 게임 오버입니다.
5. 다시 시작하려면 게임 시작 버튼을 다시 누르십시오.
■ 게임 기능
- 첫 게임 시작
- 입력 필드 자동 찌르기
- setInterval, clearInterval 사용
- 텍스트 설정에 따른 버튼 화면 표시
- 사용 축
- 수신된 데이터 중 특정 단어만 표시
- 단어가 일치하면 입력창 초기화
- 임의의 단어가 나오게하십시오
■ 코드
// 사용변수
const GAME_TIME = 9;
let score = 0;
let time = GAME_TIME;
let isPlaying = false;
let timeInterval;
let checkInterval;
let words = ();
const wordInput = document.querySelector('.word-input');
const wordDisplay = document.querySelector('.word-display');
const scoreDisplay = document.querySelector('.score');
const timeDisplay = document.querySelector('.time');
const button = document.querySelector('button');
function buttonChange(text) {
button.innerText = text;
text === '게임시작' ? button.classList.remove('loading') : button.classList.add('loading');
}
init();
function init() {
buttonChange('게임로딩중...');
getWords()
wordInput.addEventListener('input', checkMatch)
}
// 게임 실행
function run() {
if (isPlaying) {
return;
}
isPlaying = true;
time = GAME_TIME;
wordInput.focus();
scoreDisplay.innerText = 0;
timeInterval = setInterval(countDown, 1000);
checkInterval = setInterval(checkStatus, 50);
buttonChange('게임중')
}
function checkStatus() {
if(!isPlaying && time === 0) {
buttonChange("게임종료...")
clearInterval(checkInterval)
}
}
// 단어 불러오기
function getWords() {
axios.get('https://randmom-word-api.herokuapp.com/word?number=100')
.then(function (response) {
response.data.forEach((word) => {
if (word.length < 10) {
words.push(word)
}
})
buttonChange('게임시작');
console.log(words)
})
.catch(function (error) {
// handle error
console.log(error);
})
}
// 단어일치 체크
function checkMatch() {
if (wordInput.value.toLowerCase() === wordDisplay.innerText.toLowerCase()) {
wordInput.value="";
if(!isPlaying) {
return;
}
score++;
scoreDisplay.innerText = score;
time = GAME_TIME;
const randomIndex = Math.floor(Math.random() * words.length);
wordDisplay.innerText = word(randomIndex)
}
}
function countDown() {
time > 0 ? time-- : isPlaying = false;
if(!isPlaying) {
clearInterval(timeInterval)
}
timeDisplay.innerText = time;
}