如何交换在我的 while 循环开始时运行的函数?

How do I swap which function runs at the beginning of my while loop?

我刚刚开始学习 Python,我正在编写一个基本的二十一点游戏。我已经掌握了基本的东西,但我想在这里和那里添加一些技巧。我正在寻找一种方法,用我的 while 循环开头的引入函数代替我的 new_round 函数。

我的想法是,我可以在顶部设置一个圆形计数器 运行ning,它将指示哪个函数将 运行 通过和 if/elif 语句。

我只想说,这是行不通的。首先,我想知道为什么它没有,其次想要一种方法!

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}

player_name = ''

playing = True

class Card:

    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return f'{self.rank} of {self.suit}'

class Deck:

    def __init__(self):
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit,rank))

    def __str__(self):
        deck_comp = ''
        for card in self.deck:
            deck_comp += '\n '+card.__str__()
        return 'The deck has:' + deck_comp

    def shuffle(self):
        random.shuffle(self.deck)

    def deal(self):
        single_card = self.deck.pop()
        return single_card

class Hand:

    def __init__(self):
        self.cards = []
        self.value = 0
        self.aces = 0

    def add_card(self,card):
        self.cards.append(card)
        self.value += values[card.rank]
        if card.rank == 'Ace':
            self.aces += 1

    def adjust_for_ace(self):
        #if value of players hand is over 21 and includes an ace then the player will automatically have the ace value reduced to 1
        #also track ace counter will revert to 0
        while self.value > 21 and self.aces > 0:
            self.value -= 10
            self.aces -= 1

class Chips:

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

    def win_bet(self):
        self.total += self.bet

    def lose_bet(self):
        self.total -= self.bet

def take_bet(chips):
    while True:
        try:
            player_chips.bet = int(input('How many chips would you like to bet?: '))
        except ValueError:
            print('\nSorry, the number of chips must be a number!')
        else:
            if player_chips.bet > player_chips.total:
                print(f"\nSorry guy, your bet can't exceed {player_chips.total} chips.")
            else:
                print(f"\nYour bet of {player_chips.bet} chips has been accepted - good luck!")
                break

def introduction():
    global player_name
    print("\nWelcome to BlackJack! Get as close to 21 as you can without busting.\n\nThe Dealer will hit up to 17, Face cards count as 10 and Aces are 1/11.")
    player_name=input("The first round is about to begin, what is your name friend?: ")

def next_round():
    global player_name
    print("Hey ho, let's go another round!")

def chip_count():
    global player_name
    print(f"{player_name}, your current chip count stands at {player_chips.total}")

def play_again():
    global player_name
    global playing
    while True:
        replay = input(f"{player_name}, would you like to play another round?: ").upper()
        if replay[0] == 'Y':
            return True
        elif replay[0] == 'N':
            print(f"\nThanks for playing - you leave the table with {player_chips.total} chips.")
            break
        else:
            print("Sorry, I don't understand what you are saying, do you want to play the next round, or not? Y or N!: ")
            continue

def total():
    global player_name
    while True:
        try:
            total = int(input(f'Hello {player_name}, how many chips will you be using this game?: '))
        except ValueError:
            print('\nSorry, the number of chips must be a number!')
        else:
            return total
            print(f"\nWelcome to the table - you currently have {total} chips to play with.")

def hit(deck,hand):
    #run the add card function within the Hand Class with the card argument being generated by the deal function within the Deck Class.
    hand.add_card(deck.deal())
    hand.adjust_for_ace()

def hit_or_stand(deck,hand):
    global player_name
    global playing
    while True:
        response = input(f"{player_name}, Would you like to hit or stand?: ")
        if response[0].upper() == 'H':
            hit(deck,hand)
        elif response[0].upper() == 'S':
            print(f"{player_name} stands. It is the Dealer's turn")
            playing = False
        else:
            print("\nI can't understand what you are saying - are you hitting or standing?!")
            continue
        break

def show_some(player,dealer):
    print("\nDealer's Hand:")
    print("<card hidden>")
    print(dealer.cards[1])
    print("\nPlayer's Hand: ",*player.cards, sep='\n')
    print("Value of your cards: ",player.value)

def show_all(player,dealer):
    print("\nDealer's Hand: ",*dealer.cards, sep='\n')
    print("Dealer's Hand = ",dealer.value)
    print("\nPlayer's Hand: ",*player.cards, sep='\n')
    print("Player's Hand =  ",player.value)

def player_busts(player,dealer,chips):
    global player_name
    print(f"{player_name} busts!")
    chips.lose_bet()

def player_wins(player,dealer,chips):
    global player_name
    print(f"{player_name} wins the round!")
    chips.win_bet()


def dealer_busts(player,dealer,chips):
    print("Dealer busts!")
    chips.win_bet()


def dealer_wins(player,dealer,chips):
    print("Dealer wins!")
    chips.lose_bet()

def push(player,dealer,chips):
    print("You have tied with the Dealer! It's a push, your chips have been refunded.")

############################################################################################################################################################
while True:
    counter = 0
    if counter > 0:
        next_round()
    elif counter == 0:
        introduction()

    #Create & shuffle the deck, deal 2 cards to each player.
    deck = Deck()
    deck.shuffle()

    player_hand = Hand()
    player_hand.add_card(deck.deal())
    player_hand.add_card(deck.deal())

    dealer_hand = Hand()
    dealer_hand.add_card(deck.deal())
    dealer_hand.add_card(deck.deal())

    #Set up Player's chips
    player_chips = Chips(total())

    #Prompt the Player for their bet
    take_bet(player_chips)

    #Show cards (keep one dealer card hidden)
    show_some(player_hand,dealer_hand)

    while playing == True:
        #Prompt for player hit or stand
        hit_or_stand(deck,player_hand)

        #show cards (keep one dealer card hidden)
        show_some(player_hand,dealer_hand)

        #if player's hand exceeds 21, player busts - break loop
        if player_hand.value > 21:
            player_busts(player_hand,dealer_hand,player_chips)
            break

    #if player hasn't bust, play dealer's hand until dealer reaches 17 or busts.
    if player_hand.value <= 21:
        while dealer_hand.value < 17:
            hit(deck,dealer_hand)

        #show all cards
        show_all(player_hand,dealer_hand)

        #run different winning scenarios
        if dealer_hand.value > 21:
            dealer_busts(player_hand,dealer_hand,player_chips)
        elif dealer_hand.value > player_hand.value:
            dealer_wins(player_hand,dealer_hand,player_chips)
        elif dealer_hand.value < player_hand.value:
            player_wins(player_hand,dealer_hand,player_chips)
        else:
            push(player_hand,dealer_hand,player_chips)

    #inform player of their current chip count.
    chip_count()
    counter += 1

    #play another round?
    if play_again() == True:
        continue
    else:
        break

您正在将每个循环开始时的 counter 重置为 0

您可能打算在循环开始之前将其设置为 0,然后让它在每个循环中增加。

而不是:

while True:
    counter = 0
    if counter > 0:

尝试:

counter = 0
while True:
    if counter > 0:

您的代码中的问题是,每次您遍历 While True: 循环时,您都会将变量 counter 设置回零....因此即使您递增 counter 在循环结束时,它会在循环重新启动时立即设置回零。

另一种完成您正在寻找的方法是 运行 您的 introduction() 函数就在您的 While True: 循环之前,然后将代码的最后几行编辑为调用 next_round() 函数,如下所示:

if play_again() == True:
        next_round()
        continue