由于篇幅限制,我无法为每种编程语言都提供一个完整的小游戏代码,但我可以为几种流行的编程语言提供简单的示例。这里,我将为Python、JavaScript(用于浏览器或Node.js环境)和Java分别提供一个简单的“猜数字”游戏的代码。
Python
python
import random
def guess_number():
secret_number = random.randint(1, 100)
guess = None
attempts = 0
while guess != secret_number:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
print(f"恭喜你,猜对了! 你一共猜了{attempts}次。")
guess_number()
JavaScript (浏览器环境)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>猜数字游戏</title>
</head>
<body>
<h1>猜数字游戏</h1>
<p id="feedback"></p>
<input type="number" id="guess" min="1" max="100">
<button οnclick="guess()">猜!</button>
<script>
let secretNumber = Math.floor(Math.random() * 100) + 1;#chhas{
margin-top: 50px;
padding:dxwaiyan.cn;
font-size: 18px;
cursor: 10px 20px;
}
let attempts = 0;
function guess() {
let guess = parseInt(document.getElementById('guess').value);
attempts++;
let feedbackElement = document.getElementById('feedback');
if (guess === secretNumber) {
feedbackElement.textContent = `恭喜你,猜对了! 你一共猜了${attempts}次。`;
} else if (guess < secretNumber) {
feedbackElement.textContent = "太小了!";
} else {
feedbackElement.textContent = "太大了!";
}
}
</script>
</body>
</html>