一、人机猜拳游戏
1. 核心功能
2. 案例实现
from abc import ABC, abstractmethod
import random
class Gesture:
"""手势类(组合关系核心组件)"""
RELATIONS = {
'石头': ['剪刀'],
'剪刀': ['布'],
'布': ['石头']
}
def __init__(self, gesture: str):
if gesture not in self.RELATIONS:
raise ValueError("无效手势")
self.gesture = gesture
def beats(self, other):
"""判断当前手势是否击败另一个手势"""
return other.gesture in self.RELATIONS[self.gesture]
class Player(ABC):
"""定义抽象类,玩家基类(继承体系核心)"""
def __init__(self, name):
self.name = name
self.gesture = None
@abstractmethod
def choose_gesture(self):
"""抽象方法:子类必须实现手势选择逻辑"""
pass
class HumanPlayer(Player):
"""人类玩家子类"""
def choose_gesture(self):
while True:
choice = input(f"{self.name}请选择手势({'/'.join(Gesture.RELATIONS.keys())}): ").strip()
if choice in Gesture.RELATIONS:
self.gesture = Gesture(choice)
return
print("无效输入,请重新选择!")
class ComputerPlayer(Player):
"""电脑玩家子类"""
def choose_gesture(self):
choice = random.choice(list(Gesture.RELATIONS.keys()))
self.gesture = Gesture(choice)
print(f"{self.name}选择了:{choice}")
class Game:
"""游戏控制类"""
def __init__(self, rounds=3):
self.human = HumanPlayer("人类玩家")
self.computer = ComputerPlayer("电脑AI")
self.rounds = rounds
self.scores = {'human': 0, 'computer': 0}
def judge_round(self):
"""单局胜负判断, 这里的逻辑是设计很开放,这里只是其中一种思路"""
if self.human.gesture.beats(self.computer.gesture):
self.scores['human'] += 1
return "玩家胜"
elif self.computer.gesture.beats(self.human.gesture):
self.scores['computer'] += 1
return "电脑胜"
return "平局"
def start(self):
"""游戏主流程"""
print(f"=== 猜拳游戏开始({self.rounds}局制) ===")
for i in range(self.rounds):
print(f"\n第{i + 1}局:")
self.human.choose_gesture()
self.computer.choose_gesture()
result = self.judge_round()
print(f"结果:{result} | 当前比分 {self.scores['human']}:{self.scores['computer']}")
print("\n=== 最终结果 ===")
if self.scores['human'] > self.scores['computer']:
print("🎉 玩家获得最终胜利!")
elif self.scores['computer'] > self.scores['human']:
print("🤖 电脑获得最终胜利!")
else:
print("⚖️ 双方战平!")
if __name__ == "__main__":
game = Game(rounds=3)
game.start()
3. 试玩结果
=== 猜拳游戏开始(3局制) ===
第1局:
人类玩家请选择手势(石头/剪刀/布): 布
电脑AI选择了:布
结果:平局 | 当前比分 0:0
第2局:
人类玩家请选择手势(石头/剪刀/布): 剪刀
电脑AI选择了:布
结果:玩家胜 | 当前比分 1:0
第3局:
人类玩家请选择手势(石头/剪刀/布): 剪刀
电脑AI选择了:剪刀
结果:平局 | 当前比分 1:0
=== 最终结果 ===
🎉 玩家获得最终胜利!
二、代码解析(结合OOP知识点):
- 继承体系设计
Player
抽象基类定义玩家共性(名称、手势属性)HumanPlayer/ComputerPlayer
子类继承并实现差异化逻辑:
def choose_gesture(self):
def choose_gesture(self):
random.choice(...)
- 多态性实现
- 抽象方法
choose_gesture()
强制子类实现不同行为 - 运行时根据对象类型动态调用方法:
players = [HumanPlayer(), ComputerPlayer()]
for p in players:
p.choose_gesture()
- 组合关系应用
Gesture
类独立封装手势规则Player
类通过gesture
属性组合Gesture
实例:
class Player:
def __init__(self):
self.gesture = None
- 胜负判断逻辑
手势关系存储在Gesture类中,实现高内聚,后续扩展的时候秩序增加手势关系即可:
RELATIONS = {
'石头': ['剪刀'],
'剪刀': ['布'],
'布': ['石头']
}
def beats(self, other):
return other.name in self.RELATIONS[self.name]