-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.html
95 lines (84 loc) · 2.73 KB
/
main.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!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>Document</title>
</head>
<body>
<form id="form">
<input type="text" id="input">
<button id="btn">확인</button>
</form>
<div id="logs"></div>
<script>
const $input = document.querySelector('#input');
const $form = document.querySelector('#form');
const $logs = document.querySelector('#logs');
const numbers = [];
// for문
for (let n = 0; n < 9; n++){
numbers.push(n + 1);
}
// while 문
// let n = 1
// while(n < 10){
// numbers.push(n);
// n++
// }
const answer = []
for (let i = 0; i < 4; i++){
const index = Math.floor(Math.random() * numbers.length);
answer.push(numbers[index])
numbers.splice(index, 1)
}
const tries = [];
function checkInput(input){
if (input.length !== 4){
return alert('4자리 숫자를 입력해 주세요.');
}
if (new Set(input).size !== 4){
return alert('중복되지 않게 입력해 주세요.');
}
if (tries.includes(input)){
return alert('이미 시도한 값입니다.');
}
return true;
} //검사하는 코드
$form.addEventListener('submit', (event)=> {
event.preventDefault();
const value = $input.value;
$input.value = '';
if (!checkInput(value)){
return;
}
//입력값 문제없음
if (answer.join('') === value){
$logs.textContent = "홈런!";
return;
}
if (tries.length >= 9) {
const message = document.createTextNode(`패배! 정답은 ${answer.join('')}`);
$logs.appendChild(message);
return;
}
// 몇 스트라이크 몇 볼인지 검사
let strike = 0;
let ball = 0;
for (let i = 0; i < answer.length; i++){
const index = value.indexOf(answer[i]);
if(index > -1){
if(index === i){
strike += 1;
}else {
ball += 1;
}
}
}
$logs.append(`${value}: ${strike} 스트라이크 ${ball} 볼`, document.createElement('br'));
tries.push(value);
});
</script>
</body>
</html>