python实现斗地主(发牌、展示牌)详细注释

python实现斗地主(发牌、展示牌)

import random

# 定义类
class Poker():
    # 定义扑克
    poke = []
    # 玩家的手牌
    playerOne = []
    playerTwo = []
    playerThree = []
    # 底牌
    holeCards = []

    # 初始化类时需要传递两个参数,
    def __init__(self, num, flower):
        self.num = num
        self.flower = flower

    # 重写方法,当调用Poker.poke时,相当于调用此方法
    def __str__(self) -> str:
        return f'{self.flower}{self.num}'

    @classmethod  # 可以通过类名调用,在类加载时初始化
    def prepareCards(cls):
        # 王
        king = ['大王', '小王']
        # 花色
        flower = ['♥', '♣', '♦', '♠']
        # 牌
        num = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', "2"]
        # 双重循环,使用列表的追加方法,将牌添加到Poker里面,实际上是调用了Poker的__init__方法
        for n in num:
            for f in flower:
                # cls相当于Poker
                cls.poke.append(Poker(n, f))
        # 将王追加到扑克中
        cls.poke.append(king[0])
        cls.poke.append(king[1])

    @classmethod  # 洗牌方法
    def shuffle(cls):
        # 调用random包里面的shuffle方法,无返回值  return None
        random.shuffle(cls.poke)

    @classmethod  # 发牌
    def deal(cls):
		# 将已经打乱的牌,进行循环发牌,理解着就是一次发17张,因为索引是从0开始,所以start = 0
        for i in range(0, 54):
            if i < 17:
                # print(i)
                cls.playerOne.append(cls.poke[i])
			# 将17到34这牌发给玩家2
            if 17 <= i < 34:
                # print(i)
                cls.playerTwo.append(cls.poke[i])
            if 34 <= i < 51:
                # print(i)
                cls.playerThree.append(cls.poke[i])
			# 底牌
            if i >= 51:
                cls.holeCards.append(cls.poke[i])

    @classmethod
    def showPoke(cls):
        print('玩家1的牌:')
        for i in cls.playerOne:
            print(f'{i}', end=' ')
        print()
        print('玩家2的牌:')
        for i in cls.playerTwo:
            print(f'{i}', end=' ')
        print()
        print('玩家3的牌:', end='\n')
        for i in cls.playerThree:
            print(f'{i}', end=' ')
        print()
        print("底牌")
        for i in cls.holeCards:
            print(i, end=' ')


# 初始化
Poker.prepareCards()
# 打乱牌
Poker.shuffle()
# # 发牌
Poker.deal()
# # 展示牌
Poker.showPoke()

上一篇:整理dicom目录


下一篇:connect 出现error: C2243: “类型转换”: 从“const cls *”到“const QObject *”的转换存在,但无法访问