python面向对象猜拳游戏
时间: 2023-10-28 11:01:26 浏览: 110
好的,这是一个简单的Python面向对象猜拳游戏示例:
```python
import random
class Player:
def __init__(self, name):
self.name = name
self.score = 0
def choose_gesture(self):
pass
class Human(Player):
def choose_gesture(self):
gesture = input("Choose your gesture (rock/paper/scissors/lizard/spock): ").lower()
while gesture not in ['rock', 'paper', 'scissors', 'lizard', 'spock']:
gesture = input("Invalid gesture. Choose again (rock/paper/scissors/lizard/spock): ").lower()
return gesture
class Computer(Player):
def choose_gesture(self):
return random.choice(['rock', 'paper', 'scissors', 'lizard', 'spock'])
class Game:
def __init__(self):
self.player1 = Human("You")
self.player2 = Computer("Computer")
def determine_winner(self, gesture1, gesture2):
if gesture1 == gesture2:
print("Tie!")
elif (gesture1 == 'rock' and gesture2 in ['scissors', 'lizard']) or \
(gesture1 == 'paper' and gesture2 in ['rock', 'spock']) or \
(gesture1 == 'scissors' and gesture2 in ['paper', 'lizard']) or \
(gesture1 == 'lizard' and gesture2 in ['paper', 'spock']) or \
(gesture1 == 'spock' and gesture2 in ['rock', 'scissors']):
self.player1.score += 1
print(f"{self.player1.name} wins!")
else:
self.player2.score += 1
print(f"{self.player2.name} wins!")
def play_game(self):
print("Let's play Rock-Paper-Scissors-Lizard-Spock!")
while True:
gesture1 = self.player1.choose_gesture()
gesture2 = self.player2.choose_gesture()
print(f"{self.player1.name} chooses {gesture1}")
print(f"{self.player2.name} chooses {gesture2}")
self.determine_winner(gesture1, gesture2)
print(f"{self.player1.name}: {self.player1.score} - {self.player2.name}: {self.player2.score}")
play_again = input("Play again? (y/n): ").lower()
if play_again != 'y':
break
print("Thanks for playing!")
if __name__ == '__main__':
game = Game()
game.play_game()
```
该游戏使用了三个类:`Player`,`Human`和`Computer`。`Player`类是一个基类,它定义了一个玩家应该具有的属性和方法,例如`name`和`score`属性,以及`choose_gesture()`方法。`Human`和`Computer`类都继承自`Player`类,并实现了`choose_gesture()`方法。
`Game`类用于实现游戏机制,包括决定胜者和打印分数等。`play_game()`方法是游戏的主要逻辑,其中包括循环直到玩家退出游戏。
您可以通过运行此代码来尝试游戏。
阅读全文