之前我们实现了游戏的主体功能,以及恢复之类的功能!本次我们来实现高分榜的功能
功能的需求如下:
● 这个逻辑非常的简单,就是当我们猜对了数字后,跟我们的highscore做比较,如果比highscore高的话,就赋值给score
'use strict';
// console.log(document.querySelector('.message').textContent);
// document.querySelector('.message').textContent = 'Correct Number';
// document.querySelector('.number').textContent = 13;
// document.querySelector('.score').textContent = 16;
// console.log(document.querySelector('.guess').value);
// document.querySelector('.guess').value = 23;
// console.log(document.querySelector('.guess').value);
let secretnumber = Math.trunc(Math.random() * 20) + 1;
let score = 20;
let highscore = 0;
document.querySelector('.check').addEventListener('click', function () {
const guess = Number(document.querySelector('.guess').value);
console.log(guess);
if (!guess) {
document.querySelector('.message').textContent = '⛔No Number';
} else if (guess === secretnumber) {
document.querySelector('.message').textContent = 'Correct Number';
document.querySelector('body').style.backgroundColor = '#60b347';
document.querySelector('.number').style.width = '30rem';
document.querySelector('.number').textContent = secretnumber;
if (highscore < score) {
highscore = score;
document.querySelector('.highscore').textContent = highscore;
}
} else if (guess > secretnumber) {
if (score > 1) {
document.querySelector('.message').textContent = 'Too high';
score--;
document.querySelector('.score').textContent = score;
} else {
document.querySelector('.message').textContent = 'You lost the game!';
document.querySelector('.score').textContent = 0;
}
} else if (guess < secretnumber) {
if (score > 1) {
document.querySelector('.message').textContent = 'Too low';
score--;
document.querySelector('.score').textContent = score;
} else {
document.querySelector('.message').textContent = 'You lost the game';
document.querySelector('.score').textContent = 0;
}
}
});
document.querySelector('.again').addEventListener('click', function () {
score = 20;
document.querySelector('.score').textContent = score;
document.querySelector('body').style.backgroundColor = '#222';
document.querySelector('.message').textContent = 'Start guessing...';
document.querySelector('.number').style.width = '15rem';
document.querySelector('.number').textContent = '?';
document.querySelector('.guess').value = '';
secretnumber = Math.trunc(Math.random() * 20) + 1;
});
这样我们的猜数字小游戏已经完成了,但是看上面的代码,不知道大家有没有发现有很多重复的代码,例如太高了或太低了代码非常的相似,下节课我们来优化代码