2016-03-05 49 views
2

所以我试图通过使用随机骰子在Python中编程一个二十一点游戏,我试图将玩家函数与经销商函数进行比较,但是我不知道如何与其他函数进行比较?如果你可以解释一下如何在一个函数中创建一个局部变量,这个局部变量等于另一个函数中的另一个局部变量,那将是非常值得赞赏的。代码是用于如果你只是想看看我想要做什么,它没有完成。Python:你如何让两个不同函数的两个值相等?

玩二十一点骰子的程序。

import random 
def roll_die(): 
return random.randint(1, 11) 

def player(): 
    ''' 
    Implements what happens on player's turn. 
    Returns total and blackjack, which represents 
    the player's total score and whether the 
    player hit Blackjack, respectively. 
    ''' 
    blackjack = False 
    total = 0 

    print('************ YOUR TURN ************') 
    die1 = random.randint(1,11) 
    die2 = random.randint(1,11) 
    if die1 == 11 and die2 == 11: 
     die1 = 10 
    initial_roll = print('Roll: ',die1,die2) 
    initial_total = die1+die2 
    print('Total: ',initial_total) 
    stay_or_roll = input('(s)tay or (r)oll? ') 
    next_total = initial_total 
    if next_total == 21: 
     print(blackjack) 

    while stay_or_roll == 'r' or next_total > 21: 
     next_roll = (roll_die()) 
     print('\nRoll: ',next_roll) 
     next_total = int(next_total+ next_roll) 
     print('Total: ',next_total) 
     if next_total > 21: 
      print('Bust!') 
     dealer() 
     stay_or_roll = input('(s)tay or (r)oll? ')  
      if stay_or_roll == 's': 
       dealer()  

    # < Insert the rest of your code here. > 

def dealer(): 
    ''' 
    Implements what happens on the dealer's turn. 
    Returns total which represents the dealer's 
    total score. 
''' 

print("\n********** DEALER'S TURN **********") 
die1 = random.randint(1,11) 
die2 = random.randint(1,11) 
if die1 == 11 and die2 == 11: 
    die1 = 10 
initial_roll = print('Roll: ',die1,die2) 
initial_total = die1+die2 
print('Total: ',initial_total) 
stay_or_roll = input('Press <enter to continue ...') 
next_total = initial_total 
if next_total >=16 or next_total <21: 
    print('done') 
if next_total == 21: 
    print(Blackjack) 
while stay_or_roll == '' and int(next_total) <= 21: 
    next_roll = (roll_die()) 
    print('\nRoll: ',next_roll) 
    next_total = int(next_total+ next_roll) 
    print('Total: ',next_total) 
    if next_total > 21: 
     print('Bust!')  
    stay_or_roll = input('Press <enter to continue ...')  
def main(): 
    ''' 
    The main driver of the program. Connects the 
    player() and dealer() functions together to 
    play Blackjack Dice. 
    ''' 

    # The user (or player) plays first. 
player_total, blackjack = player() 
    print(player()) 
    print(dealer()) 
    # < Insert the rest of your code here. > 

main() 

回答

2

您不能在函数之间直接共享局部变量。您的实际选择是返回值,设置全局变量,传入要修改的可变对象以包含数据,或者重写为使用保留值作为属性的类。

+0

谢谢你的帮助! – CoTaNgO

1

当函数被调用时,您可以使用全局变量并从函数内部设置它们的值。这样你就可以访问其他函数的值。

相关问题