그럼에도 불구하고

👨‍💻

숫자 뽑기 게임 본문

JavaScript/Function implementation

숫자 뽑기 게임

zenghyun 2023. 1. 31. 11:00

숫자 뽑기 게임을 만들어보자

 

 

※ 조건 

1. 0부터 내가 선택한 숫자 범위 내에서 비교할 숫자를 입력해야 한다.

 

2. 비교할 숫자가 내가 선택한 숫자보다 클 수 없다.

 

3. 비교할 숫자는 0이거나, 음수일 수 없다.

 

4. 0부터 내가 선택한 숫자 범위 내에서 "Play!" 버튼을 누를 때마다 랜덤으로 숫자를 생성하여 비교할 숫자와 크기를 비교한다.

 

5, 비교 결과를 알려준다.

 

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
<!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>
  <style>
    #guideText {
      color: red;
    }
  </style>
</head>
 
<body>
  <h1>Random Number Game</h1>
  <p>Generate a number between 0 and <input type="number" id="choiceNum"></p>
  <p>Guess the number: <input type="number" id="guessNum"><button id="btn">Play!</button></p>
  <p id="guideText"></p>
  <p>You chose: <span id="myChose"></span>, the machine chose: <span id="randomPic"></span>.</p>
  <p id="showWinner"></p>
  <script src="./main.js"></script>
</body>
 
</html>
cs

 

 

JavaScript

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
const btn = document.querySelector('#btn');
const randomPic = document.querySelector('#randomPic');
const showWinner = document.querySelector('#showWinner');
const myChose = document.querySelector('#myChose');
const guess = document.querySelector('#guessNum');
 
btn.addEventListener('click', () => {
  const choice = document.querySelector('#choiceNum');
  const choiceNum = parseInt(choice.value);
  const guessNum = parseInt(guess.value);
  const guideText = document.querySelector('#guideText');
 
  if ( guessNum > parseInt(choice.value)) {
    guideText.innerText = "선택한 숫자가 범위보다 큽니다. 다시 입력해주세요";
    guess.value = "";
    showWinner.innerText = "";
    randomPic.innerText = "";
  } else if ( guessNum <= 0) {
    guideText.innerText = "선택한 숫자는 0이거나, 음수일 수 없습니다. ";
    guess.value = "";
    showWinner.innerText = "";
    randomPic.innerText = "";
  } else {
    guideText.innerText = "";
    myChose.innerText = guessNum;
    let random = Math.floor(Math.random() * choiceNum);
    randomPic.innerText = random;
    (random > guessNum) ?
      (showWinner.innerText = "You lose!") : (random < guessNum) ?
        (showWinner.innerText = "You win!") : (showWinner.innerText = "Draw!");
  }
})
 
guess.addEventListener('click', () => {
  guess.value = "";
  myChose.innerText = '';
  showWinner.innerText = "";
  randomPic.innerText = "";
})
cs

 

 

 

결과

See the Pen Untitled by zenghyun (@zenghyun) on CodePen.

 

Comments