由于篇幅限制,我将为您提供几种不同编程语言中非常简单的“猜数字”游戏的代码示例。这个游戏要求玩家猜一个介于1到100之间的随机数字。
Python
python
import random
4er.cn
def game():
secret_num = random.randint(1, 100)
guess = None
attempts = 0
while guess != secret_num:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < secret_num:
print("太小了!")
elif guess > secret_num:
print("太大了!")
print(f"恭喜你,猜对了!你用了{attempts}次尝试。")
if __name__ == "__main__":
game()
JavaScript (可以在浏览器中运行或Node.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>
<button οnclick="startGame()">开始游戏</button>
<script src="game.js"></script>
</body>
</html>