编写代码实现剪刀、石头、布的猜拳游戏:玩家输入1、2、3 表示剪刀、石头、布,程序随机产生1、2、3与玩家比较,并输出输赢结果。
时间: 2023-08-20 21:04:17 浏览: 88
好的,以下是实现剪刀石头布游戏的Python 代码:
```python
import random
print("欢迎来到剪刀石头布游戏!")
print("请出拳:1表示剪刀,2表示石头,3表示布")
player = int(input("请出拳:"))
computer = random.randint(1, 3)
print("你出的是:%d" % player)
print("电脑出的是:%d" % computer)
if ((player == 1 and computer == 3) or
(player == 2 and computer == 1) or
(player == 3 and computer == 2)):
print("恭喜你,你赢了!")
elif player == computer:
print("平局!")
else:
print("很遗憾,你输了!")
```
代码解释:
首先,利用 Python 的 `random` 模块随机产生电脑出的拳,然后获取玩家输入的拳,最后根据玩家和电脑出的拳比较输赢,并输出结果。
如果玩家出的是剪刀,电脑出的是布,或者玩家出的是石头,电脑出的是剪刀,或者玩家出的是布,电脑出的是石头,那么玩家获胜。如果玩家和电脑出的拳一样,那么是平局。否则,玩家输了。
相关问题
编写代码实现剪刀、石头、布的猜拳游戏:玩家输入1、2、3 表示剪刀、石头、布,程序随机产生1、2、3与玩家比较,并输出输赢结果。
好的,以下是Python语言的代码实现:
```python
import random
def game(player):
computer = random.randint(1, 3)
if player == computer:
return "平局"
elif player == 1 and computer == 2:
return "你输了,电脑出了石头"
elif player == 1 and computer == 3:
return "你赢了,电脑出了布"
elif player == 2 and computer == 1:
return "你赢了,电脑出了剪刀"
elif player == 2 and computer == 3:
return "你输了,电脑出了布"
elif player == 3 and computer == 1:
return "你输了,电脑出了剪刀"
elif player == 3 and computer == 2:
return "你赢了,电脑出了石头"
player = int(input("请输入剪刀(1)、石头(2)或布(3):"))
result = game(player)
print(result)
```
该程序首先导入了Python的random模块,用于产生随机数。然后定义了一个名为game的函数,该函数的输入参数是玩家出的手势,返回值是比赛结果。在函数内部,程序使用随机数产生了电脑出的手势,然后根据玩家和电脑的手势比较,输出不同的结果。最后,程序让玩家输入手势,调用game函数,并输出比赛结果。
编写python代码实现剪刀、石头、布的猜拳游戏:玩家输入1、2、3 表示剪刀、石头、布,程序随机产生1、2、3与玩家比较,并输出输赢结果
好的,我来为您编写这个程序。
```python
import random
print("欢迎来到剪刀石头布游戏!")
print("请输入 1 表示剪刀,2 表示石头,3 表示布")
player = int(input("请出拳:"))
computer = random.randint(1, 3)
if player == 1:
if computer == 1:
print("电脑出剪刀,平局!")
elif computer == 2:
print("电脑出石头,你输了!")
else:
print("电脑出布,你赢了!")
elif player == 2:
if computer == 1:
print("电脑出剪刀,你赢了!")
elif computer == 2:
print("电脑出石头,平局!")
else:
print("电脑出布,你输了!")
elif player == 3:
if computer == 1:
print("电脑出剪刀,你输了!")
elif computer == 2:
print("电脑出石头,你赢了!")
else:
print("电脑出布,平局!")
else:
print("输入有误,请重新输入!")
```
运行该程序后,用户输入 1、2、3 分别代表剪刀、石头、布,程序随机产生 1、2、3 与用户比较,输出输赢结果。
注意:该程序只是一个简单的猜拳游戏,程序逻辑并不复杂,可以作为初学者的练习项目。