全球变量玩得越来越少

2024-06-16 12:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在hit\u或\u stay函数中将playing声明为全局变量,但当我运行程序时不断出现错误,并说“name error:playing is not defined”如何修复此问题

我在hit\u或\u stand()中使用全局播放来根据玩家的输入控制游戏流程。当我运行代码时,我得到一个错误“NameError:name playing is not defined.”我试图将“global playing”移到hit\u或\u 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:未定义名称“playing”


Tags: selfformatvaluedefcardcardsplayerprint
2条回答

问题是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 11\n")

    # ~snip~

    # define here
    playing = True

    while playing:
        # rest of your code

此外,它看起来像hit_or_stay还有一个while循环。我建议你看看到目前为止你是如何构建你的代码的,也许可以重构它。与其只在hit_or_staybreak,不如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

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()

相关问题 更多 >