用python编写一个猜数字,包含难度选择,输入提示,次数剩余显示,成功和失败界面
时间: 2024-09-26 10:07:16 浏览: 30
你可以使用Python编写一个简单的猜数字游戏,下面是一个基础版本的代码示例:
```python
import random
def get_number(difficulty):
if difficulty == "easy":
number = random.randint(1, 10)
elif difficulty == "medium":
number = random.randint(11, 50)
else: # 难度设为"hard"
number = random.randint(51, 100)
return number
def guess_game():
print("欢迎来到猜数字游戏!")
difficulty = input("请选择游戏难度(easy, medium, hard): ")
number_to_guess = get_number(difficulty)
attempts = 6
print(f"你有{attempts}次机会猜对一个介于1到{number_to_guess}之间的数字。")
for attempt in range(attempts):
guess = int(input("请输入你的猜测: "))
if guess < number_to_guess:
print("太小了,再试一次。")
elif guess > number_to_guess:
print("太大了,再试一次。")
else:
print(f"恭喜!你猜对了,数字就是{guess}。")
break
if attempt == attempts - 1:
print("很遗憾,你没有猜对。正确答案是{}。".format(number_to_guess))
if __name__ == "__main__":
guess_game()
```
在这个游戏中,玩家可以选择不同难度等级,程序会生成相应的随机数。然后通过循环让玩家尝试猜测,每次给出提示直到猜对为止,如果超过最大尝试次数则会显示正确答案。
阅读全文