全局变量播放不断获得名称错误



声明在我的hit_or_stay函数中播放为全局变量,但是当我运行程序时,请继续出现错误,说"名称错误:播放未定义",我该如何解决此问题?

我使用hit_or_stand((中的全局播放来控制游戏流,这取决于玩家的输入。当我运行代码时,我会遇到错误"名称:名称播放未定义"。我试图在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 {} chipsn".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 Winsn")
    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 11n")
    #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)

名称:名称'play'未定义

python中的 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 11n")
    #create an instance of Deck class and print the deck
    game_deck = Deck()
    #shuffle and print the deck
    game_deck.shuffle()

问题是 playing是在 hit_or_stay中定义的,直到 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 11n")
    # ~snip~
    # define here
    playing = True
    while playing:
        # rest of your code

此外,看起来hit_or_stay 也有一个while循环。我建议您看看您到目前为止如何结构您的代码,并可能对其进行重构。也许您可以return playing

,而不是hit_or_stay中的break
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

相关内容

  • 没有找到相关文章

最新更新