首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >函数要求输入两次,而它应该只要求输入一次

函数要求输入两次,而它应该只要求输入一次
EN

Stack Overflow用户
提问于 2018-09-29 05:42:55
回答 2查看 70关注 0票数 0

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

代码语言:javascript
复制
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)

下面是assets模块:

代码语言:javascript
复制
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

它询问两次王牌的值(如果玩家得到了一张),即使他只得到了一张王牌,并给出了如下内容:

我尝试了不同的方法,但我仍然找不到这个问题的答案,老实说,这让我真的很沮丧。

EN

回答 2

Stack Overflow用户

发布于 2018-09-29 05:58:08

每次调用player.evaluate_hand()时,它都会调用player.evaluate_ace(),然后让用户选择该值。

避免多次询问的一种方法是保存ace的值,并仅在该值尚未保存时询问。

票数 0
EN

Stack Overflow用户

发布于 2018-09-29 06:56:11

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

代码语言:javascript
复制
def add_card(self, card_to_add):
    self.hand += card_to_add
    self.hand_value = evaluate_hand()

然后,您可以将self.evaluate_hand()的所有实例替换为self.hand_value,当设置了self.hand_value时,播放器将只提示一次ACE值。

另外,还有一些需要考虑的事情:

当你抽牌时,你同样有可能抽出任何花色。所以如果牌上还剩下10个方块和1颗心,你的算法画出心形的概率就是所有方块加起来的概率。

你真的不需要问玩家王牌的值;很明显,如果玩家可以在不破坏的情况下做到这一点,他们会选择11,否则选择1。我在赌场没什么经验。庄家真的会问玩家他们希望他们的A值多少吗?您应该计算没有max的手牌值,然后执行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或更高,手牌就不应该发生这种情况)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52562970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档