介绍
系统会在1-100之间随机选择一个数字让你猜,并提示你猜大了还是小了,并实时更新你猜的次数。
代码
<!DOCTYPE html><html><head><title>猜数字游戏</title></head><body><h1>猜数字游戏</h1><p id="message"></p><button onclick="guess()">猜!</button><script>// 生成1到100之间的随机数var secretNumber = Math.floor(Math.random() * 100) + 1;var attempts = 0;function guess() {var guess = prompt("请输入你猜测的数字(1-100):");attempts++;// 检查输入是否为有效的数字,并且在1到100之间if (isNaN(guess) || guess < 1 || guess > 100) {document.getElementById("message").innerHTML = "请输入有效的数字(1-100)!";return;}// 检查猜测的数字是否等于秘密数字if (guess == secretNumber) {document.getElementById("message").innerHTML = "恭喜你,你猜对了!你尝试了" + attempts + "次。";} else if (guess < secretNumber) {document.getElementById("message").innerHTML = "你猜的数字太小了,请再试一次。你尝试了" + attempts + "次。";} else {document.getElementById("message").innerHTML = "你猜的数字太大了,请再试一次。你尝试了" + attempts + "次。";}}</script></body></html>