一聚教程网:一个值得你收藏的教程网站

热门教程

python实现简单石头剪刀布游戏代码示例

时间:2022-06-25 01:38:42 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下python实现简单石头剪刀布游戏代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

思路:

假设剪刀(0),石头(1),布(2),那么如何才能获胜呢?

那么根据这个表格可以初步写出代码:

if user == 0 and computer == 0:
 print("平局")
elif user == 0 and computer == 1:
 print("玩家胜")
elif user == 0 and computer == 2:
 print("电脑胜")
elif user == 1 and computer == 0:
 print("电脑获胜")
elif user == 1 and computer == 1:
 print("平局")
elif user == 1 and computer == 2:
 print("玩家胜")
elif user == 2 and computer == 0:
 print("玩家胜")
elif user == 2 and computer == 1:
 print("电脑胜")
elif user == 2 and computer == 2:
 print("平局")

当我们写完这串代码,我们不难发现,这样写代码太麻烦了,谁都怕麻烦,所以,我们可以根据这之中的规律写出更短的代码。

根据上表,我们可以很轻松的发现规律:

1.if user-computer == -2 or user-computer == 1 时,是玩家胜出
2.if user-computer == -1 or user-computer == 2 时,是电脑胜出
3.if user-computer == 0 时,是平局

那么精简后的部分代码如下:

if user == computer:
 print("玩家是%s,电脑是%s,平局"%(usr,com))
elif user - computer == -1 or user - computer == 2:
 print("玩家是%s,电脑是%s,玩家输"%(usr,com))
else:
 print("玩家是%s,电脑是%s,玩家胜"%(usr,com))

因为电脑是随机的,我们并不知道,所以需要调用random。完整的代码如下:

import random
computer = random.randint(0,2)
user = int(input("剪刀(0),石头(1),布(2):"))
#判断电脑出的是石头,剪刀,还是布
if computer == 0:
 com = "剪刀"
elif computer == 1:
 com = "石头"
else:
 com = "布" 
#判断玩家出的石头,剪刀,还是布
if user == 0:
 usr = "剪刀"
elif user == 1:
 usr = "石头"
else:
 usr = "布"
#结果并输出
if user == computer:
 print("玩家是%s,电脑是%s,平局"%(usr,com))
elif user - computer == -1 or user - computer == 2:
 print("玩家是%s,电脑是%s,玩家输"%(usr,com))
else:
  print("玩家是%s,电脑是%s,玩家胜"%(usr,com))

效果演示图如下:

热门栏目