网页小游戏代码:猜数字游戏 - 简单易懂的实现
<!DOCTYPE html>
<html>
<head>
<title>猜数字游戏</title>
<style>
body {
text-align: center;
}
h1 {
color: #333;
}
p {
color: #777;
}
input {
padding: 5px;
margin: 10px;
}
button {
padding: 10px 20px;
background-color: #333;
color: #fff;
border: none;
cursor: pointer;
}
#result {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>猜数字游戏</h1>
<p>猜一个1到100之间的随机数字!</p>
<input type="number" id="guess" min="1" max="100" />
<br />
<button onclick="checkGuess()">猜</button>
<p id="result"></p>
<pre><code><script>
var targetNumber = Math.floor(Math.random() * 100) + 1;
var attempts = 0;
function checkGuess() {
var guess = parseInt(document.getElementById("guess").value);
if (guess === targetNumber) {
document.getElementById("result").innerHTML =
"恭喜你,猜对了!一共猜了" + attempts + "次。";
} else if (guess < targetNumber) {
document.getElementById("result").innerHTML = "太小了!再试一次。";
attempts++;
} else {
document.getElementById("result").innerHTML = "太大了!再试一次。";
attempts++;
}
}
</script>
</code></pre>
</body>
</html>
这是一个简单的猜数字游戏,玩家需要在输入框中输入一个1到100之间的数字,然后点击“猜”按钮来猜测。游戏会根据玩家的猜测给出相应的提示,直到猜中目标数字为止。页面会显示玩家一共猜了多少次才猜中。
原文地址: https://www.cveoy.top/t/topic/pRcQ 著作权归作者所有。请勿转载和采集!