所以我试图使用randomed骰子在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()
答案 0 :(得分:2)
您无法在函数之间直接共享局部变量。您的实际选择是返回值,设置全局变量,传入要修改的可变对象以包含数据,或重写以使用将值保存为属性的类。
答案 1 :(得分:1)
调用函数时,可以使用全局变量并在函数内部设置它们的值。这样您就可以从其他函数中访问该值。