练习题解析:掷骰子
import random
def roll_dice(number = 3,points = None):
print('<<<ROLL THE DICE')
if points is None:
points = []
while number > 0:
point = random.randrange(1,7)
points.append(point)
numbers = numbers-1
return points
'''
第2行:创建函数,设定两个默认参数作为可选,numbers--骰子数量,points--三个骰子点数列表
第3行:告知用户开始摇骰子
第4-5行:如果参数中并未指定points,那么为points创建空的列表
第6-9行:摇三次骰子,每摇一次numbers就减1,直至小于等于0时,循环停止;
第10行:返回结果的列表
'''
#将点数转成大小
def roll_result(total):
isBig = 11 <= total <= 18
isSmall = 3 <= total <= 10
if isBig:
return 'Big'
elif isSmall:
return 'Small'
'''
第1行:创建函数,其中必要的参数是骰子的总数点
第2-3行:设定’大小‘的判断标准
第4-7行:在不同的条件下返回不同的结果
'''
#最后,创建一个开始游戏的函数,让用户输入猜大小,并且定义什么是猜对,什么是猜错,并输入对应的结果
def start_game():
print('<<<GAME STARTS>>>')
choices=['Big','Small']
your_choice = 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()
'''
第1行:创建函数,并不需要什么特殊参数
第2行:告知用户游戏开始
第3行:规定什么是正确的输入
第4行:讲用户输入的字符串储存在your_choice中
第5、13-15行:如果符合输入规范往下进行,不符合这告知用户并重新开始
第6行:调用roll_dice函数,将返回的列表命名为points
第7行:点数求和
第8行:设定胜利的条件--你所选的结果和计算机生成的结果是一致的
第9-12行:成立则告知胜利,反之告知失败
第16行:调用程序,使程序运行
'''
#增加个赌钱的判断
import random
def roll_dice(numbers=3,points=None):
print('<<< ROLL THE DICE! >>>')
if points is None:
points = []
while numbers > 0:
point = random.randrange(1,7)
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( ):
your_money = 1000
while your_money > 0:
print('<<< GAME STARTS!>>>')
choices = ['Big','Small']
your_choice = input('Big or Small:')
if your_choice in choices:
your_bet = int(input('How much you wanna bet? -'))
points = roll_dice( )
total = sum(points)
youWin = your_choice == roll_result(total)
if youWin:
print('The points are',points,'You win !')
print('You gained {},you have {}now'.format(your_bet,your_money+your_bet))
your_money = your_money + your_bet
else:
print('The points are',points,'You lose!')
print('You gained {},you have {}now'.format(your_bet, your_money - your_bet))
your_money = your_money - your_bet
else:
print('Invalid Words')
else:
print('GAME OVER')
start_game( )