python - 无法为一副牌赋予数值

标签 python

(编号为 2-10 的牌的点数应分别为 2-10。J、Q 和 K 应为 10,A 应为 1 或 11,具体取决于手牌的点数)。

如何为牌组分配这些值?另外,比赛需要进行3轮。我的方法只有一轮。如何让游戏进行三次,同时跟踪玩家的输赢?

有人可以解释一下我如何以简单的方式做到这一点吗?

最佳答案

这是为您提供的完整实现

看手牌。分数

import random

class Card:
    def __init__(self,rank,suite):        
        self.rank = rank
        self.suite = suite
    def Rank(self):
        return "Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King".split()[self.rank]
    def Suite(self):
        return "Hearts Spades Clubs Diamonds".split()[self.suite]
    def __str__(self):
        #print "Get Self:",type(self)
        #print "Dir:",dir(self)
        #return "OF"
        return self.Rank()+" of "+ self.Suite()


class Hand:
    def __init__(self):
        self.cards = []
    def Score(self):
        aces_ct = 0
        score = 0
        for c in self.cards:
            if c.rank == 0:
                aces_ct += 1
                score += 11
            if 0 < c.rank < 9:
                score += c.rank+1
            else:
                score += 10
        while score > 21 and aces_ct > 0:
            score -= 10
            aces_ct -= 1
        return score
    def add(self,card):
        self.cards.append(card)
    def Show(self,show_only=None):
        if not show_only:
            for k in self.cards:
                print "%s"%k
        else:
            if isinstance(show_only,int):
                print "%s"%self.cards[show_only]
            elif isinstance(show_only,(list,tuple)):
                for idx in show_only:
                    print "%s"%self.cards[idx]


class deck:
    def __init__(self):
        self.cards = []
        for i in range(4):
            for j in range(13):
                self.cards.append(Card(j,i))
        random.shuffle(self.cards)
    def shuffle(self):
        random.shuffle(self.cards)
    def pop(self):
        return self.cards.pop()

if __name__ == "__main__":
    d = deck()
    player_hand = Hand()
    dealer_hand = Hand()
    player_hand.add(d.pop())
    dealer_hand.add(d.pop())
    player_hand.add(d.pop())
    dealer_hand.add(d.pop())
    print "Player Score :",player_hand.Score()
    player_hand.Show()
    print "\n\nDealer Score :",dealer_hand.Score()
    dealer_hand.Show()

关于python - 无法为一副牌赋予数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11730723/

相关文章:

python - 终止时保存列表值

python - TensorFlow 估计器 DNNClassifier 无法进行 2 次线性分离

python - PyRhO 似乎在安装时破坏了我的其他库

python - 严格递增子序列的最小数量

python - 在python2.6上有条件地安装importlib

Python - 重写BeautifulSoup函数变得更优雅的技巧

python - 变量不能被定义

python - 为什么 Web.py 不让我在端口 80 上运行服务器?

python - 在Python中,json.dumps无法处理{integer : 'string' ,}的字典

python - PyQt:ListWidget.insertItem 未显示