您现在的位置是:群英 > 开发技术 > Python语言
用python怎样实现简单的石头剪刀布小游戏?
Admin发表于 2021-11-23 17:41:431376 次浏览

    石头剪刀布的小游戏相信大家都有玩过吧,这篇文章我们来了解如何用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))

    效果演示图如下:

    关于用python实现简单的石头剪刀布小游戏就介绍到这,本文代码仅供参考,感兴趣的朋友可以了解看看,希望能对大家有帮助,想要了解更多大家可以关注其它的相关文章。

文本转载自脚本之家

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

相关信息推荐
2022-12-01 16:14:37 
摘要:php查询字段有无的实现方法:1、创建一个php示例文件;2、连接数据库;3、通过“select * from”语句查询某值;4、使用“if (!mysql_num_rows($result)){...}else{...}”语句判断该值是否存在即可。
2022-01-26 18:39:53 
摘要:Java的几种运算符基本用法是什么?在Java中,常用的运算符有算术运算符、赋值运算符、比较运算符、逻辑运算符和条件运算符等等这些,文中简单的介绍了它们的使用,及优先级,感谢兴趣的朋友就继续往下看吧。
2022-04-29 15:26:41 
摘要:python文件的后缀名有:“.py”、“.py3”、“.pyc”、“.pyo”、“.pyd”、“.pyi”、“.pyx”、“.pyz”、“.pywz”、“.rpy”、“.pyde”、“.pyp”、“.pyt”。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部