likes
comments
collection
share

Python基础(七)

作者站长头像
站长
· 阅读数 3

前面我们已经学习了逻辑判断和循环的用法,也提及了一下猜字游戏,现在我们试着完善一下上一次提及的猜数字小游戏。

在澳门赌场有个经久不衰的游戏,就是买大小,我们来试着写一下这里面的逻辑。买小时,点数是3<=总值<=10,大则是11<=总值<=18。

首先,我们要构建一个摇骰子的函数,roll_dice。

import random

def roll_dice(numbers=3,points=None):
    print('请开始摇骰子!')
    if points is None:
        points = []
    while numbers > 0:
        point = random.randrange(1,7)
        points.append(point)
        numbers = numbers -1
     return points

请看下图,我在循环结束用了print,而不是return,是因为用return不会显示出points里面的内容。

Python基础(七)

有了三个点数,接下来我们就要判断这三个数加起来的大小了。我们要用到if语句来定义大小:


def roll_result(total):
    big = 11 <= total <= 18
    small = 3 <= total <= 10
    if big:
        return 'Big'
    elif small:
        return 'Small'

有了大小的判断规则,现在就要设计一个开始游戏的函数,让用户猜大小,并输出猜测结果的对错。我们将用户猜测的结果存到your_choices中,然后调用roll_dice函数,并将返回值命名为points,在执行求和,调用判断大小函数roll_result,最后设定胜利条件即可。

def game():
    print("猜大小游戏开始!")
    choices = ['Big','Small']
    your_choices = input('Please enter Big or Small :')
    if your_choices in choices:
        points = roll_dice()
        total = sum(points)
        win = your_choices == roll_result(total)
        if win:
            print('you win',points)
        else:
            print('you lose',points)
    else:
        print("输错啦,请输入Big or Small:")
        game()
game()


我们看看完整的代码执行效果是怎样的:

Python基础(七)

我们运用了循环和判断混用的方法来设计这个小游戏。还有就是里面用到的sum函数,我没有过多的解释,这是python的内置函数,它可以将列表求和并返回结果。例如

list = [1,2,3]
print(sum(list))

输出结果如下:

Python基础(七)

转载自:https://juejin.cn/post/7059400682717069319
评论
请登录