开发一个猜数字游戏,游戏应随机选择一个 100 以内的自然数, 然后邀请玩家在 10 轮以内猜出这个数字。每轮后都应告知玩家的答案正确与否,如果出错了,则告诉他数字是低了还是高了。并且应显示出玩家前一轮所猜的数字。一旦玩家猜对,或者用尽所有机会,游戏将结束。游戏结束后,可以让玩家选择再次开始。
思维:
1、随机生成一个100以内的自然数
2、记录玩家当前的轮数。从1开始
3、为玩家提供一种猜测数字的方法
4、一旦有结果提交,先将其记录下来,以便用户可以看到他们先前的猜测
5、然后检查他是否正确
6、如果正确:
1.显示祝贺消息
2.阻止玩家继续猜测
3.显示空间永续玩家重新开始游戏
7、如果出错
1、告诉玩家他们错了
2、语序他们输入另一个猜测
3、轮数加1
8、如果出错,并且玩家没有剩余轮次
1、告诉玩家游戏结束
2、阻止玩家继续猜测
3、显示空间允许玩家重新开始游戏
9、一旦游戏重启,确保游戏的逻辑和UI完全充值然后返回步骤1
html代码:
<!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>猜数字游戏</title>
<script type="text/javascript" src="./JS/猜数字游戏.js" async></script>
/*根据自己的实际改变*/
</head>
<body>
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
<label for="guessField">请猜数:</label>
<input type="text" id="guessField" class="guessField" />
<input type="submit" value="确定" class="guessSubmit" />
</body>
</html>
js代码:
let randomNumber = Math.floor(Math.random() * 100) + 1;
const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");
const guessSubmit = document.querySelector(".guessSubmit");
const guessField = document.querySelector(".guessField");
let guessCount = 1;
let resetButton;
/* 游戏逻辑 */
function checkGuess() {
/* 获取用户输入的内容,强制转换为数值 */
let userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = "上次猜的数:";
}
guesses.textContent += userGuess + " ";
if (userGuess === randomNumber) {
lastResult.textContent = "恭喜你!猜对了";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = "!!! GAME OVER !!!";
setGameOver();
} else {
lastResult.textContent = "您猜错了";
lastResult.style.backgroundColor = "red";
if (userGuess < randomNumber) {
lowOrHi.textContent = "你猜低了";
} else {
lowOrHi.textContent = "你猜高了";
}
}
guessCount++;
guessField.value = "";
guessField.focus();
}
/* 结束游戏 */
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement("button");
resetButton.textContent = "开始新游戏";
document.body.appendChild(resetButton);
resetButton.addEventListener("click", resetGame);
}
/* 初始化 */
function resetGame() {
guessCount = 1;
const resetParas = document.querySelectorAll(".resultParas p");
for (let i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = " ";
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = "";
guessField.focus();
lastResult.style.backgroundColor = "white";
randomNumber = Math.floor(Math.random() * 100) + 1;
}
guessSubmit.addEventListener("click", checkGuess);