【问题标题】:Python - Blackjack game not getting anymore than 1 playerPython - 二十一点游戏不超过 1 名玩家
【发布时间】:2016-07-22 07:25:06
【问题描述】:

我正在阅读一本 python 编程书,其中一章有一个二十一点游戏。我正在通过这个练习来查找程序中的错误并进行处理。其中一个错误是我要求的玩家数量在 1 到 7 之间。所以理论上,我应该能够在这个游戏中拥有多达 7 名玩家。但是,当我运行程序时,我无法添加超过 1 个玩家。如果我说我想要除 1 以外的任何其他数字,它只会重复这个问题。

这是games 模块,我在其中提出是/否和数字问题:

# Games
# Demonstrates module creation


class Player(object):
    """ A Player for the game """
    def __init__(self, name, score=0):
        self.name = name
        self.score = score

    def __str__(self):
        rep = self.name + ":\t" + str(self.score)
        return rep


def ask_yes_no(question):
    """ Ask a yes or no question """
    response = None
    while response not in ("y", "n"):
        response = input(question).lower()
    return response


def ask_number(question, low, high):
    """ Ask for a number within a range """
    response = None
    while response not in (low, high):
        response = int(input(question))
    return response

if __name__ == "__main__":
    print("You ran this module directly (and did not 'import' it).")
    input("\n\nPress the ENTER key to exit.")

这是我从上面调用的模块:

# Blackjack
# From 1 to 7 players compete against a dealer
import python_programming_absolute_beginner.chapter_9.cards as cards
import python_programming_absolute_beginner.chapter_9.games as games


class BlackjackCard(cards.Card):
    """ A Blackjack Card """
    ACE_VALUE = 1

    @property
    def value(self):
        value = BlackjackCard.RANKS.index(self.rank) + 1
        if self.is_face_up:
            if value > 10:
                value = 10
        else:
            value = None
        return value


class BlackjackDeck(cards.Deck):
    """ A Blackjack Deck """

    def populate(self):
        for suit in BlackjackCard.SUITS:
            for rank in BlackjackCard.RANKS:
                self.cards.append(BlackjackCard(rank, suit))


class BlackjackHand(cards.Hand):
    """ A Blackjack Hand """
    def __init__(self, name):
        super(BlackjackHand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BlackjackHand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):
        # if a card in the hand has a value of None, then total is None
        for card in self.cards:
            if not card.value:
                return None

        # add up card values, treat each Ace as 1
        t = 0
        for card in self.cards:
            t += card.value

        # determine if hand contains an Ace
        contains_ace = False
        for card in self.cards:
            if card.value == BlackjackCard.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough treat Ace as an 11
        if contains_ace and t <= 11:
            # add only 10 since we've already added 1 for the Ace
            t += 10
        return t

    def is_busted(self):
        return self.total > 21


class BlackjackPlayer(BlackjackHand):
    """ A Blackjack Player """
    def is_hitting(self):
        response = \
            games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
        return response == "y"

    def bust(self):
        print(self.name, "busts.")
        self.lose()

    def lose(self):
        print(self.name, "loses.")

    def win(self):
        print(self.name, "wins.")

    def push(self):
        print(self.name, "pushes.")


class BlackjackDealer(BlackjackHand):
    """ A Blackjack Dealer """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, "busts.")

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BlackjackGame(object):
    """ A Blackjack Game """
    def __init__(self, names):
        self.players = []
        for name in names:
            player = BlackjackPlayer(name)
            self.players.append(player)

        self.dealer = BlackjackDealer("Dealer")
        self.deck = BlackjackDeck()
        self.deck.populate()
        self.deck.shuffle()

        # Check the card count, and if it is less than 10 repopulate and
        # reshuffle

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)
        return sp

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print(player)
            if player.is_busted():
                player.bust()

    def play(self):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand=2)
        self.dealer.flip_first_card()  # hide dealer's first card
        for player in self.players:
            print(player)
        print(self.dealer)

        # deal additional cards to players
        for player in self.players:
            self.__additional_cards(player=player)

        self.dealer.flip_first_card()  # reveal the dealer's first card

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print(self.dealer)
        else:
            # deal additional cards to dealer
            print(self.dealer)
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win()
            else:
                # compare each player still playing to the dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

        # remove everyone's cards
        for player in self.players:
            player.clear()
        self.dealer.clear()


def main():
    print("\t\tWelcome to Blackjack!")
    names = []
    number = games.ask_number("How many players? (1 - 7): ", low=1, high=8)
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)
        print()
        game = BlackjackGame(names)

        again = None
        while again != "n":
            game.play()
            again = games.ask_yes_no("\nDo you want to play again?: ")

main()
input("\n\nPress the ENTER key to exit.")

我不太确定为什么只允许 1 名玩家而不是最多 7 名玩家?

【问题讨论】:

    标签: python python-3.5


    【解决方案1】:

    由于缩进不当,主循环中存在逻辑错误。

    你有

    def main():
        print("\t\tWelcome to Blackjack!")
        names = []
        number = games.ask_number("How many players? (1 - 7): ", low=1, high=8)
        for i in range(number):
            name = input("Enter player name: ")
            names.append(name)
            print()
            #still in the loop, game starts now with first player
            game = BlackjackGame(names)
    
            again = None
            while again != "n":
                game.play()
                again = games.ask_yes_no("\nDo you want to play again?: ")
    

    这将在第一个玩家进入后立即开始游戏。

    您希望 for 循环的主体只处理添加玩家,并且仅在添加所有玩家之后才开始游戏。

    代码应该是:

    def main():
        print("\t\tWelcome to Blackjack!")
        names = []
        number = games.ask_number("How many players? (1 - 7): ", low=1, high=8)
        for i in range(number):
            name = input("Enter player name: ")
            names.append(name)
            print()
    
        #only start the game after all players are added
        game = BlackjackGame(names)
    
        again = None
        while again != "n":
            game.play()
            again = games.ask_yes_no("\nDo you want to play again?: ")
    

    【讨论】:

      【解决方案2】:

      在我看来,这行代码有问题:

      while response not in (low, high) #It checks if variable response equals only 1 or 8.
      

      尝试将其更改为:

      while response not in range(low, high) #This checks if variable response equals any number between 1 and 8
      

      【讨论】:

      • 好吧,这阻止了它询问我想要多少玩家的问题,但它只允许我在游戏开始前输入一个玩家姓名。我也觉得main方法有问题。
      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 2018-05-18
      • 1970-01-01
      • 2023-03-21
      • 2020-05-18
      • 2020-06-20
      • 2018-06-14
      • 1970-01-01
      相关资源
      最近更新 更多