[JS Toy Project] 타이핑 게임

sangyong park·2022년 9월 20일
0
post-thumbnail

Dom요소 조작과 함수 작동을 이용한 타이핑 게임

# UI/UX

HTML 코드

<html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Typing Game</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div class="header">
        <h1> Typing Game ! </h1>
    </div>
    <div class="word-display">
        Hello
    </div>
    <div class="word-input-box">
        <input type="text" class="word-input" />
    </div>
    <div class="game-info">
        <div>   
            Time: <span class="time">0</span></div>
        <div>
            score: <span class="score">0</span></div>
    </div>
    <button class="button loading" onclick="run()">Game comming..</button>
    <script src="./main.js"></script>
</body>
</html>
</html>

javascript 코드

<script>
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");

const GAME_TIME = 6;

let score = 0;
let time = GAME_TIME;
let isPlaying = false;
let timeInterval;
let words = [];
let checkInterval;

init();

function init () {
    buttonChange("Game load..")
    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("In Game");
}



function checkStatus () {
    if(!isPlaying && time === 0) {
        buttonChange("Game start");
        clearInterval(checkInterval);
    }
}

//단어 불러오기
function getWords () {
    axios.get('https://random-word-api.herokuapp.com/word?number=100')
        .then(function (response) {

            response.data.forEach((word) => {
                if (word.length < 10){
                    words.push(word);
                }
            })
        buttonChange("Game start");
    })
        .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 = words[randomIndex];
    }
}

function countDown () {
    time > 0 ? time-- : isPlaying = false;
    if (!isPlaying) {
        clearInterval(timeInterval);
    }
    timeDisplay.innerText = time;
}

function buttonChange (text) {
    button.innerText = text;
    text === "Game start" ? button.classList.remove("loading") : button.classList.add("loading");
}
</script>

# 기능

랜덤단어

api로 단어들을 가져와 단어를 입력하면 랜덤으로 다음 단어가 계속 나오도록
만들어 보았습니다.

<script>
//단어 불러오기
function getWords () {
    axios.get('https://random-word-api.herokuapp.com/word?number=100')
        .then(function (response) {

            response.data.forEach((word) => {
                if (word.length < 10){
                    words.push(word);
                }
            })
        buttonChange("Game start");
    })
        .catch(function (error) {
        // handle error
        console.log(error);
    })
}
</script>

시간제한

setInterval / clearInterval을 이용하여 게임에 시간제한을 두어 게임의 완성도를 더 올렸습니다.

<script>
// 게임 실행
function run () {
    if (isPlaying) {
        return;
    }
    isPlaying = true;
    time = GAME_TIME;
    wordInput.focus();
    scoreDisplay.innerText = 0;
    timeInterval = setInterval(countDown, 1000);
    checkInterval = setInterval(checkStatus, 50);
    buttonChange("In Game");
}

function countDown () {
    time > 0 ? time-- : isPlaying = false;
    if (!isPlaying) {
        clearInterval(timeInterval);
    }
    timeDisplay.innerText = time;
}
</script>

단어일치 체크

if문을 돌려 단어일치를 확인하여 정확하게 입력 했을 때 점수를 하나씩 올려주도록 설정 했습니다.

<script>
//단어 일치 체크
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 = words[randomIndex];    
    }
}
</script>

게임시작 버튼

게임시작 버튼을 누르면 버튼이 비활성화 되도록 설정하여 게임이 시작한 것을 확실하게 구분 지었습니다.

<script>

function buttonChange (text) {
    button.innerText = text;
    text === "Game start" ? button.classList.remove("loading") : button.classList.add("loading");
}
</script>
profile
Dreams don't run away It is always myself who runs away.

0개의 댓글