跳转至

Coding Challenge #1#

Implement a game rest functionality, so that the player can make a new guess!

Your tasks#

  1. Select the element with the 'again' class and attach a click event handler
  2. In the handler function, restore initial values of the 'score' and 'secretNumber' variables
  3. Restore the initial conditions of the message, number, score and guess input fields
  4. Also restore the original background color (#222) and number width (15rem)

GOOD LUCK 😀


 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
'use strict';
let guessNum = Math.trunc(Math.random() * 20 + 1);
// document.querySelector('.number').textContent = guessNum;
let score = 20;
let highscore = 0;

const checkBtn = document.querySelector('.btn.check');

const displayMessage = message => {
  document.querySelector('.message').textContent = message;
};

checkBtn.addEventListener('click', () => {
  let myNum = Number(document.querySelector('.guess').value);
  !myNum && displayMessage('⛔️ No number!');

  // 答对的情况
  if (myNum === guessNum) {
    displayMessage('🎉 Correct Number!');

    document.querySelector('.number').textContent = guessNum;
    document.querySelector('body').style.backgroundColor = '#60b347';
    document.querySelector('.number').style.width = '30rem';

    // 如果超过了最高纪录,刷新
    if (score > highscore) {
      highscore = score;
      document.querySelector('.highscore').textContent = highscore;
    }
    // 答错的情况
  } else if (myNum !== guessNum) {
    // 确保在次数范围内
    if (score >= 1) {
      displayMessage(myNum > guessNum ? '📈 Too high!' : '📉 Too low!');
      score--;
      document.querySelector('.score').textContent = score;
    }
    if (score === 0) {
      displayMessage('💥 You lost the game!')
    }
  }
});

document.querySelector('.btn.again').addEventListener('click', () => {
  document.querySelector('body').style.backgroundColor = '#222';
  document.querySelector('.number').style.width = '15rem';
  document.querySelector('.number').textContent = '?';
  document.querySelector('.guess').value = '';

  score = 20
  document.querySelector('.score').textContent = score;

  guessNum = Math.trunc(Math.random() * 20 + 1);
  // document.querySelector('.number').textContent = guessNum;
  displayMessage('Start guessing...')
})

评论