当前位置:首页 / 文章测试 / PY 猜数

PY 猜数

开始打字练习

import random

import time

def number_guessing_game():

"""猜数字游戏主函数"""

print("=" * 40)

print("欢迎来到猜数字游戏!")

print("我会想一个1到100之间的随机数字")

print("你需要猜出这个数字,我会告诉你猜大了还是猜小了")

print("看看你能用多少次猜对吧!")

print("=" * 40)

print()

# 游戏设置

max_number = 100

secret_number = random.randint(1, max_number)

attempts = 0

guessed_numbers = []

difficulty = choose_difficulty()

# 根据难度设置最大尝试次数

max_attempts = {

'简单': 15,

'中等': 10,

'困难': 7

}[difficulty]

print(f"已选择{difficulty}难度,你有{max_attempts}次机会")

print("游戏开始!")

print()

# 游戏主循环

while attempts < max_attempts:

# 获取玩家猜测

try:

guess = input(f"请输入你猜的数字(1-{max_number}): ")

guess = int(guess)

# 验证输入范围

if guess < 1 or guess > max_number:

print(f"请输入1到{max_number}之间的数字!")

continue

# 检查是否重复猜测

if guess in guessed_numbers:

print("你已经猜过这个数字了,请换一个!")

continue

# 记录猜测

attempts += 1

guessed_numbers.append(guess)

# 检查猜测结果

if guess < secret_number:

print("猜小了!再试试更大的数字")

elif guess > secret_number:

print("猜大了!再试试更小的数字")

else:

# 猜对了

print()

print("=" * 40)

if attempts == 1:

print("太神奇了!你一次就猜对了!")

elif attempts <= 5:

print(f"太棒了!你只用了{attempts}次就猜对了!")

elif attempts <= max_attempts // 2:

print(f"不错!你用了{attempts}次猜对了!")

else:

print(f"恭喜你!你用了{attempts}次猜对了!")

print(f"秘密数字就是: {secret_number}")

print("=" * 40)

break

# 显示剩余次数

remaining = max_attempts - attempts

if remaining > 0:

print(f"还剩{remaining}次机会")

# 提供提示(在困难模式下提示较少)

if difficulty != '困难' and remaining <= max_attempts // 2:

give_hint(guess, secret_number, max_number)

print()

except ValueError:

print("请输入有效的数字!")

# 游戏结束但未猜对

if attempts >= max_attempts and guess != secret_number:

print()

print("=" * 40)

print(f"游戏结束!你已经用完了所有{max_attempts}次机会")

print(f"秘密数字是: {secret_number}")

print("=" * 40)

# 询问是否再玩一次

play_again = input("\n想再玩一次吗?(是/否): ").strip().lower()

if play_again in ['是', 'y', 'yes', '1']:

number_guessing_game()

else:

print("\n谢谢参与!下次再见!")

time.sleep(1)

def choose_difficulty():

"""让玩家选择游戏难度"""

while True:

print("请选择难度:")

print("1. 简单 (15次机会)")

print("2. 中等 (10次机会)")

print("3. 困难 (7次机会)")

choice = input("请输入1-3选择难度: ").strip()

if choice == '1':

return '简单'

elif choice == '2':

return '中等'

elif choice == '3':

return '困难'

else:

print("请输入有效的选项(1-3)!")

print()

def give_hint(guess, secret, max_num):

"""给玩家提供提示"""

difference = abs(guess - secret)

percentage = (difference / max_num) * 100

if percentage < 10:

print("提示:非常接近了!就在附近!")

elif percentage < 20:

print("提示:很近了!再调整一点点")

elif percentage < 30:

print("提示:比较接近了")

elif percentage < 50:

print("提示:还有一段距离")

else:

print("提示:差得有点远哦")

if __name__ == "__main__":

# 启动游戏

number_guessing_game()

声明:以上文章均为用户自行发布,仅供打字交流使用,不代表本站观点,本站不承担任何法律责任,特此声明!如果有侵犯到您的权利,请及时联系我们删除。

本文打字速度TOP10

  • 暂无打字数据!