鬥地主——發牌案例(數據存儲練習)

案例:鬥地主——發牌案例

""" 案例鬥地主 分析: 1.撲克牌做爲對象呈現 2.建立未發牌的牌堆的列表 3.建立三個玩家牌堆的列表 4.建立底牌的元組(暫待) 5.最原始的牌堆初始化,將54張牌加入到牌堆 6.建立洗牌操做 7.建立發牌操做 """
# 建立Poke類,三個玩家和未發牌堆4個列表,底牌堆
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)
    # 初始化牌,54張牌添加進牌堆
 @classmethod
    def init_pokes(cls):
    # 花色數字不可變,定義爲元組
        flowers = ("♠","♥","♣","♦")  
        nums = ("2","3","4","5","6","7","8","9","10","J","Q","K","A")
    # 單獨添加大小王,運用字典練習
        kings = {"big":"大王","small":"小王"}
        # for循環嵌套組成52張花牌
        for flower_ in flowers:
            for num_ in nums:
        # 用p建立一個變量,是for循環中變量組成的任意一張牌(建立了多個對象p) 
                p = Poke(flower_,num_)
                # 把p添加進牌堆
                cls.pokes.append(p)
        # 添加大小王,引用類名.字典名,傳入鍵,取對應值,注意類型是字符串
        cls.pokes.append(Poke(kings["big"],""))
        cls.pokes.append(Poke(kings["small"],""))
    # 洗牌,洗牌就是兩兩交換,Python中能夠用a,b = b,a。選那張牌就是隨機選。
    # 定義洗牌方法
 @classmethod # 多個對象調用的方法定義爲類方法
    def wash(cls):
        # for循環,取出一張牌a
        for a in range(54):
        # 剩下53張隨機取出一張牌b
            b = random.randint(0,53)
            # a,b=b,a交換牌
            cls.pokes[a],cls.pokes[b] = cls.pokes[b],cls.pokes[a]
    # 發牌
 @classmethod
    def send_poke(cls):
    # 循環取出17張牌,發到三人手裏
        for _ in range(0,17):
        # 玩家1列表中添加的是牌堆中每次減的第一張牌
            cls.player1.append(cls.pokes.pop(0))
            # 同上
            cls.player2.append(cls.pokes.pop(0))
            cls.player3.append(cls.pokes.pop(0))
        # 將剩餘的3張牌作成底牌last,cls此時只指剩餘的三張牌
        cls.last = tuple(cls.pokes)
    # 臨時方法:展現牌堆
 @classmethod
    def show(cls):
    # 展現牌堆全部牌(可刪除)
        for poke in cls.pokes:
            print (poke,end="")
        print()
        
 @classmethod
    # 展現玩家的牌
    def show_player(cls):
        print("玩家1",end=":")
        for poke in cls.player1:
            print(poke,end=" ")  # 空格隔開每張牌,避免出現連字
        print()
        print("玩家2",end=":")
        for poke in cls.player2:
            print(poke,end=" ")
        print()
        print("玩家3",end=":")
        for poke in cls.player3:
            print(poke,end=" ")
        print()
        print("底牌",end=":")
        for poke in cls.last:
            print(poke,end=" ")
        print()
        
Poke.init_pokes()  # 調用牌堆(可刪除)
Poke.show()       # 展現牌堆全部牌(可刪除)
Poke.wash()      # 調用洗牌(可刪除)
Poke.show()       # 展現洗牌後的牌堆(可刪除)
Poke.send_poke()    # 發牌
Poke.show_player()     # 展現發牌後的玩家牌和底牌

複製代碼
相關文章
相關標籤/搜索