python面向对象人机猜拳
时间: 2023-05-20 14:03:22 浏览: 198
面向对象之人机猜拳
5星 · 资源好评率100%
可以使用类来实现人机猜拳游戏,其中人类玩家和机器玩家都是对象,可以定义一个Game类来管理游戏的流程和逻辑。以下是一个简单的示例代码:
```python
import random
class Player:
def __init__(self, name):
self.name = name
self.score = 0
self.choice = None
def choose(self):
self.choice = input(f"{self.name}, 请出拳(石头/剪刀/布): ")
def random_choose(self):
self.choice = random.choice(["石头", "剪刀", "布"])
def __str__(self):
return f"{self.name}({self.score}分): {self.choice}"
class Game:
def __init__(self):
self.player = Player("你")
self.computer = Player("电脑")
def start(self):
print("欢迎来到人机猜拳游戏!")
while True:
self.player.choose()
self.computer.random_choose()
print(self.player)
print(self.computer)
result = self.compare(self.player.choice, self.computer.choice)
if result == 1:
print("你赢了!")
self.player.score += 1
elif result == -1:
print("电脑赢了!")
self.computer.score += 1
else:
print("平局!")
print(f"当前得分:你({self.player.score}分) vs 电脑({self.computer.score}分)")
if self.is_game_over():
break
print("游戏结束!")
def compare(self, choice1, choice2):
if choice1 == choice2:
return 0
elif choice1 == "石头" and choice2 == "剪刀" or \
choice1 == "剪刀" and choice2 == "布" or \
choice1 == "布" and choice2 == "石头":
return 1
else:
return -1
def is_game_over(self):
if self.player.score >= 3:
print("你赢了游戏!")
return True
elif self.computer.score >= 3:
print("电脑赢了游戏!")
return True
else:
return False
if __name__ == "__main__":
game = Game()
game.start()
```
这个程序实现了一个简单的人机猜拳游戏,玩家可以通过输入石头/剪刀/布来出拳,电脑则随机出拳。游戏进行到某一方得分达到3分时结束,得分高的一方获胜。
阅读全文