栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实现简单的石头剪刀布游戏

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python实现简单的石头剪刀布游戏

相信大家在童年或者生活中都玩过石头剪刀布这个游戏,这个游戏需要两个及以上的人。而今天,网上也实现了石头剪刀布的游戏。通过初步学习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))

效果演示图如下:

总结

在学习的过程中,我们要学会去寻找规律,找到了规律就能让我们的代码变得更剪短,程序的运行速度也会随之提升。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339011.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号