바닐라코딩 Starter Kit - Step 5 - Number Baseball

roadzmoon76·2022년 2월 4일
0

✏️ 진행과정

1. 게임 시작 버튼 만들기

  • 가운데에 놓기 위해 버튼의 모태그 <main> 을 만들고 flex 를 줌
  • 나중에 스타일을 주기 위해 CSS에 클래스를 만들고, 자바스크립트에서 클래스로 요소를 선택함

2. 게임 시작 버튼을 클릭 했을 때, 랜덤한 세 자리 숫자 만들기

  • 게임 특성상 자리만 맞은 경우와, 숫자만 맞은 경우가 분리 되어야 하므로 정답을 number 값으로 하기보단 array 로 만들어 각 자리수에 대한 인덱스도 부여하고, includes 메소드를 사용하는게 좋을 것 같아 빈 배열 randomNum 을 만들어줌
  • 나무위키 룰을 보니 세자리수가 067 이런 경우로도 되어서 배열의 각 자리에 0~9 를 배정해주는 함수를 만듬. Math 메소드의 결과값이 Number 속성이므로 String 으로 형변환 해줌
  • 애드리스너로 버튼에 클릭 이벤트시 그 함수가 실행되게 함
  • 콘솔 찍어서 정상 작동 확인

3. 숫자 입력칸 만들기

  • <input> 태그를 이용해 만들었고, 숫자만 받기위해 typenumber 로 둠

4. 사용자가 엔터키를 클릭 했을때, 입력값이 세자리 숫자가 아닌 경우 경고창 띄워주기

https://jinseong0928.blogspot.com/2012/03/input-box.html

  • 로그를 찍이서 input 박스 값을 스트링으로 받는다는걸 알아냄
  • userInput.value.length 를 이용해 3자리수인지 아닌지를

5. 사용자가 엔터키를 클릭 했을때, 2단계에서 생성한 숫자와 비교해서 스트라이크 개수, 볼 갯수 판별

6. 화면에 스트라이크와 볼의 갯수 표기

7. 사용자가 10회까지 시도한후 찬스 다쓰면 인풋창 비활성

8. 게임시작 버튼이 처음 누른후부터는 재시작 버튼으로바뀌며, 누르면 찬스초기화되며 새로운 랜덤번호 생성

📝 코드

📙 HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <link
      href="https://fonts.googleapis.com/css?family=Pacifico&display=swap"
      rel="stylesheet"
    />
    <link
      href="https://fonts.googleapis.com/css?family=Varela+Round&display=swap"
      rel="stylesheet"
    />
    <link rel="icon" href="/images/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>Baseball Project</title>
  </head>

  <body>
    <section>
      <div class="image-box">
        <img src="images/vanilla_coding_logo.png" />
      </div>
      <h1>Baseball</h1>

      <!-- 야구게임 Start -->
      <main>
        <button class="start-button">게임시작</button>
        <h3>0~9로 구성된 세자리 수를 입력해주세요(ex. 007)</h3>
        <h2></h2>
        <div class="chance"></div>
        <input
          type="number"
          class="user-input"
          disabled
          onkeypress="if(event.keyCode === 13) {play()}"
        />
      </main>
      <!-- 야구게임 End -->
    </section>

    <script src="index.js"></script>
  </body>
</html>

📘 CSS

body {
  background-image: url("./images/bg.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  font-family: "Varela Round", sans-serif;
}

h1 {
  font-family: "Pacifico", cursive;
  text-align: center;
  font-size: 72px;
}

main {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.start-button {
}

.user-input {
}

.chance {
  background-color: white;
}

📕 JS

//변수 모음

const startButton = document.querySelector(".start-button");
let randomNum = [];
const userInput = document.querySelector(".user-input");
let strikeNum;
let ballNum;
const nowScore = document.querySelector("h2");
let countNum = 10;
const chance = document.querySelector(".chance");


//함수 모음

function makeRandomNum () {
    for (let i = 0; i < 3; i++) {
        randomNum[i] = String(Math.floor(Math.random() * 10));
    }
    console.log(randomNum);
    startButton.textContent = '재시작';
    nowScore.textContent = '';
    countNum = 10;
    chance.textContent = `남은기회 : ${countNum}`;
    userInput.disabled = false;
    userInput.value = '';
}



function play () {
    if (userInput.value.length !== 3) {
        alert('3자리 숫자를 입력해주세요')
        return
    }
    strikeNum = 0;
    ballNum = 0;
    for (let i = 0; i < 3; i++) {
        if (userInput.value[i] === randomNum[i]) {
            strikeNum++;
        }
    }
    if (strikeNum === 3) {
        alert('🎉정답🎉');
        return
    } else if (strikeNum === 2) {
        nowScore.textContent = '2S 0B';
    } else if (strikeNum === 1) {
        nowScore.textContent = `1S ${ballCount() - 1}B`;
    } else {
        if (ballCount() === 0) {
            nowScore.textContent = 'OUT';
        } else {
            nowScore.textContent = `0S ${ballCount()}B`;
        }
    }
    countNum--;
    chance.textContent = `남은기회 : ${countNum}`;
    if (countNum === 0) {
        userInput.disabled = true;
    }
}

function ballCount () {
    ballNum = 0;
    for (let i = 0; i < 3; i++) {
        if (randomNum.includes(userInput.value[i])) {
            ballNum++;
        }
    }
    return ballNum;
}

//이벤트 모음
startButton.addEventListener("click", makeRandomNum);

🎉 결과

결과
깃허브

  • 나무위키 규칙대로 007 이런식으로 0이 들어간 세자리까지 입력가능하도록 만들음
  • 중복 숫자도 대응을 해놓음
  • 게임 기능만 구현하고 미적인건 전혀 건들지 않았는데 우선 프렙코스 신청 전까지 과제를 마치고싶어서 요구사항대로만 했고, 프렙코스 신청후 스타일을 수정할 것
  • 자기가 입력했던 숫자들과 그 결과를 기록해놓고 텍스트로 보여주는 기능과 자기가 입력했던 숫자를 또 입력하면 기회를 깎지 않고 알려주는 기능을 나중에 구현해보려 함
profile
크론병걸린 자퇴생, 개발자되기

0개의 댓글