python人机猜拳代码
时间: 2024-06-11 13:02:38 浏览: 9
以下是Python实现人机猜拳游戏的代码:
```python
import random
# 玩家类
class Player:
def __init__(self, name):
self.name = name
self.guess = 0
self.win = 0
def show(self):
print(self.name, end=' ')
if self.guess == 1:
print('石头', end=' ')
elif self.guess == 2:
print('剪刀', end=' ')
else:
print('布', end=' ')
print(str(self.win)+'胜')
def finger_guess(self):
print('请出拳:')
print('1.石头 2.剪刀 3.布')
self.guess = int(input('请输入数字:'))
# 电脑类
class Computer:
def __init__(self, name):
self.name = name
self.guess = 0
self.win = 0
def show(self):
print(self.name, end=' ')
if self.guess == 1:
print('石头', end=' ')
elif self.guess == 2:
print('剪刀', end=' ')
else:
print('布', end=' ')
print(str(self.win)+'胜')
def finger_guess(self):
self.guess = random.randint(1, 3)
# 猜拳游戏类
class FingerGuessGame:
def __init__(self, player, computer):
self.player = player
self.computer = computer
def play(self):
self.player.finger_guess()
self.computer.finger_guess()
if (self.player.guess == 1 and self.computer.guess == 2) or \
(self.player.guess == 2 and self.computer.guess == 3) or \
(self.player.guess == 3 and self.computer.guess == 1):
self.player.win += 1
print(self.player.name+'赢了')
elif (self.player.guess == 1 and self.computer.guess == 3) or \
(self.player.guess == 2 and self.computer.guess == 1) or \
(self.player.guess == 3 and self.computer.guess == 2):
self.computer.win += 1
print(self.computer.name+'赢了')
else:
print('平局')
self.player.show()
self.computer.show()
# 创建玩家和电脑
player = Player('玩家')
computer = Computer('电脑')
# 创建猜拳游戏
game = FingerGuessGame(player, computer)
# 进行猜拳游戏
for i in range(5):
print('第'+str(i+1)+'局:')
game.play()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)