人机猜拳游戏代码python用类和多态来写
时间: 2024-12-22 12:24:35 浏览: 0
在Python中,我们可以使用类和多态来创建一个简单的人机猜拳游戏。首先,我们定义一个基本的`Game`类,然后为石头、剪刀、布三种情况分别创建子类,如`Rock`, `Scissors`, 和 `Paper`。每个子类都覆盖一个`play`方法,表示它们各自的猜测。这里是一个简单的示例:
```python
class Game:
def play(self):
raise NotImplementedError("子类需要实现这个方法")
class Player:
def __init__(self, choice):
self.choice = choice
class Rock(Player):
def play(self):
return "石头"
class Scissors(Player):
def play(self):
return "剪刀"
class Paper(Player):
def play(self):
return "布"
def guess_game():
player_choice = input("请输入你的选择(石头、剪刀、布):")
game = {
'石头': Rock,
'剪刀': Scissors,
'布': Paper
}.get(player_choice, None)
if not game:
print("无效的选择,请重新输入。")
return
computer_choice = game().play()
result = compare_choices(player_choice, computer_choice)
print(f"你选择了{player_choice},电脑选择了{computer_choice},结果是:{result}")
def compare_choices(player, computer):
if player == computer:
return "平局"
elif (player == '石头' and computer == '剪刀') or \
(player == '剪刀' and computer == '布') or \
(player == '布' and computer == '石头'):
return "你赢了!"
else:
return "电脑赢了!"
guess_game()
```
在这个代码中,当你运行`guess_game()`函数时,它会提示用户输入他们的选择,并根据玩家输入动态地调用相应子类的`play`方法。这就是多态的应用,因为`Game`类的实例可以根据用户的输入变成`Rock`, `Scissors`, 或 `Paper`的具体实例。
阅读全文