目录
思路:
玩家出拳只有三种结果:石头、剪刀、布,分别用整数,0,1,2代替
注意:可以用别的数字,但要连续的整数!
电脑出拳结果三种情况不固定,这就要用到python当中的随机函数。
random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。
import random
设置两个参数,player代表玩家,computer代表电脑
player = int(input('请输入猜拳数字0-石头,1-剪刀,2-布:'))
computer = random.randint(0,2)
结果只有三种,玩家获胜,电脑获胜,平局。
根据if...elif....else 我写了一个比较冗长的代码段,如下:
(文末简易版本)
import random
player = int(input('请输入猜拳数字0-石头,1-剪刀,2-布:'))
computer = random.randint(0,2)
#玩家获胜
#电脑获胜
#平局
if player == 0:
print('玩家出石头')
elif computer == 1:
print('电脑出剪刀')
print('玩家获胜!')
elif computer == 2:
print('电脑出布')
print('电脑获胜!')
elif computer == 0:
print('电脑出石头')
print('平局!')
else:
if player == 1:
print('玩家出剪刀')
elif computer == 2:
print('电脑出布')
print('玩家获胜!')
elif computer == 0:
print('电脑出石头')
print('电脑获胜!')
elif computer == 1:
print('电脑出剪刀')
print('平局!')
else:
if player == 2:
print('玩家出布')
elif computer == 0:
print('电脑出石头')
print('玩家获胜!')
elif computer == 1:
print('电脑剪刀')
print('电脑获胜!')
elif computer == 2:
print('电脑出布')
print('平局!')
else:
print('输入错误,请重新输入!')
输入剪刀,看一下随机结果~
优化后的简化版本,如下:
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('电脑获胜,呜呜呜')
还是输入剪刀,看一下随即结果~
优化建议:1.设置窗体页面
2.知道电脑随机出拳的结果
本文仅供参考学习交流,感谢大家的支持~