游戏代码
import random
import time
def show_title():
"""显示游戏标题"""
print("=" * 40)
print(" 欢迎来到猜数字小游戏 ")
print("=" * 40)
print("规则:系统会随机生成一个数字,你需要在有限次数内猜中它!")
print("-" * 40)
def choose_difficulty():
"""选择游戏难度"""
print("请选择难度:")
print("1. 简单(1-10,10次机会)")
print("2. 中等(1-50,8次机会)")
print("3. 困难(1-100,5次机会)")
while True:
choice = input("请输入难度序号(1-3):")
if choice == '1':
return 10, 10
elif choice == '2':
return 50, 8
elif choice == '3':
return 100, 5
else:
print("输入错误,请重新选择!")
def play_game(max_num, attempts):
"""开始游戏"""
secret_num = random.randint(1, max_num)
print(f"\n游戏开始!我想了一个1到{max_num}之间的数字,你有{attempts}次机会猜~")
for attempt in range(1, attempts + 1):
try:
guess = int(input(f"第{attempt}次猜测,请输入数字:"))
if guess < secret_num:
print("猜小了!再试试大一点的数~")
elif guess > secret_num:
print("猜大了!再试试小一点的数~")
else:
print(f"恭喜你!在第{attempt}次猜中了数字{secret_num}!")
return True, attempt
except ValueError:
print("请输入有效的数字!")
print(f"\n很遗憾,机会用完了!正确数字是{secret_num}。")
return False, attempts
def show_scoreboard(total_games, win_games, total_attempts):
"""显示游戏统计"""
if total_games == 0:
print("还没有游戏记录哦~")
return
win_rate = win_games / total_games * 100
avg_attempts = total_attempts / win_games if win_games > 0 else 0
print("=" * 40)
print(" 游戏统计 ")
print(f"总游戏次数:{total_games}")
print(f"获胜次数:{win_games} ({win_rate:.1f}%)")
print(f"平均猜中次数:{avg_attempts:.1f}")
print("=" * 40)
def main():
"""主函数"""
total_games = 0
win_games = 0
total_attempts = 0
show_title()
while True:
max_num, attempts = choose_difficulty()
total_games += 1
is_win, attempt = play_game(max_num, attempts)
if is_win:
win_games += 1
total_attempts += attempt
show_scoreboard(total_games, win_games, total_attempts)
play_again = input("\n想再玩一次吗?(y/n):").lower()
if play_again != 'y':
print("感谢游玩!再见~")
break
print("\n" + "-" * 40 + "\n")
time.sleep(1) # 暂停1秒,提升游戏体验
if name == "main":
main()
浙公网安备 33010602011771号