电脑
Python开发工具
由于需要电脑随机出拳,所以我们这里导入随机数模块,具体代码:import random然后用input 代码和用户交互,让用户选择出 剪刀 石头或者布player = input('请输入要出的选项:剪刀(1)/石头(2)/布(3)')
对玩家出拳进行判断,我们这里用 1 代表了 剪刀 2 代表石头 3 代表布 所以我们限制玩家只能出 这三个数字,输入其他字符 则提示玩家出拳错误if player.isdigit() and int(player) >= 1 and int(player) <= 3:else: print('出拳有误')
下面在用户输入正确的情况下 写入判断代码,首先把用户输入的数字转换成整数类型,以及将电脑随机数代码完善player = int(player) cpu = random.randint(1, 3)
然后我们进行胜负条件的判断,我们先写上当用户胜利时候的情况,具体代码如下:if (player == 1 and cpu == 3) \ or (player == 2 and cpu == 1) \ or (player == 3 and cpu == 2): print('玩家胜利')
按照同样的判断方法,判断出电脑胜利和平局的结果:if (player == 1 and cpu == 2) \ or (player == 2 and cpu == 3) \ or (player == 3 and cpu == 1): print('电脑胜利') if (player == 1 and cpu == 1) \ or (player == 2 and cpu == 2) \ or (player == 3 and cpu == 3): print('平局')
经过以上代码,我们基本完成了整个游戏的过程,下面运行一下看效果:
整体代码总结:import random player = input('请输入要出的选项:剪刀(1)/石头(2)/布(3)') if player.isdigit() and int(player) >= 1 and int(player) <= 3: player = int(player) cpu = random.randint(1, 3) if player == 1: player1 = '剪刀' if player == 2: player1 = '石头' if player == 3: player1 = '布' if cpu == 1: cpu1 = '剪刀' if cpu == 2: cpu1 = '石头' if cpu == 3: cpu1 = '布' print('玩家出拳为:', player1, '电脑出拳为:', cpu1) # if (player == 1 and cpu == 3) \ or (player == 2 and cpu == 1) \ or (player == 3 and cpu == 2): print('玩家胜利') if (player == 1 and cpu == 2) \ or (player == 2 and cpu == 3) \ or (player == 3 and cpu == 1): print('电脑胜利') if (player == 1 and cpu == 1) \ or (player == 2 and cpu == 2) \ or (player == 3 and cpu == 3): print('平局') else: print('出拳有误')
Python中所有字符需要是英文格式
if循环中注意tab缩进问题