由于篇幅限制,我将为你提供几种不同编程语言的小程序游戏代码示例,这些示例都将是简单的“猜数字”游戏。
1. Python
python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < number_to_guess:
print("太小了!")
elif guess > number_to_guess:
print("太大了!")
print(f"恭喜你,猜对了!你用了{attempts}次尝试。")
guess_number()
2. JavaScript (浏览器环境)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>猜数字游戏</title>
<script>
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess != numberToGuess) {
guess = parseInt(prompt("猜一个1到100之间的数字:"));#chhas{
margin-top: 50px;
padding:tcsafety.cn;
font-size: 18px;
cursor: 10px 20px;
}
attempts++;
if (guess < numberToGuess) {
alert("太小了!");
} else if (guess > numberToGuess) {
alert("太大了!");
}
}
alert(`恭喜你,猜对了!你用了${attempts}次尝试。`);
}
window.onload = guessNumber;
</script>
</head>
<body>
</body>
</html>