【问题标题】:Blackjack game reshuffling problem-edited二十一点游戏改组问题编辑
【发布时间】:2011-02-04 08:15:48
【问题描述】:

我正在尝试制作一个二十一点游戏,在每个新回合之前,程序都会检查以确保每个玩家的牌组有 7 张牌。如果没有,套牌就会清理、重新填充和重新洗牌。我解决了大部分问题,但出于某种原因,在每笔交易开始时,它都会不止一次地重新洗牌,我不知道为什么。请帮忙。 这是我到目前为止所拥有的: (PS 导入的卡片和游戏模块不是问题的一部分,我很确定我的问题在于 BJ_Deck 类的 deal() 函数。)

import cards, games     

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

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

    value = property(get_value)


class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS: 
            for rank in BJ_Card.RANKS: 
                self.cards.append(BJ_Card(rank, suit))

    def deal(self, hands, per_hand=1):
        for rounds in range(per_hand):
            if len(self.cards)>=7*(len(hands)):
                    print "Reshuffling the deck."
                    self.cards=[]
                    self.populate()
                    self.shuffle()
            for hand in hands:
                    top_card=self.cards[0]
                    self.give(top_card, hand)


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

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

    def get_total(self):
        # if a card in the hand has 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
        total = 0
        for card in self.cards:
              total += card.value

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

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

        return total

    total = property(get_total)

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


class BJ_Player(BJ_Hand):
    """ 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 BJ_Dealer(BJ_Hand):
    """ 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 BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):      
        self.players = []
        for name in names:
            player = BJ_Player(name)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    def get_still_playing(self):
        remaining = []
        for player in self.players:
            if not player.is_busted():
                remaining.append(player)
        return remaining

    # list of players still playing (not busted) this round
    still_playing = property(get_still_playing)

    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)

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

        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 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!\n"

    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
    for i in range(number):
        name = raw_input("Enter player name: ")
        names.append(name)
    print

    game = BJ_Game(names)

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


main()
raw_input("\n\nPress the enter key to exit.")

既然有人决定将此称为“通灵调试”,那么我将继续告诉您这些模块是什么。 这是卡片模块:

class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7",
         "8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]

def __init__(self, rank, suit, face_up = True):
    self.rank = rank
    self.suit = suit
    self.is_face_up = face_up

def __str__(self):
    if self.is_face_up:
        rep = self.rank + self.suit
    else:
        rep = "XX"
    return rep

def flip(self):
    self.is_face_up = not self.is_face_up

类手(对象): """一手扑克牌。""" def 初始化(自我): self.cards = []

def __str__(self):
    if self.cards:
       rep = ""
       for card in self.cards:
           rep += str(card) + "\t"
    else:
        rep = "<empty>"
    return rep

def clear(self):
    self.cards = []

def add(self, card):
    self.cards.append(card)

def give(self, card, other_hand):
    self.cards.remove(card)
    other_hand.add(card)

类甲板(手): """一副扑克牌。""" 定义填充(自我): 对于 Card.SUITS 中的西装: Card.RANKS 中的排名: self.add(Card(rank, suit))

def shuffle(self):
    import random
    random.shuffle(self.cards)

def deal(self, hands, per_hand = 1):
    for rounds in range(per_hand):
        for hand in hands:
            if self.cards:
                top_card = self.cards[0]
                self.give(top_card, hand)
            else:
                print "Can't continue deal. Out of cards!"

如果 name == "ma​​in": print "这是一个带有扑克牌类的模块。" raw_input("\n\n按回车键退出。")

这里是游戏模块:

class Player(object):
""" A player for a 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(问题): """问一个是或否的问题。""" 响应 = 无 而响应不在(“y”,“n”)中: 响应 = raw_input(问题).lower() 返回响应

def ask_number(问题,低,高): """求一个范围内的数字。""" 响应 = 无 而响应不在范围内(低,高): 响应 = int(原始输入(问题)) 返回响应

如果 name == "ma​​in": print "你直接运行了这个模块(并且没有'导入'它)。" raw_input("\n\n按回车键退出。")

【问题讨论】:

    标签: python


    【解决方案1】:

    您在循环内一次又一次地检查它,当您分发卡片时,牌组正在减少,我认为(无法确定您的代码中的Deck.give 方法)。

    您可能只想检查一次,将检查移到循环之外。

    def deal(self, hands, per_hand=1):
        for rounds in range(per_hand):
            if len(self.cards) <= 7 * len(hands):
                print "Reshuffling the deck."
                self.cards = []
                self.populate()
                self.shuffle()
            for hand in hands:
                top_card=self.cards[0]
                self.give(top_card, hand)
    

    【讨论】:

    • 好吧,我觉得我检查的太多了。我也认为这可以解决问题,但它仍然告诉我每手牌后它会重新洗牌两次。
    【解决方案2】:

    for hand in hands:

    真的想为每手牌运行这个逻辑吗?

    【讨论】:

      【解决方案3】:

      Nosklo 指出了一个问题(在循环内检查),但还有第二个问题。

      条件

      if len(self.cards)>=7*(len(hands)):
      

      正在检查卡片的数量是否大于所需的数量,如果是,则清除牌组,填充并洗牌。

      当与循环内的检查结合使用时,它会在每次开始下一轮时重新填充并洗牌。

      所以你可能想要这样的东西:

          if len(self.cards) <= 7*(len(hands)):
                  print "Reshuffling the deck."
                  self.cards=[]
                  self.populate()
                  self.shuffle()
          for rounds in range(per_hand):
              for hand in hands:
                      top_card=self.cards[0]
                      self.give(top_card, hand)
      

      【讨论】:

        猜你喜欢
        • 2015-08-02
        • 2016-06-21
        • 2015-06-02
        • 2013-10-08
        • 2023-03-21
        • 2020-05-18
        • 1970-01-01
        • 2020-03-06
        • 2014-10-22
        相关资源
        最近更新 更多