函数请求输入两次,而它只应在

2024-04-20 12:22:52 发布

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

我目前正在为一个课程作业在Python上开发一个基于文本的21点游戏,但是当我运行以下代码时:

import assets


def show_hands(pl, dl):
    print('\n' + pl.__str__())
    print(f'Total: {pl.evaluate_hand()}')
    print(dl.hidden_card() + '\n')


def ask_for_bet(money):
    while True:
        try:
            bet = int(input(f'Your current amount of money is {money}, how much would you like to bet? (50 or up):  '))
        except ValueError:
            print('That is not a number!')
        else:
            while bet > money or bet < 50:
                if bet > money:
                    print("You don't have that much money!")
                    break
                else:
                    print("Your bet is too low! (50 or up)")
                    break
            else:
                break

    print('Alright! The game is on!')
    return bet


if __name__ == '__main__':

    print("-_-_-_-_-_-_-_-_-_Welcome to Omar's game of BlackJack!-_-_-_-_-_-_-_-_-_")
    print('\n')

    # Creating instances of both the player and the dealer, initializing the player's money
    current_money = 500
    player = assets.Player()
    dealer = assets.Dealer()

    while current_money >= 50:

        # Ask for the player's bet
        player_bet = ask_for_bet(current_money)

        # Deal two cards to the player
        print('\n' + 'The cards are being dealt...')
        player.add_card(dealer.deal_cards(2))

        # Show both the hand of the player and the dealer (one face down card)
        show_hands(player, dealer)

        # Continuously ask for the player's decision (hit/stand) as long as he chooses to hit and doesn't bust
        continue_hitting = True

        while continue_hitting and player.evaluate_hand() <= 21:

            hit_or_stand = input('Do you want to hit or stand? (hit/stand): ').lower()

            while hit_or_stand not in ('hit', 'stand'):
                hit_or_stand = input('PLease input a correct value (hit/stand): ').lower()
            else:
                if hit_or_stand == 'stand':
                    continue_hitting = False
                else:
                    player.add_card(dealer.deal_cards(1))
                    show_hands(player, dealer)
        else:
            if player.evaluate_hand() > 21:
                print('You have busted!')

        # Reveal the hand of the dealer and compare it with the player's
        print(dealer)

下面是资产模块:

import random


# -------------------------------------------------------------------------

class Player:

    def __init__(self):
        self.hand = []

    def add_card(self, card_to_add):
        self.hand += card_to_add

    def evaluate_ace(self):
        ace_value = input("Choose your ace's value (1/11): ")

        while ace_value not in ('1', '11'):
            ace_value = input("Input a correct value (1/11): ")

        return int(ace_value)

    def evaluate_hand(self):
        hand_value = 0

        for rank, suit in self.hand:
            if rank.isalpha():
                if rank in ('jack', 'king', 'queen'):
                    hand_value += 10
                else:
                    hand_value += self.evaluate_ace()
            else:
                hand_value += int(rank)

        return hand_value

    def __str__(self):
        hand_str = 'Your current hand is: '

        for rank, suit in self.hand:
            hand_str += f'({rank} of {suit})'

        return hand_str


# -------------------------------------------------------------------------

class Dealer(Player):

    suits = ['hearts', 'spades', 'diamonds', 'clubs']
    ranks = ['king', 'queen', 'jack', 'ace', '2', '3', '4', '5', '6', '7', '8', '9', '10']

    def __init__(self):
        Player.__init__(self)

        self.deck = {}
        for suit in self.suits:
            ranks_copy = self.ranks.copy()
            random.shuffle(ranks_copy)
            self.deck[suit] = ranks_copy

        self.add_card(self.deal_cards(2))

    def deal_cards(self, num_of_cards):
        dealt_cards = []

        for x in range(num_of_cards):
            rand_suit = self.suits[random.randint(0, 3)]
            dealt_cards.append((self.deck[rand_suit].pop(), rand_suit))

        return dealt_cards

    def evaluate_hand(self):
        hand_value = 0

        for rank, suit in self.hand:
            if rank.isalpha():
                if rank in ('jack', 'king', 'queen'):
                    hand_value += 10
                else:
                    if hand_value > 10:
                        hand_value += 1
                    else:
                        hand_value += 10
            else:
                hand_value += int(rank)

        return hand_value

    def __str__(self):
        hand_str = "The dealer's current hand is: "

        for rank, suit in self.hand:
            hand_str += f'({rank} of {suit})'

        return hand_str

    def hidden_card(self):
        hidden_card = "The dealer's current hand is: "

        for rank, suit in self.hand:
            if rank != 'ace':
                hidden_card += f'({rank} of {suit}) (hidden card)'
                break

        return hidden_card

它要求两次获得王牌的值(如果玩家得到一张),即使他只得到一张王牌,并且给出了一些类似于:

我尝试过不同的方法,但是我仍然找不到这个问题的答案,老实说,这让我非常沮丧。你知道吗


Tags: theselfforvaluedefcardelsecards
2条回答

每次调用player.evaluate_hand()时,它都会调用player.evaluate_ace(),然后要求用户选择值。你知道吗

避免多次询问的一种方法是保存ace的值,并且只询问尚未保存的值。你知道吗

如果要使用某个值,那么应该将其编码为属性,而不是每次调用时都返回该值的方法。因此,如果将hand_value创建为属性,则可以执行以下操作:

def add_card(self, card_to_add):
    self.hand += card_to_add
    self.hand_value = evaluate_hand()

然后你可以用self.hand_value替换self.evaluate_hand()的所有实例,当self.hand_value被设置时,玩家只会被提示输入一次ace值。你知道吗

此外,还需要考虑以下几点:

当你抽一张牌的时候,你同样有可能抽到任何一张牌。因此,如果牌组中还有10颗钻石和1颗心脏,那么使用draw the heart的算法的概率与所有钻石加在一起的概率相同。你知道吗

你其实不需要向玩家询问王牌的价值;很明显,如果玩家可以在不破坏的情况下选择11,否则选择1。我在赌场没什么经验。交易者真的问玩家他们想要的王牌值多少钱吗?你应该在没有a的情况下计算手牌值,然后执行max(rest_of_hand+number_of_aces+10*i for i in range(number_of_aces) if rest_of_hand+number_of_aces+10*i < 22),并将结果作为手牌值(注意,你必须确保这不会导致尝试获取空集的max,但只要玩家的手牌值达到21或更高,手牌就不会终止)。你知道吗

相关问题 更多 >