【问题标题】:What would be your recommendation for dealing a black jack hand?你对处理黑杰克手有什么建议?
【发布时间】:2020-09-12 10:59:25
【问题描述】:

我是一名初学者,我的任务是(作为课程的一部分)构建二十一点游戏。

我的初始代码可以在下面找到。我坚持的部分是当我进入 Deck 类并且必须创建 Deal 方法时。我正在努力解决的是如何分发最初的四张牌,将它们从牌组中的可用牌中移除(以备将来使用),然后还能够将它们作为变量存储为即将到来的课程中实际玩家手牌的变量。感谢您的帮助!

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}

playing = True

class Card:

    def __init__(self,suit,rank,value):
        self.suit = suit
        self.rank = rank
        self.value = value

    def __str__(self):
        print(f'{rank} of {suit}')


class Deck:

    def __init__(self):
        self.deck = []  # start with an empty list
        for suit in range(len(suits)):
            for rank in range(len(ranks)):
                self.deck += [(suits[suit],values[ranks[rank]])]

    def __str__(self):
        return f'{self.deck}'

    def shuffle(self):
        random.shuffle(self.deck)

    def deal(self):
        ?????

【问题讨论】:

  • 您忘记发布您已经完成的deal 的哪一部分。
  • 老实说,我真的不知道从哪里开始。我唯一能收集到的是,在某个时候我会在某个地方有del self.deck[0:3]

标签: python blackjack


【解决方案1】:

我的建议是让deal 函数弹出并返回一张牌,因为当玩家需要击球时你会经常这样做:

def deal(self) -> Card:
    return self.deck.pop()

然后生成两张牌的两只手,你可以这样做:

player_hand, dealer_hand = ([deck.deal() for _ in range(2)] for _ in range(2))

或许:

def deal_starting_hand(deck: Deck) -> List[Card]:
    """Deals a starting hand of two cards."""
    return [deck.deal() for _ in range(2)]

deck = Deck()
players = ["Player 1", "Dealer"]
player_hands = {player: deal_starting_hand(deck) for player in players}

等等


如果你真的想要一个返回四张卡片的函数并且你不想通过迭代弹出来做到这一点,你可以这样做:

four_cards = self.deck[:4]
self.deck = self.deck[4:]
return four_cards

但 IMO 最好(从学习和可读性的角度来看)先拥有更小更简单的功能,然后用它来构建更大的东西。

【讨论】:

  • 使用你的回复,我选择了这个:``` def deal(self): self.playerhand = [] self.dealerhand = [] for x in range(5): if x%2 != 0: self.playerhand.append(self.deck.pop(0)) else: self.dealerhand.append(self.deck.pop(0)) ``` 想法?
  • 让这两只手成为Deck 的属性似乎有点令人困惑——一旦牌在玩家手中,它们就不再在牌组中了,对吧?也许应该有一个使用DeckCardsGame 类?另请注意,range(5) 表示您正在发五张牌,因此playerhand 将有三张牌!
猜你喜欢
  • 1970-01-01
  • 2013-04-30
  • 2012-09-13
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 2015-01-24
  • 1970-01-01
相关资源
最近更新 更多