由于不同编程语言有其独特的语法和用途,我将为你提供几个简单的“猜数字”游戏的示例代码,分别使用 Python、JavaScript(用于网页)和 Java(用于控制台)。
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()
JavaScript (用于网页)
HTML 部分 (index.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>
<h1>猜数字游戏</h1>
<input type="number" id="guess" min="1" max="100">
<button οnclick="checkGuess()">提交</button>
<p id="feedback"></p>
<script src="game.js"></script>
</body>
</html>