[HTML/CSS/Javascript] 타자 게임 만들기

김선우·2022년 1월 7일

HTML/CSS/Javascript

목록 보기
4/9
post-thumbnail

Typing Game
누르면 게임으로 접속합니다!

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Typing Game</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> 
</head>
<body>
    <div class = "header">
        <h1>타이핑 게임 made by 선우</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>
           남은 시간: <span class = "time">0</span></div>
        <div>
            획득 점수: <span class ="score">0</span></div>
    </div>
    <button class="button loading" onclick = "run()">게임을 불러오는중...</button>
    <script src= "js/main.js"></script>
</body>
</html>

CSS

* {
    margin: 0;
    padding: 0;
}

body {
     display: flex;  /*이거 공부하기 */
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.header {
    width: 100%;
    background: #3b5999;
    color: #fff;
    text-align: center;
    padding: 1rem;
}

.word-display {
    margin-top: 3rem;
    font-size: 80px;
    color: #3b5999;
}

.word-input-box{
    margin-top: 2rem;
}

.word-input {
    padding: 0.5rem;
    width: 300px;
}

.game-info {
    margin-top: 2rem;
    font-size: 0.8rem;
    display: flex;
    justify-content: space-between;
    width: 200px; 
}

.time, .score {
    font-size: 30px;
}

.button {
    width: 200px;
    height: 35px;
    background: #3b5999;
    color: #fff;
    border: none;
    margin-top: 3rem;
    cursor: pointer;
}

.loading {
    background: #ccc;
    cursor: not-allowed;
}

JS

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

// const
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");

init();

function init() {
    buttonChange("게임로딩중...");
    getWords()
    wordInput.addEventListener('input', checkMatch)
} 

//게임 실행
const GAME_TIME = 9;
 let score = 0;
 let time = GAME_TIME;
 let isPlaying = false;
 let timeInterval;
 let words = [];
 let checkInterval;

// const
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");

init();

function init() {
    buttonChange("게임로딩중...");
    getWords()
    wordInput.addEventListener('input', checkMatch)
} 

    // .addEventListener('이벤트','함수')

//게임 실행(index에 onclick = run()으로 연결.)
function run() {
    if(isPlaying) {
        return;
    }
    isPlaying = true; // function buttonChange() 실행
    time = GAME_TIME;
    wordInput.focus(); // 마우스커서 여기로
    scoreDisplay.innerText = 0;
    timeInterval = setInterval(countDown,1000); // 1000미리초 (1초)
    checkInterval = setInterval(checkStatus, 50);
    buttonChange("게임중");
}

    

function checkStatus() {
    if(!isPlaying && time === 0) {
        buttonChange("게임시작");
        clearInterval(checkInterval);
    }
}

//단어 불러오기 //package 사용해서 랜덤단어 생성
function getWords() {
    axios.get('https://random-word-api.herokuapp.com/word?number=100') // random단어생성 api
        .then(function (response) {
            // handle success

            response.data.forEach((word) => {
                if (word.length < 10) {
                    words.push(word);
                }
            })
            buttonChange("게임시작");

  
        })
        .catch(function (error) {
            // handle error
            console.log(error);
        })
        .then(function () {
            // always executed
        });
    buttonChange("게임시작");
}



//단어일치 체크하고 새로운 단어로 나타내기
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]
    }
}

    // Math.random() : 0이상 1미만의 난수를 생성
    // Math.floor() : 소수점 이하를 반올림
    // toLowerCase() 모든 문자 소문자로

// setInterval(countDown,1000);
    //setTimeout을 이용해 일정 시간이 지난 후에 함수를 실행
    //setInterval을 이용해 일정 시간 간격을 두고 함수를 실행


function countDown() {
    time > 0 ? time -- : isPlaying = false; 
    
    // 시간 0전에 맞추면 checkMatch() 실행. 점수 오르고 시간 초기화, 새로운 단어 보여줌.
    // 시간 0이 되면 isPlaying = false -> checkStatus() 실행)

    if(!isPlaying) {
        clearInterval(timeInterval)
    }
    timeDisplay.innerText = time;

    // 시간 0 되면 더이상 시간이 흐르지 않고 게임시작으로 바뀜, 다시 반복
}

    // '삼항 연산자' (조건) ? 참일경우 : 거짓일경우

function buttonChange(text) {
    button.innerText = text;
    text === "게임시작" ? button.classList.remove('loading') : button.classList.add('loading');
}
profile
꿈꾸는중

0개의 댓글