由于篇幅限制,我将分别为你提供三种编程语言(Python、JavaScript 和 Java)的简单小游戏代码示例:一个基本的“猜数字”游戏。
Python 版本
python
import random
def game():
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}次尝试。')
if __name__ == "__main__":
game()
JavaScript 版本(在浏览器控制台或HTML文件中运行)
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>