Python 三人鬥地主程式碼

python小胡發表於2018-12-05
"""
案例鬥地主
分析:
1.撲克牌作為物件呈現
2.建立未發牌的牌堆的列表
3.建立三個玩家牌堆的列表
4.建立底牌的元組
5.最原始的牌堆初始化,將54張牌加入到牌堆
6.建立洗牌操作
7.建立發牌操作

"""
import random


class Poke:
    pokes = []
    player1 = []
    player2 = []
    player3 = []
    last = None

    def __init__(self,flower,num):
        self.flower = flower
        self.num = num

    def __str__(self):
        return "%s%s" % (self.flower, self.num)

    # 初始化牌
    @classmethod
    def init_pokes(cls):
        """   """
        flowers = ("♠", "♥", "♣", "♦")
        nums = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A")
        kings = {"big": "大王", "small": "小王"}
        for flower_ in flowers:
            for num_ in nums:
                p = Poke(flower_,num_)

                cls.pokes.append(p)
        cls.pokes.append(Poke(kings["big"], ""))
        cls.pokes.append(Poke(kings["small"], ""))

    @classmethod
    def wash_pokes(cls):
        """對建立好的牌堆進行洗牌"""
        for idx in range(54):
            idxx = random.randint(0,53)
            cls.pokes[idx], cls.pokes[idxx] = cls.pokes[idxx], cls.pokes[idx]

    @classmethod
    def deal(cls):
        """建立一個發牌的類方法"""
        for _ in range(17):
            cls.player1.append(cls.pokes.pop(0))
            cls.player2.append(cls.pokes.pop(0))
            cls.player3.append(cls.pokes.pop(0))
        cls.last = cls.pokes



    @classmethod
    def show_player(cls):
        """建立一個展示玩家底牌的類方法"""
        print("玩家1:",end="")
        for player1 in cls.player1:
            print(player1, end=",")
        print()

        print("玩家2:", end="")
        for player2 in cls.player2:
            print(player2, end=",")
        print()

        print("玩家3:", end="")
        for player3 in cls.player3:
            print(player3, end=",")
        print()

        print("底牌:", end="")
        for last1 in cls.last:
            print(last1, end=",")
        print()

    @classmethod
    def landlord(cls):
        """建立一個隨機產生地主的方法,並將剩下的底牌發給地主"""
        landlord_poke = random.randint(1,3)
        if landlord_poke == 1:
            for _ in range(3):
                cls.player1.append(cls.last.pop(0))

        if landlord_poke == 2:
            for _ in range(3):
                cls.player2.append(cls.last.pop(0))

        if landlord_poke == 3:
            for _ in range(3):
                cls.player3.append(cls.last.pop(0))

Poke.init_pokes()
Poke.wash_pokes()
Poke.deal()
Poke.landlord()
Poke.show_player()



複製程式碼

相關文章