由于篇幅限制,我将为你提供三种常见编程语言(Python, JavaScript, 和 C++)的简单游戏代码示例:一个基本的猜数字游戏。
1. 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"恭喜你,猜对了!数字是 {secret_number},你用了 {attempts} 次尝试。")
guess_number()
2. JavaScript 版本(HTML + JavaScript)
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>
<p>猜一个1到100之间的数字</p>
<input type="number" id="guessInput" min="1" max="100">
<button οnclick="guessNumber()">猜</button>
<p id="feedback"></p>
<script src="game.js"></script>
</body>
</html>