p y t hon猜拳小游戏,用if…elif语句,使用randint()函数产生电脑随机数(0、1、2),定义两个变量,分别保存用户和电脑的出拳
时间: 2024-05-06 16:17:29 浏览: 17
好的,以下是代码实现:
```python
import random
options = ['石头', '剪刀', '布'] # 定义出拳选项
computer_choice = random.randint(0, 2) # 随机生成电脑出拳
user_choice = int(input('请出拳:0-石头,1-剪刀,2-布\n')) # 获取用户出拳
# 判断胜负
if user_choice == computer_choice:
print('平局')
elif user_choice == 0 and computer_choice == 1:
print('你赢了')
elif user_choice == 1 and computer_choice == 2:
print('你赢了')
elif user_choice == 2 and computer_choice == 0:
print('你赢了')
else:
print('电脑赢了')
print('你出了%s,电脑出了%s' % (options[user_choice], options[computer_choice])) # 显示出拳结果
```
运行结果如下:
```
请出拳:0-石头,1-剪刀,2-布
1
电脑赢了
你出了剪刀,电脑出了布
```
相关问题
p y t hon猜拳小游戏,用if…elif语句,使用randint()函数产生电脑随机数(0、1、2)
好的,下面是一个简单的Python猜拳小游戏:
```python
import random
print("猜拳游戏开始!")
print("请出拳:0-石头,1-剪刀,2-布")
player = int(input("请出拳:"))
computer = random.randint(0, 2)
if player == computer:
print("平局,再来一局!")
elif player == 0 and computer == 1 or player == 1 and computer == 2 or player == 2 and computer == 0:
print("恭喜你,你赢了!")
else:
print("很遗憾,你输了!")
print("电脑出的是:" + str(computer))
```
运行结果:
```
猜拳游戏开始!
请出拳:0-石头,1-剪刀,2-布
请出拳:1
很遗憾,你输了!
电脑出的是:0
```
注意,上述代码中,使用了`random`库中的`randint()`函数来产生随机数,`input()`函数用于获取用户输入。`if...elif`语句用于根据用户和电脑的出拳情况判断胜负。最后,将电脑的出拳结果输出。
p y t hon猜拳小游戏
好的,下面是一个简单的 Python 猜拳小游戏:
```python
import random
print("猜拳游戏:")
while True:
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("输入错误,请重新输入!")
print("继续游戏?(y/n)")
if input() == "n":
break
```
这个程序使用了 while 循环来持续让玩家进行游戏,直到玩家选择退出。玩家可以输入 1、2 或 3 来选择石头、剪刀或布,电脑则使用 random 模块随机选择一个数字代表出什么拳。最后根据玩家和电脑的选择输出结果,再询问是否继续游戏。