python人机猜拳
时间: 2023-11-19 14:57:48 浏览: 394
以下是一个简单的Python人机猜拳游戏的例子:
```python
import random
player = int(input('请输入猜拳数字0-石头,1-剪刀,2-布:'))
computer = random.randint(0,2)
if player == 0 and computer == 1 or player == 1 and computer == 2 or player == 2 and computer == 0:
print('玩家获胜,哈哈哈')
elif player == 0 and computer == 0 or player == 1 and computer == 1 or player == 2 and computer == 2:
print('平局,别走!再来一局!')
else:
print('电脑获胜,呜呜呜')
```
在这个例子中,我们使用了Python内置的`random`模块来生成电脑的随机选择。玩家需要输入一个数字来代表他们的选择,然后程序会根据玩家和电脑的选择来判断胜负并输出结果。
相关问题
python人机猜拳游戏
好的,我可以帮你写一个Python人机猜拳游戏。
以下是代码:
```python
import random
def get_hand():
"""获取手势"""
while True:
hand = input("请输入你的手势(0-石头,1-剪刀,2-布):")
if hand.isdigit() and int(hand) in [0, 1, 2]:
return int(hand)
else:
print("无效的手势,请重新输入!")
while True:
# 人出手势
player_hand = get_hand()
# 机器出手势
com_hand = random.randint(0, 2)
# 输出结果
print("你出了%s,机器出了%s。" %(["石头", "剪刀", "布"][player_hand], ["石头", "剪刀", "布"][com_hand]))
# 判断胜负
if player_hand == com_hand:
print("平局!")
elif player_hand == 0 and com_hand == 1 or player_hand == 1 and com_hand == 2 or player_hand == 2 and com_hand == 0:
print("你赢了!")
else:
print("机器赢了!")
# 询问是否继续
answer = input("是否继续(Y/N):")
if answer.lower() != "y":
break
```
这个游戏是一个简单的人机对战,玩家输入石头、剪刀、布中的一个手势,机器随机选择一个手势,然后判断胜负。玩家可以选择是否继续游戏。
python人机猜拳代码
以下是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()
```
阅读全文