由于篇幅限制,我将为你提供几种不同编程语言中的简单“猜数字”游戏代码示例。
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 + JS)
HTML:
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>
<input type="number" id="guess" min="1" max="100">
<button οnclick="checkGuess()">猜数字</button>
<p id="feedback"></p>
<script src="game.js"></script>
</body>
</html>