- Number Baseball, 숫자 야구
숫자 야구란, 랜덤한 세 자리 숫자가 주어지면 그 숫자가 무엇인지 맞혀보는 게임이다. 숫자와 숫자가 위치한 자리까지 일치하면 Strike, 자리는 일치하지 않으나 포함되어 있으면 Ball로 처리된다. 예를 들면, 랜덤한 숫자가 375이고 내가 745라고 예상했다면 7은 자리는 일치하지 않으나 포함되어 있으나 1 Ball로 처리되고, 4는 아예 포함되어 있지 않으니 Strike나 Ball 둘다 아니다. 5는 숫자와 자리까지 일치하니 1 Strike가 된다.
숫자 야구에 대한 자세한 설명 : https://namu.wiki/w/%EC%88%AB%EC%9E%90%EC%95%BC%EA%B5%AC
크게 막히는 부분은 없었다. 비효율적일 순 있으나 내가 설계한 대로 동작이 잘되니 뿌듯하다. 중간 중간에 구글링으로 필요한 것을 찾아내는 방법도 어느 정도 익혀가는 것 같다. 특히 MDN을 되도록이면 참고하려고 했다. 1차적인 자료를 읽어서 제대로 이해하고 써먹는 것이 나중에 응용하는 데에 있어 좋을 것이라 생각했기 때문이다. 뭐든 뿌리를 알아야 되지 않을까!
- 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 -->
<div class="contents">
<div class="clickButton">
<button id="startButton">Start</button>
<button id="restartButton">Restart</button>
</div>
<br />
<div class="notificationBox">
<p id="notice">[Notice!]</p>
<ul>
<li><p>Press the start button at first</p></li>
<li><p>Please enter only number</p></li>
<li><p>Don't enter duplicate number</p></li>
</ul>
</div>
<div id="numberBox"></div>
<div class="strikeBall">
<div id="strike">Strike</div>
<div id="ball">Ball</div>
<div id="chance"></div>
</div>
<input
type="number"
id="inputNumber"
oninput="handleOnInput(this, 3)"
placeholder="What is your number?"
/>
</div>
<!-- 야구게임 End -->
</section>
<script src="index.js"></script>
</body>
</html>
- CSS
body {
background-image: url("./images/bg.jpeg");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
font-family: "Varela Round", sans-serif;
}
.image-box {
display: flex;
justify-content: center;
align-items: center;
}
img {
width: 700px;
height: 200px;
}
h1 {
font-family: "Pacifico", cursive;
text-align: center;
font-size: 36px;
}
.contents {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.notificationBox {
padding: 15px;
border: 3px solid black;
border-radius: 5px;
background-color: white;
font-size: 20px;
font-weight: 300;
color: black;
}
#notice {
padding-top: 0px;
text-align: center;
font-size: 25px;
font-weight: 900;
}
#numberBox {
margin-top: 30px;
width: 400px;
height: 200px;
border: 3px solid black;
border-radius: 3px;
background-color: yellow;
display: flex;
text-align: center;
justify-content: center;
flex-direction: column;
font-size: 50px;
}
.strikeBall {
margin-top: 20px;
display: flex;
width: 200px;
height: 25px;
border: 3px solid black;
border-radius: 3px;
background-color: rgb(20, 207, 231);
justify-content: center;
}
#strike {
margin-top: 2px;
margin-right: 30px;
}
#ball {
margin-top: 2px;
margin-right: 30px;
}
#chance {
margin-top: 2px;
}
#inputNumber {
margin-top: 20px;
margin-bottom: 20px;
}
- JavaScript
var numberArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var startButton = document.querySelector("#startButton");
var restartButton = document.querySelector("#restartButton");
var inputNumber = document.querySelector("#inputNumber");
var numberBox = document.querySelector("#numberBox");
var strikeNumber = document.querySelector("#strike");
var ballNumber = document.querySelector("#ball");
var chance = document.querySelector("#chance");
let randomArray = [];
let chanceNumber = 10;
chance.textContent = chanceNumber;
inputNumber.style.display = "none";
restartButton.addEventListener("click", function reload() {
location.reload();
});
startButton.addEventListener("click", function createNumber() {
inputNumber.style.display = "";
startButton.remove();
numberBox.textContent = "? ? ?";
for (var i = 0; i < 3; i++) {
var randomIndex = Math.floor(Math.random() * numberArray.length);
var randomValue = numberArray[randomIndex];
numberArray.splice(randomIndex, 1);
randomArray.push(randomValue);
}
alert("Here is a new number. Guess what it is!");
console.log(randomArray);
});
function handleOnInput(el, maxlength) {
if (el.value.length > maxlength) {
el.value = el.value.substr(0, maxlength);
}
}
inputNumber.addEventListener("keypress", function (key) {
if (key.key === "Enter") {
var inputValue = inputNumber.value;
var inputValueArray = Array.from(inputValue);
console.log(inputValueArray);
if (inputValueArray.length < 3) {
alert("Please enter 3 digit number");
return;
}
var strike = 0;
var ballcount = 0;
for (var i = 0; i < 3; i++) {
if (inputValueArray[i] === randomArray[i]) {
strike += 1;
}
if (randomArray.indexOf(inputValueArray[i]) >= 0) {
ballcount++;
}
}
var ball = ballcount - strike;
if (ball < 0) {
ball = 0;
}
strikeNumber.textContent = strike + "S";
ballNumber.textContent = ball + "B";
console.log("strike : " + strike);
console.log("ball : " + ball);
if (strike === 3) {
numberBox.textContent = randomArray.join("");
alert(`YES! That's right!`);
}
chanceNumber = chanceNumber - 1;
chance.textContent = chanceNumber;
if (chanceNumber === 0) {
alert("Over! Please click restart button");
inputNumber.remove();
}
}
});
HTML과 CSS에서는 그저 배웠던 것들을 적용하면 되었기 때문에 크게 문제가 되는 건 없었다. JavaScript를 짤 때 몇 가지 문제에 직면해 애를 먹었다. 그 문제와 해결은 다음과 같이 했다.
0. 숫자 비교 등은 어떻게 할 것인가!
-> 일단 배열 형태로 랜덤한 숫자가 생성되게 하고, 유저가 입력하는 숫자도 Array.from으로 배열로 바뀌게 했다. 그 후 for문을 사용해 랜덤 숫자와 유저의 숫자를 비교했고 일치하면 strike의 숫자가 올라가게 했다. ball은 indexOf를 사용해서 count했다. 해당 숫자가 랜덤 숫자(randomArray)중에 존재하기만 해도 1이 올라간다.(ballcount++)
0-1. 이 때 문제가 생기는 것은 ball이다.
-> 랜덤한 숫자가 375이고 유저의 예상 숫자가 357이라면 strike는 정상적으로 1이 뜨나 ball은 3이 떠버린다. 1strike 2ball이 떠야되기 때문에 이는 잘못된 것이다. 하지만 간단하다. ball - strike해주면 된다 ^.^ ball - strike이 진짜 ball이기 때문에 앞의 ball은 ballcount로 만들었다.
1. 세 자리가 중복되지 않으면서 랜덤한 숫자 생성
-> 랜덤한 세 자리 숫자 생성을 위해 Math.floor와 Math.random을 사용했고, 중복되지 않도록 한 번 뽑힌 숫자는 splice로 제거 했다.
2. 3자리 숫자만 입력하게 하기
-> input의 type이 number일 때는 maxlength와 minlength가 안먹힌다. 그래서 handleOnInput을 사용해주었고 입력받은 숫자가 3자리 미만일 때는 곧바로 return이 되어 inputNumber에 추가된 함수가 종료되도록 하고 alert창을 띄우게 했다.
3. 여러번 start를 누를 경우, input에 여러번 입력할 경우 의도하지 않은 바가 나타난다.
-> 위 설계는 여러번 start를 누른다고 계속해서 랜덤한 3자리 숫자가 나타나지 않는다... 그리고 start를 누르지 않았는데 input에 입력하면 10번의 chance가 입력할 때마다 감소한다. 이것들은 단순하게 때에 따라 display를 none하는 것을 이용했다.
다른 사람이 어떻게 작업했는지는 모르겠다. 당연히 나보다 잘했겠지... 일부러 안 찾아보고 되는 대로 raw하게 해보자 생각하며 시도했는데 좀 퀄리티가 처참한 것 같다 ㅎㅎㅎ

'프로그래밍 > 바닐라코딩_Prep Guide' 카테고리의 다른 글
Step 5. JavaScript in Depth - Koans (0) | 2022.01.05 |
---|---|
Step 4. Interacting with WebPages(5) (0) | 2021.12.27 |
Step 4. Interacting with Webpages(4) (0) | 2021.12.21 |
Step 4. Interacting with Webpages(3) (0) | 2021.12.16 |
Step 4. Interacting with Webpages(2) (0) | 2021.12.16 |