今日重点:类 + 对象(OOP)
- 支持:开始新游戏 / 查看历史 / 清记录 / 退出 菜单
完整可运行代码(Day7 终阶版)
import random
import time
from datetime import datetime
# ============= 第1步:把整个游戏写成类 =============
classWordGuessGame:
def__init__(self):
# 游戏配置
self.word_lib = {
"简单": ["cat", "dog", "pen", "book", "egg"],
"中等": ["apple", "banana", "grape", "hello", "milk"],
"困难": ["watermelon", "chocolate", "elephant", "umbrella", "computer"]
}
self.score_map = {"简单": 1, "中等": 2, "困难": 3}
self.total_round = 3
self.timeout = 5
self.history = [] # 历史战绩
# 随机取单词(去重)
defget_word(self, used):
all_words = []
for level in self.word_lib:
all_words.extend(self.word_lib[level])
available = [w for w in all_words if w notin used]
ifnot available:
used.clear()
return random.choice(all_words)
return random.choice(available)
# 一轮游戏
defplay_one_round(self):
used_words = []
score = 0
wrongs = []
print("\n==== 新游戏开始 ====")
for i in range(1, self.total_round + 1):
word = self.get_word(used_words)
used_words.append(word)
correct = ''.join(reversed(word))
print(f"\n第{i}题:{word}")
try:
start = time.time()
ans = input("你的答案:").strip().lower()
cost = round(time.time() - start, 1)
except:
ans = ""
cost = 999
# 判断
if cost > self.timeout:
print(f"⏰ 超时!正确:{correct}")
wrongs.append((word, correct, "超时"))
elif ans != correct.lower():
print(f"❌ 错!正确:{correct}")
wrongs.append((word, correct, "答错"))
else:
print("🎉 正确!+1分")
score += 1
# 结束
record = {
"time": datetime.now().strftime("%m-%d %H:%M"),
"score": score,
"total": self.total_round,
"wrongs": wrongs
}
self.history.append(record)
return record
# 显示历史
defshow_history(self):
ifnot self.history:
print("\n暂无记录")
return
print("\n==== 历史战绩 ====")
for idx, h in enumerate(self.history, 1):
print(f"{idx}. {h['time']} | 得分:{h['score']}/{h['total']}")
for w, cor, typ in h["wrongs"]:
print(f" - {w} → {cor} ({typ})")
# 清空历史
defclear_history(self):
self.history.clear()
print("已清空历史")
# ============== 第2步:菜单主程序 ==============
defmain():
game = WordGuessGame()
whileTrue:
print("\n===== 反转猜词游戏(Day7 终阶版)=====")
print("1. 开始游戏")
print("2. 查看历史")
print("3. 清空历史")
print("0. 退出")
choose = input("请选择:").strip()
if choose == "1":
res = game.play_one_round()
print(f"\n最终得分:{res['score']}/{res['total']}")
elif choose == "2":
game.show_history()
elif choose == "3":
game.clear_history()
elif choose == "0":
print("再见!")
break
else:
print("输入错误")
if __name__ == "__main__":
main()
今天你学会了什么(超硬核总结)
- 对象方法:
play_one_round、show_history
明日预告(Day8)
我可以继续带你做 更难的真实项目:
你想明天继续升级这个游戏吗?