import random
"""
构造可以摇骰子的函数roll_dice,这个函数其实并不需要输入任何参数,调用后会返回储存着摇出来三个点数结果的列表
创建函数,设定两个默认参数作为可选,numbers—骰子数量,points—三个筛子的点数的列表
"""
def roll_dice (numbers = 3,points = None):
"""告知用户开始摇骰子"""
print('*****PLAY THE DICE*****')
# """如果参数中并未指定points,那么为points创建空的列表"""
if points is None:
points = []
"""要三次骰子,每摇一次numbers就减1,直至小于等于0时,循环停止"""
while numbers > 0:
point = random.randrange(1,7)
points.append(point)
numbers = numbers -1
return points
"""
我们再用一个函数来将点数转化成大小,并使用if语句来定义什么是 “大”,什么是“小“
创建函数,其中必要的参数是骰子的总点数
”"""
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 = input('Big or Small:') #将用户输入的字符串储存在your_choice中
if your_choice in choices: #如果符合输入规范则往下进行,不符合则告知用户并重新开始
points = roll_dice() #调用roll_dice函数,将返回的列表命名为points
total = sum(points) #求点数和
youwin = your_choice ==roll_result(total) #设定胜利条件—你所选的结果和计算机生成的结果是一致的
# 如果成立则告知胜利,反之,告知失败
if youwin:
print('the points is ',points,'you win!')
else:
print('the points is ',points,'you lose!')
else:
print('输入无效')
start_game()
start_game()
打印结果:
#####Game Starts!#####
Big or Small:Small
*****PLAY THE DICE*****
the points is [3, 5, 4] you lose!