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()

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

posted on 2017-03-04 07:49  whaben  阅读(3828)  评论(0编辑  收藏  举报

导航