相信大家在童年或者生活中都玩过石头剪刀布这个游戏,这个游戏需要两个及以上的人。而今天,网上也实现了石头剪刀布的游戏。通过初步学习python,也学会了如何编写这个游戏。
利用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))
在学习的过程中,我们要学会去寻找规律,找到了规律就能让我们的代码变得更剪短,程序的运行速度也会随之提升。