본문 바로가기

코딩 공부 + IT 정보/코딩 실험

타자 게임 만들고 영어, 스페인어 공부해보자 (Vanilla JavaScript Speed Typing Game)

<타자 게임 만들기 도전>

 

 

지난번에는 넘버1의 요청으로 온라인 퀴즈앱을 만들었었다.

사이트를 보면 뭔가 좀 허전하다는 생각이 들어 타자 게임을 추가하고 싶어졌다.

영어와 스페인어 단어를 마음껏 불러 오고, 타자 게임과 동시에 키보드 연습도 되고 좋을 것 같았다.

그렇게 찾아낸 것이 바로 아래의 동영상이다.

 

Vanilla 자바스크립트 타자게임 만들기! 실전코스

 

너무나 감사하게도 우리말로 공부를 할 수 있다.

보통 이렇게 따라 만드는 영상은 외국게 많아서 한국분이 설명해 주시는 자료는 정말 귀하다.

(감사합니다>.<)

 

 

내가 만든 타자 게임은 문제를 풀 때마다 정답 확인을 할 수 있게 약간 변형했다.

사이트 타이틀 css도 약간 반짝거리게 바꿔봤다.

소스는 아래와 같다.

 

 

 

index.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>English Words 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-box">
        <div class="header">
            <h1>English Words Game</h1>
        </div>
    </div>
    <div class="word-display">Hello</div>
    <div class="word-input-box">
        <input type="text" class="word-input">
    </div>
    <div class="message"></div>
    <div class="game-info">
        <div>
            Time Left: <span class="time">0</span>
        </div>
        <div>
            Score: <span class="score">0</span>
        </div>
    </div>
    <button class="button loading">loading...</button>
    <!-- <button class="button loading" onclick="run()">loading...</button> -->

    <script src="js/main.js"></script>

</body>
</html>

 

css 폴더 만들고 style.css 파일 저장

*{
    margin: 0;
    padding: 0;
}

body{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
}
.header-box{
    width:100%;
    background: white;
    text-align: center;
    padding: 30px;
    border-bottom: 1px solid lightgray;
}
.header{
    width: 100%;
    
    color:transparent;
    background-image: linear-gradient(to left,beige,purple,rgb(18, 63, 122), white,#3b5999 ,powderblue,silver);
    -webkit-background-clip:text;
    background-size:500%;
    animation: animate 11s linear infinite;
}
@keyframes animate{
    0%{
        background-position: 0 100%;
    }
    50%{
        background-position: 100% 0;
    }
    100%{
        background-position: 0 100%;
    }
}

.word-display{
    margin-top: 4rem;
    font-size:70px;
    /* color: #3b5999; */
    color: rgb(131, 130, 190);
    font-weight: 550;
}

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

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

.game-info{
    margin-top: 2rem;
    font-size: 1rem;
    display: flex;
    width: 250px;
    justify-content: space-evenly;
    color:gray;
}

.time, .score {
    font-size: 25px;
    color: rgb(131, 130, 190);
    font-weight: 500;
}

.button{
    margin-top: 50px;
    width: 200px;
    height: 35px;
    background-color:rgb(130, 126, 185);
    color:white;
    border: none;
    border-radius: 5px;
    border-bottom: 2px solid rgb(79, 73, 104);
    border-right: 2px solid rgb(79, 73, 104);
    cursor:pointer;
    outline: none;
    transition: all 0.1s ease-out;
    
}
.button:hover{
    background: rgb(83, 73, 122);
}
.button:active{
    transform: translate(1px, 2px);
}
.loading:hover{
    background: gray;
}
.loading:active{
    transform: none;
}

.loading{
    background: gray;
    cursor:not-allowed;
    /* pointer-events: none; */

}

.word-input.disabled{
    pointer-events: none;
}


.message{
    font-size: 1rem;
    margin-top:25px;
    color:rgb(248, 139, 139);
    font-weight: 600;
}

 

 

 

js 폴더 만들고 main.js 파일 저장

const Game_Time = 6;
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");
const message = document.querySelector(".message");



init();



function init(){
    buttonChange("Game loading..");
    getWords();
    wordInput.classList.add("disabled");


}

//게임 실행

button.onclick = ()=>{
    run();   
    score = 0;

    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("Game Playing...");
    wordInput.classList.remove("disabled");
    message.innerHTML = "";
}


function checkStatus(){
    if(!isPlaying && time === 0){
        buttonChange("Game Start");
        clearInterval(checkInterval);
        wordInput.value = "";
        wordInput.blur();
        wordInput.classList.add("disabled");
        message.innerHTML = "Game Over!!";


    }
}


//단어 불러오기
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");

    //         // words = response.data;
        })
        .catch(function (error) {
            // handle error
            console.log(error);
        });

}


//단어 일치 체크
function checkMatch(){
    if(wordInput.value.toLowerCase() === wordDisplay.innerText.toLowerCase()){
        wordInput.value = "";
        message.innerHTML= "Correct!";
        if(!isPlaying){
            return;
        }
        score++;
        time = Game_Time;
        scoreDisplay.innerText = score;
        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");
}

 

그리고 참고 동영상이 하나 더 있다.

아래 주소를 확인하시길~

 

Build A Speed Typing Game In JavaScript

 

 

타자 게임에는 영어와 스페인어 둘 다 불러 올 수 있다.

이 과정에서 깃허브와 다른 사람의 모듈을 다운로드 받아 이용하고 api를 사용한다는 것을 알게 되었는데 이게 생각보다 많이 어려웠다.

영어와 스페인어 단어들을 배열로 타자 게임에 직접 집어넣는건 가능했는데 엄청 많은 양의 단어를 랜덤으로 불러오는 과정에서 막혀버렸다.

 

내가 시도했던 사이트는 이곳이다.

 

 

GitHub - words/an-array-of-spanish-words: List of ~636,000 Spanish words

List of ~636,000 Spanish words. Contribute to words/an-array-of-spanish-words development by creating an account on GitHub.

github.com

 

여기에서 모듈을 다운받고 index.json에 있는 단어들을 어떤 방식으로 js 파일에 불러오는건지 알 수가 없었다..

난 아직 node.js를 모른다.

그래서 그런가...?

타자 게임에 스페인어를 랜덤으로 집어 넣고 넘버1의 홈페이지를 완성하고 싶었다.

하지만 여기에서 딱 막혀버렸다..

 

 

이걸 해결하기까지 얼마나 많은 시간이 걸릴지는 모르겠지만.. 꼭 해내고야 말겠다...!

 

To be continued...

 

 

호두룰루

호두룰루 만화와 굿즈를 만나보세요^^=

(인스타툰, 텀블러, 유리컵, 그립톡, 폰케이스, 슬리퍼 )

 

 

hodululu | 인포크링크

hodululu님의 멀티링크를 구경해보세요 👀

link.inpock.co.kr