HANGMAN 제작 #1

이석원·2022년 8월 14일
0

지나갔던 옛 과제들을 회고하기보다 새롭게 만들 때 더 나은 공부가 될것으로 믿고 토이 프로젝트를 시작했다.

첫 번째 버전은 동작의 구현에 초점을 두었다. windows.prompt, windows.confirm, windows.alret 을 활용해서 만들었다. html 페이지는 통로 역할만 할 뿐이다. 다음 버전을 위한 연습이었다.

전체 코드는 아래와 같다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Website</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <main>
        <h1 >Welcome</h1>
    <p ></p>
	<script src="hangman.js"></script>
  </body>
</html>

아래는 자바스크립트

const isStart = ()=>{
    const answer = window.confirm("Hangman Game start");
    if(answer){
        main();
    }else{
        window.alert("Goodbye");
    }
}const problemSet = {
    0 : "apple",
    1 : "relation",
    2 : "postman",
    3 : "gray",
    4 : "hijack"
}const problemSetLength = Object.keys(problemSet).length;const again=()=>{
    const restart = window.confirm("Again?");
    if(restart) main();
    return;
}const main = ()=>{
    const number = Math.floor((Math.random()*problemSetLength));
    const problem = problemSet[number];
    let life = problem.length + 5;
    let inputWindow = new Array(problem.length).fill("_");
    const answer = problem.split("");
    while(life>0){
        let userAnswer = window.prompt(inputWindow.join(" "));
        if(answer.includes(userAnswer)){
            for(let i=0; i<answer.length; i++){
                if(answer[i] === userAnswer) inputWindow[i] = userAnswer;
            }
        }else{
            life--;
            window.alert(`Wrong Answer!\nYour Life : ${life}`);
        }
        if(!inputWindow.includes("_")){
            window.alert("Game Set, You Win");
            again();
            return;
        }
    }
    window.alert("Game Over");
    again();
    return;
}isStart();
profile
개발자 공부중

0개의 댓글