斗地主——发牌案例(数据存储练习)

案例:斗地主——发牌案例

""" 案例斗地主 分析: 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()     # 展现发牌后的玩家牌和底牌

复制代码
相关文章
相关标签/搜索