Python实现的摇骰子猜大小功能小游戏示例
作者:whaben 时间:2022-04-08 13:26:28
本文实例讲述了Python实现的摇骰子猜大小功能小游戏。分享给大家供大家参考,具体如下:
最近学习Python的随机数,逻辑判断,循环的用法,就想找一些练习题,比如小游戏猜大小,程序思路如下:
开发环境:python2.7 , 附上源代码如下:
摇骰子的函数,这个函数其实并不需要传任何参数,调用后会返回三个点数结果的列表。
import random
def roll_dice(numbers=3,points=None):
print ('<<<<< ROLL THE DICE! >>>>>')
if points is None:
points = []
while numbers > 0:
point = random.randint(1,6)
points.append(point)
numbers = numbers-1
return points
接着再用一个函数来将点数转化成大小
def roll_result(total):
isBig = 11 <=total <= 18
isSmall = 3 <= total <= 10
if isBig:
return 'Big'
elif isSmall:
return 'Small'
最后,创建一个开始游戏的函数,让用户输入猜大小,并且定义什么是猜对,什么是猜错,并输出对应的输赢结果。
def start_game():
print ('<<<<< GAME STARTS! >>>>>')
choices=['Big','Small']
your_choice=raw_input('Big or Small')
if your_choice in choices:
points = roll_dice()
total = sum(points)
youWin = your_choice == roll_result(total)
if youWin:
print('The points are',points,'You win !')
else:
print('The points are',points,'You lose !')
else:
print('Invalid Words')
start_game()
start_game()
完成这个小游戏之后,你就可以试着和自己设计的程序玩猜大小了。同时你也掌握了循环和条件判断混用的方法,初步具备了设计更复杂的程序的能力了。
PS:这里再提供几款相关工具供大家参考使用:
在线随机生成个人信息数据工具:
http://tools.jb51.net/aideddesign/rnd_userinfo
在线随机字符/随机密码生成工具:
http://tools.jb51.net/aideddesign/rnd_password
在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
常用电话号码在线查询:
http://tools.jb51.net/bianmin/pub_tel
希望本文所述对大家Python程序设计有所帮助。
来源:http://www.cnblogs.com/whaben/p/6500228.html
标签:Python,小游戏
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
sqlserver 触发器实例代码
2012-01-29 18:30:45
python实现库存商品管理系统
2023-06-01 06:37:29
![](https://img.aspxhome.com/file/2023/7/80597_0s.jpg)
在Python中使用CasperJS获取JS渲染生成的HTML内容的教程
2021-07-01 14:41:42
python学习笔记--将python源文件打包成exe文件(pyinstaller)
2021-04-17 22:03:22
PyTorch使用GPU训练的两种方法实例
2023-09-21 08:11:40
![](https://img.aspxhome.com/file/2023/9/85309_0s.png)
windows下python 3.9 Numpy scipy和matlabplot的安装教程详解
2021-12-20 13:20:47
![](https://img.aspxhome.com/file/2023/5/117845_0s.png)
利用Python将图片中扭曲矩形的复原
2022-05-24 21:35:54
![](https://img.aspxhome.com/file/2023/3/95233_0s.jpg)
Python破解网站登录密码脚本
2022-09-29 23:21:38
![](https://img.aspxhome.com/file/2023/8/93458_0s.png)
巧用JDBC实现对MySQL的“增删改查”
2008-12-31 15:12:00
先学会为自己做设计
2008-06-01 16:32:00
python三元运算符实现方法
2022-08-19 23:11:34
教你用Python读取CSV文件的5种方式
2022-12-11 15:32:51
![](https://img.aspxhome.com/file/2023/1/75331_0s.png)
python 查找文件名包含指定字符串的方法
2021-05-03 08:54:21
![](https://img.aspxhome.com/file/2023/5/127815_0s.jpg)
asp如何验证日期输入是否正确?
2010-06-10 18:38:00
用Python做一个哔站小姐姐词云跳舞视频
2022-09-17 12:32:30
![](https://img.aspxhome.com/file/2023/1/72761_0s.jpg)
PyInstaller将Python文件打包为exe后如何反编译(破解源码)以及防止反编译
2021-03-17 16:31:22
![](https://img.aspxhome.com/file/2023/6/120406_0s.jpg)
oracle中的视图详解
2009-12-22 11:48:00
SQL语句执行顺序图文介绍
2023-07-04 22:59:27
![](https://img.aspxhome.com/file/UploadPic/201211/30/20121130203549375s.png)
sql server 锁表语句分享
2012-02-12 15:49:20
在ASP中如何使用类class
2007-09-16 17:17:00