将列表中的字符串转换为整数

时间:2014-05-21 16:18:33

标签: python string list int blackjack

我正在制作BlackJack游戏并需要一些帮助。 我希望能够转换字符串列表,例如:

unused_cards1 = ['AS', '2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S', 'TS', 'JS', 'QS', 'KS', 'AC', '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', 'TC', 'JC', 'QC', 'KC', 'AH', '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', 'TH', 'JH', 'QH', 'KH', 'AD', '2D', '3D', '4D', '5D', '6D', '7D', '8D', '9D', 'TD', 'JD', 'QD', 'KD']
当我随机添加一个手时,

到适当的整数:

player_1_hand = []

我希望它保持它的字符串属性,当我显示手,并保持它的整数属性,以实际玩游戏,但问题是,我还希望所选卡从unused_cards1列表中删除,放入弃牌堆:used_cards = []

我该怎么做?任何方式都会有所帮助...

谢谢!

4 个答案:

答案 0 :(得分:5)

另一种方法是创建Card类:

class Card:
    def __init__(self, name):
        self.name = name

    def face_value(self):
        return #insert face value computation here

根据需要添加其他方法(例如:__str__suit等)。

然后在您的初始卡片中,执行以下操作:

unused_cards1 = map(Card, ['AS', '2S', '3S', '4S', '5S', '6S', '7S', '8S', ...])

unused_cards1将成为Card个对象的列表,而不仅仅是字符串。

答案 1 :(得分:0)

听起来像字典是你想要的:

>>> cards = {'AS' : 11, '2S' : 2, etc...}  # default aces to 11
>>> cards['AS']
1

然后您可以将卡片添加到已用过的卡片列表中:

# use the card somehow
used_cards.append('AS')

如果卡片是ace并且得分为21则添加得分,同时将得分降低10,这有效地使得ace == 1.如果手中有2个,这也只会改变一个ace的值:

for ele in hand:
    score += cards[ele]
    if score > 21 and ele in ('AS', 'AC', 'AH', 'AD'):
        score -= 10

答案 2 :(得分:0)

value_dict = dict(zip("23456789TJQKA",[2,3,4,5,6,7,8,9,10,10,10,10,11]))
p1_hand = ["AS","KS"]
p1_values = [value_dict[val[0]] for val in p1_hand]

甚至更好地使用类

答案 3 :(得分:0)

我的建议是一堂课:

class Card(object):

    FACES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}
    SUITS = {'S': 'Spades', 'D': 'Diamonds', 'C': 'Clubs', 'H': 'Hearts'}

    def __init__(self, suit, face):
        self.suit = suit
        self.face = face

    # Logic for how the Card is displayed:
    def __str__(self):
        return "{0} of {1}".format(self.FACES.get(self.face, self.face),
                                   self.SUITS[self.suit])

    # Logic for how the Card compares to others:
    def __eq__(self, other):
        return self.face == other.face

    def __lt__(self, other):
        return self.face < other.face

    # Logic for creating Card from string:
    @classmethod
    def from_string(cls, s):
        faces = {'A': 1, 'J': 11, 'Q': 12, 'K': 13}
        face, suit = s[:-1], s[-1]
        try:
            face = int(face)
        except ValueError:
            face = faces[face]
        return cls(suit, face)

现在可以使用它们:

>>> card1 = Card.from_string("AS")
>>> card2 = Card.from_string("10D")
>>> str(card1)
'Ace of Spades'
>>> str(card2)
'10 of Diamonds'
>>> card1 < card2
True