源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python实现的摇骰子猜大小功能小游戏示例

  • 时间:2020-04-14 00:03 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python实现的摇骰子猜大小功能小游戏示例
本文实例讲述了Python实现的摇骰子猜大小功能小游戏。分享给大家供大家参考,具体如下: 最近学习Python的随机数,逻辑判断,循环的用法,就想找一些练习题,比如小游戏猜大小,程序思路如下: [img]http://files.jb51.net/file_images/article/201712/20171218122807736.png?20171118123052[/img] 开发环境: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()

完成这个小游戏之后,你就可以试着和自己设计的程序玩猜大小了。同时你也掌握了循环和条件判断混用的方法,初步具备了设计更复杂的程序的能力了。 [b]PS:这里再提供几款相关工具供大家参考使用:[/b] [b]在线随机生成个人信息数据工具: [/b][url=http://tools.jb51.net/aideddesign/rnd_userinfo]http://tools.jb51.net/aideddesign/rnd_userinfo[/url] [b]在线随机字符/随机密码生成工具: [/b][url=http://tools.jb51.net/aideddesign/rnd_password]http://tools.jb51.net/aideddesign/rnd_password[/url] [b]在线随机数字/字符串生成工具: [/b][url=http://tools.jb51.net/aideddesign/suijishu]http://tools.jb51.net/aideddesign/suijishu[/url] [b]常用电话号码在线查询: [/b][url=http://tools.jb51.net/bianmin/pub_tel]http://tools.jb51.net/bianmin/pub_tel[/url] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/942.htm]Python数学运算技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部