1+ import random
2+
3+ def guess_number_game ():
4+ """
5+ 猜数字游戏
6+ 随机生成1-100的整数,玩家猜测直到猜对为止
7+ """
8+ # 生成随机数
9+ secret_number = random .randint (1 , 100 )
10+ attempts = 0
11+ guess_history = [] # 记录猜测历史
12+
13+ print ("🎮 欢迎来到猜数字游戏!" )
14+ print ("我已经想好了一个1到100之间的整数。" )
15+ print ("试着猜猜看是多少吧!" )
16+ print ("提示:输入 'q' 可以退出游戏" )
17+ print ("-" * 40 )
18+
19+ while True :
20+ try :
21+ # 获取玩家输入
22+ guess_input = input (f"第{ attempts + 1 } 次猜测(1-100):" )
23+
24+ # 检查是否要退出
25+ if guess_input .lower () in ['q' , 'quit' , 'exit' , '退出' ]:
26+ print (f"\n 👋 游戏已退出。正确答案是 { secret_number } " )
27+ print (f"你猜了 { attempts } 次,猜测历史:{ guess_history } " )
28+ return False
29+
30+ guess = int (guess_input )
31+
32+ # 验证输入范围
33+ if guess < 1 or guess > 100 :
34+ print ("⚠️ 请输入1到100之间的数字!" )
35+ continue
36+
37+ attempts += 1
38+ guess_history .append (guess )
39+
40+ # 判断猜测结果
41+ if guess < secret_number :
42+ print ("🔽 小了!再试试看。" )
43+ elif guess > secret_number :
44+ print ("🔼 大了!再试试看。" )
45+ else :
46+ print (f"\n 🎉 恭喜你!猜对了!" )
47+ print (f"🎯 正确答案是:{ secret_number } " )
48+ print (f"📊 你总共猜了 { attempts } 次" )
49+ print (f"📝 猜测历史:{ guess_history } " )
50+
51+ # 根据尝试次数给出评价
52+ if attempts == 1 :
53+ print ("🌟 太厉害了!一次就猜中!" )
54+ elif attempts <= 5 :
55+ print ("👍 很棒!只用了很少的次数!" )
56+ elif attempts <= 10 :
57+ print ("👌 不错!表现很好!" )
58+ else :
59+ print ("💪 继续努力,下次会更好!" )
60+
61+ return True
62+
63+ except ValueError :
64+ print ("❌ 请输入有效的数字!或者输入 q 退出游戏" )
65+ except KeyboardInterrupt :
66+ print ("\n \n 👋 游戏已退出。" )
67+ return False
68+
69+ def show_instructions ():
70+ """显示游戏说明"""
71+ print ("\n 📖 游戏说明:" )
72+ print ("1. 我会随机生成一个1-100之间的整数" )
73+ print ("2. 你需要猜测这个数字是多少" )
74+ print ("3. 每次猜测后,我会告诉你'大了'或'小了'" )
75+ print ("4. 继续猜测直到猜对为止" )
76+ print ("5. 游戏会记录你猜的次数" )
77+ print ("6. 输入 'q' 可以随时退出游戏" )
78+ print ("-" * 40 )
79+
80+ def main ():
81+ """主函数,控制游戏流程"""
82+ print ("=" * 50 )
83+ print (" 猜数字游戏 v1.0" )
84+ print ("=" * 50 )
85+
86+ show_instructions ()
87+
88+ total_games = 0
89+ total_attempts = 0
90+ best_score = float ('inf' ) # 最佳成绩(最少尝试次数)
91+
92+ while True :
93+ total_games += 1
94+ print (f"\n 🎲 第 { total_games } 局游戏开始!" )
95+
96+ # 玩一局游戏
97+ game_completed = guess_number_game ()
98+
99+ # 询问是否再玩一次
100+ print ("\n " + "=" * 40 )
101+ play_again = input ("想再玩一次吗?(y/n): " ).lower ()
102+
103+ if play_again not in ['y' , 'yes' , '是' , '好的' ]:
104+ # 显示统计信息
105+ print ("\n 📈 游戏统计:" )
106+ print (f" 总游戏局数:{ total_games } " )
107+ if total_games > 0 and total_attempts > 0 :
108+ print (f" 平均尝试次数:{ total_attempts / total_games :.1f} " )
109+ if best_score < float ('inf' ):
110+ print (f" 最佳成绩:{ best_score } 次" )
111+ print ("\n 谢谢游玩!再见!👋" )
112+ break
113+ print ("\n " + "=" * 40 )
114+
115+ if __name__ == "__main__" :
116+ main ()
0 commit comments