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

问题描述 投票:-2回答:2

我刚刚开始学习Python,我正在编写一个基本的21点游戏。我已经有了一些基本的东西,但是我想在这里和那里增加一点技巧。我正在寻找一种方式,用我的while循环开始处的简介函数代替new_round函数。

我的想法是,我可以在顶部运行一个循环计数器,这将决定要运行哪个函数以及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
python python-3.x while-loop blackjack
2个回答
0
投票

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

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

而不是:

while True:
    counter = 0
    if counter > 0:

尝试:

counter = 0
while True:
    if counter > 0:

0
投票

代码中的问题是,每次循环执行While True:循环时,都将变量counter设置为零。...因此,即使在循环结束时增加counter,然后在循环重新启动时立即将其设置回零。

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

if play_again() == True:
        next_round()
        continue
© www.soinside.com 2019 - 2024. All rights reserved.