zoukankan      html  css  js  c++  java
  • 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()

    完成这个小游戏之后,你就可以试着和自己设计的程序玩猜大小了。同时你也掌握了循环和条件判断混用的方法,初步具备了设计更复杂的程序的能力了。

  • 相关阅读:
    2020/10/23-大族激光
    Windows权限维持总结
    了解蓝军--jsonhijack漏洞学习
    white-space、word-break、word-wrap傻傻分不清楚
    Vue其他指令(v-cloak和v-text,v-html,v-pre,v-once)
    Vue循环渲染(v-for)
    Vue条件渲染(v-if)
    Vue绑定事件监听器(v-on)
    Vue绑定数据和元素属性(v-bind)
    记录一下,破解idea
  • 原文地址:https://www.cnblogs.com/whaben/p/6500228.html
Copyright © 2011-2022 走看看