全局变量播放不断出现名称错误

时间:2019-05-20 16:54:33

标签: python global-variables nameerror

声明在hit_or_stay函数中作为全局变量播放,但是在运行程序时提示“名称错误:未定义播放”时会不断出错,该如何解决?

我在hit_or_stand()中使用了全局玩法来根据玩家的输入来控制游戏流程。当我运行代码时,出现错误“ NameError:未定义名称播放”。我试图将“全局播放”移到hit_or_stay()之外,但似乎没有任何效果。

import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
    'Queen':10, 'King':10, 'Ace':11}

class Deck:
    '''
        CREATES DECK, SHUFFLES DECK, DEALS CARDS.
        '''

    #CREATES DECK BY ADDING EACH SUIT TO EACH RANK AND STORING IN LIST SELF.DECK
    def __init__(self):
        self.deck = []
        for s in suits:
            for r in ranks:
                self.deck.append(r + ' of ' + s)

#SHUFFLE DECK CREATED IN __init__()
    def shuffle(self):
        random.shuffle(self.deck)

    #DEALS CARD FROM SELF.DECK AT GAME START AND IF PLAYER CHOOSES TO HIT
    def deal(self):
        single_card = self.deck.pop()
        return single_card


    #PRINTS CARDS IN SELF.DECK (FOR TROUBLESHOOTING)
    def __str__(self):
        for card in self.deck:
            return str(self.deck)



#print('\n')
##create an instance of Deck class and print the deck
#test_deck = Deck()
#print(test_deck)
#print('\n')
##shuffle and print the deck
#test_deck.shuffle()
#print(test_deck)
#print('\n')


class Card:
    '''
        CREATES CLASS FOR INDIVIDUAL CARDS, PRINTS INIDIVIDUAL CARDS "SUIT OF RANK"
        '''

    #CREATES CHARACTERISITCS OF class Card; self.suit and self.rank
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank

class Hand:
    '''
        HOLDS CARD OBJECT FROM self.deck USING Deck.deal() method
        CALCULATES THE VALUE OF THE CARDS IN HAND
        ADJUST FOR ACES WHEN APPROPRIATE
        '''
    #CREATE CHARATERISTICS FOR CARDS IN HAND; self.card = cards in hand, self.value = value of cards in hand, self.aces = counts aces in hand
    def __init__(self):
        self.cards = []
        self.value = 0
        self.aces = 0

    #ADDS CARDS TO HANDS ONCE DEALT
    def add_card(self,card):

        #ADDS CARD TO HAND
        self.cards.append(card)

        #HOLDS THE VALUE OF THE HAND
        key = ''
        key = card.split()
        self.value += values[key[0]]

        #ACCOUNT FOR ACE
        if key[0] == 'Ace':
            self.aces += 1

    #KEEPS TRACK OF ACES; ADJUSTS VALUE FOR ACE WHEN APPROPARIATE
    def adjust_for_ace(self,card):

        if self.value > 21 and self.aces:
            self.value -= 10
            self.aces -= 1


class Chips:

    def __init__(self):
        self.total = 100
        self.bet = 0

    #ADD CHIPS TO TOTAL IF WIN
    def win_bet(self):
        self.total += self.bet

    #TAKE AWAY CHIPS FORM TOTAL IF LOSE
    def lose_bet(self):
        self.total -= self.bet

#TAKE BET FROM USER
def take_bet(Chips):


    while True:
        try:
            Chips.bet = int(input("How many chips do you want to bet?: "))

        except:
            print("There was an error! Enter an integer!\n")
            continue
        else:
            if Chips.bet > Chips.total:
                print("You don't have enough chips!\n")
            else:
                print("Your bet is {} chips\n".format(Chips.bet))
                break


#IF PLAYER CHOOSES TO HIT
def hit(deck,hand):

    #USE IN hit_or_stay function; ADDS CARD DEALT FROM DECK TO THE HAND and ADJUSTS FOR ACES
    Hand.add_card(deck.deal())
    Hand.adjust_for_ace()

#DETERMINE WHETHER PLAYER WANTS TO HIT OR STAY
def hit_or_stay(deck,hand):

    global playing         #controls upcoming loop

    while True:
        h_or_s = raw_input("Would you like to hit or stay? Enter 'hit' or 'stay': ")

        if h_or_s[0].lower() == "h":
            hit(deck,hand)

        elif h_or_s[0].lower() == "s":
            playing = False

        else:
            print("\nThere was an error. Try again.\n")
            continue
        break

def show_some(player,dealer):

    print("Dealer's Hand:")
    print(dealer.cards[0])
    print("< card hidden >\n")

    print("\nPlayer's hand value: {}".format(player.value))
    print("Player's Hand:", *player.cards, sep='\n')


def show_all(player,dealer):

    print("\nDealer's hand value: {}".format(dealer.value))
    print("\nDealer's Hand:", *dealer.cards, sep='\n')

    print("\nPlayer's hand value: {}\n".format(player.value))
    print("Player's Hand:", *player.cards, sep='\n')

#GAME ENDING FUNCTIONS
def player_busts(player,dealer,Chips):

    #PRINT PLAYER BUSTS; TAKE AWAY CHIPS BET FROM TOTAL CHIPS
    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Player busts! Dealer Wins\n")
    Chips.lose_bet()
    print("You lost {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def player_wins(player,dealer,Chips):

    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Player wins!\n")
    Chips.win_bet()
    print("You won {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def dealer_busts(player,dealer,Chips):

    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Dealer busts! Player wins!\n")
    Chips.lose_bet()
    print("You won {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def dealer_wins(player,dealer,Chips):

    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Dealer wins!\n")
    Chips.lose_bet()
    print("You lost {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def push(player,dealer,Chips):

    print("Player and Dealer tie, its a push!\n")





#GAMEPLAY

while True:
    print("Welcome to Black Jack. Get as close to 21 as you can without going over 21.\n")
    print("Dealer hits until he reaches 17. Aces count as 1 or 11\n")

    #create an instance of Deck class and print the deck
    game_deck = Deck()
    #shuffle and print the deck
    game_deck.shuffle()


    #CREATE PLAYER HAND AND DEAL TWO CARDS
    player_hand = Hand()
    player_hand.add_card(game_deck.deal())
    player_hand.add_card(game_deck.deal())

    #CREATE DEALER HAND AND DEAL TWO CARDS
    dealer_hand = Hand()
    dealer_hand.add_card(game_deck.deal())
    dealer_hand.add_card(game_deck.deal())

    #TAKE BET FROM PLAYER
    #player_chips = take_bet(Chips())

    #SHOW ONE OF DEALER'S CARDS AND ALL OF PLAYER'S CARDS
    show_some(player_hand,dealer_hand)

    while playing:      #THIS IS WHERE THE NAME ERROR OCCURS!!

        if player_hand.value < 21:

            #PLAYER CHOOSES HIT OR STAY
            hit_or_stay(game_deck(),player_hand)

            #SHOW PLAYERS CARDS AND KEEP ONE DEALER CARD HIDDEN
            show_some(player_hand,dealer_hand)

NameError:名称“正在播放”未定义

2 个答案:

答案 0 :(得分:0)

问题在于playing是在hit_or_stay中定义的,直到{em> 之后,while循环才被调用。

playing定义为True以开始,或包含一个明确的break条件

while True:
    print("Welcome to Black Jack. Get as close to 21 as you can without going over 21.\n")
    print("Dealer hits until he reaches 17. Aces count as 1 or 11\n")

    # ~snip~

    # define here
    playing = True

    while playing:
        # rest of your code

此外,看起来hit_or_stay 中也有一个while循环。我建议您看一下到目前为止的代码结构,甚至可能对其进行重构。除了break中的hit_or_stay,也许您可​​以return playing

def hit_or_stay(deck,hand):
    # no need for global playing anymore, as you return the proper bool

    h_or_s = raw_input("Would you like to hit or stay? Enter 'hit' or 'stay': ")

    if h_or_s[0].lower() == "h":
        hit(deck,hand)
        return True

    elif h_or_s[0].lower() == "s":
        return False

    else:
        raise ValueError("\nThere was an error. Try again.\n")


playing = True

while playing:
    try:
        playing = hit_or_stay(deck, hand)
    # Catch the error for unexpected input and retry
    except ValueError as e:
        print(e)
        continue

答案 1 :(得分:0)

Python中的

global不会创建变量,而是defining the existing variable as global。因此,您试图声明某个变量是全局变量(但仍不存在),然后调用它。所以你会得到一个错误。

请不要在Python中使用global!在99.999%的情况下,您可以轻松替换代码而无需任何全局变量!例如,在代码的这一部分之后添加playing = True

#GAMEPLAY

while True:
    print("Welcome to Black Jack. Get as close to 21 as you can without going over 21.\n")
    print("Dealer hits until he reaches 17. Aces count as 1 or 11\n")

    #create an instance of Deck class and print the deck
    game_deck = Deck()
    #shuffle and print the deck
    game_deck.shuffle()