본문 바로가기
TIL/디지털트윈

5.19 행맨게임 만들기 프로젝트

by saramnim 2023. 5. 19.
728x90
vanila JS를 이용해 행맨게임을 만들어보자!

 

 

같이 수업 듣는 동기 분과 gpt와 함께 만들었다~!

 

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" />
    <link rel="stylesheet" href="style.css">
    <title>행맨게임</title>
  </head>
  <body>
    <div id="word-container">
      <h1>즐거운 행맨게임</h1>
      <button id="start-button" onClick = "window.location.reload()">게임시작</button>
      <p id="word-blank"></p>
      <div id = "input-box">
        <input type="text" id="guess-input" placeholder="     알파벳 입력" />
      <button id="guess-button">입력</button>
      </div>
      
      <p id="guesses">당신이 입력한 글자:</p>
      <p id="result"></p>
      <script src="index.js"></script>
    </div>
  </body>
</html>

 

js

class WordGuessGame {
  constructor() {
    this.words = [
      "dongbin",
      "hyeji",
      "jaehyung",
      "sungyeon",
      "sungi",
      "taegyeong",
      "seokjun",
      "yeonghoon",
      "jibin",
      "seokho",
      "hyeonwoo",
      "gangwoo",
      "taewook",
    ];
    this.selectedWord = "";
    this.guessesRemaining = 10;
    this.guessedLetters = [];
  }

  startGame() {
    this.selectedWord = this.getRandomWord();
    this.displayWordBlank();
    this.bindEvents();
  }

  getRandomWord() {
    return this.words[Math.floor(Math.random() * this.words.length)];
  }

  displayWordBlank() {
    const wordBlank = document.getElementById("word-blank");
    wordBlank.innerText = "□".repeat(this.selectedWord.length);
  }

  bindEvents() {
    const guessButton = document.getElementById("guess-button");
    guessButton.addEventListener("click", this.handleGuess.bind(this));

    const guessInput = document.getElementById("guess-input");
    guessInput.addEventListener("keyup", (event) => {
      if (event.key === "Enter") {
        this.handleGuess();
      }
    });
  }

  handleGuess() {
    const guessInput = document.getElementById("guess-input");
    const guess = guessInput.value.toLowerCase().trim();
    
    if (!guess || this.guessedLetters.includes(guess)) {
      guessInput.value = "";
      return;
    }

    this.guessedLetters.push(guess);
    this.displayGuessedLetters();
    this.updateWordBlank();

    if (this.checkWin()) {
      this.displayResult(this.selectedWord);
      setTimeout(() => {
        alert("성공! 다시시작?");
        location.reload();
      }, 500);
    } else {
      this.guessesRemaining--;

      if (this.guessesRemaining === 0) {
        this.displayResult("실패");
        setTimeout(() => {
          alert("바보!");
          location.reload();
        }, 500);
      }
    }

    guessInput.value = "";
  }

  displayGuessedLetters() {
    const guessesElement = document.getElementById("guesses");
    guessesElement.innerText = `입력한 단어: ${this.guessedLetters.join(", ")}`;
  }

  updateWordBlank() {
    const wordBlank = document.getElementById("word-blank");
    const newWordBlank = [...this.selectedWord]
      .map((letter) => (this.guessedLetters.includes(letter) ? letter : "□"))
      .join("");
    wordBlank.innerText = newWordBlank;
  }

  checkWin() {
    return [...this.selectedWord].every((letter) =>
      this.guessedLetters.includes(letter)
    );
  }

  displayResult(result) {
    const resultElement = document.getElementById("result");
    resultElement.innerText = result;
  }
}

const game = new WordGuessGame();
game.startGame();

alert 후 reload가 바로 실행되는 문제가 있었는데, 팀원이 setTimeout을 사용하는 방법을 일러주어 해결할 수 있었다..!

그걸 생각을 못하고 메서드를 다시 불러오는 등 더 어렵게 일을 만들었었는데, setTimeout을 넣으니 내가 원하는 만큼 딜레이를 주어 정상작동 하도록 만들었다!

크크

 

css

@font-face {
    font-family: 'DOSGothic';
    src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_eight@1.0/DOSGothic.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}
body{
    background-image: url('./stars.png');
    background-size: cover;
    font-family: 'DOSGothic';
}

#word-container {
    margin-left: 30%;
    margin-right: 30%;
    margin-top: 8rem;
    background-color: #000;
    background-image: url('./stars.png');
    color: skyblue;
    text-align: center;
    border-radius:50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 30px;
}
#input-box {
    display: flex;
    flex-direction: row;
    gap: 10px;
}
button {
    font-family: 'DOSGothic';
    border: none;
    background-color:black;
    color: white;
    width: 20%;
    border-radius:20px;
    cursor: pointer;
}

#word-blank {
    letter-spacing: 5px;
    font-size: 25px;
}
#guess-input{
    font-family: 'DOSGothic';
    border:none;
    font-size: 22px;
}

#guesses {
    font-size: 20px;
}
728x90
반응형

댓글

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."