Python实现简单的斗地主功能

## 因为这个斗地主只实现了洗牌,发牌并展示玩家和底牌的功能,代码其实不算太复杂,适合初学python的小伙伴们去学习,涉及的都是一些python的基础语法和面向对象的知识,如果能把这个代码弄懂并且自己实现,相信你会收获不少。

import random
class Poke:
    pokes=[] #初始牌堆
    player1=[]#三个玩家的牌
    player2=[]
    player3=[]
    last_poke=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_poke(cls):
        flowers=("♠","♥","♣","♦") #四种花色
        nums=("2","3","4","5","6","7","8","9","10","J","Q","K","A") #14个数字牌
        kings={"big":"大王","small":"小王"} #大小王
        for flower_ in flowers:#四种花色每一种分别与14个数字进行组合
            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_poke(cls):
        for idx in range(0,54): #54张牌,列表的索引从0到53
            idxx=random.randint(0,53)#调用随机函数,随机产生0~53的数字
            cls.pokes[idx],cls.pokes[idxx]=cls.pokes[idxx],cls.pokes[idx] #进行交换牌
    #发牌
    @classmethod
    def send_poke(cls):
        for _ in range(0,17): #产生三个玩家的牌
            cls.player1.append(cls.pokes.pop(0)) #每个玩家获得17张牌
            cls.player2.append(cls.pokes.pop(0))
            cls.player3.append(cls.pokes.pop(0))
        cls.last_poke=tuple(cls.pokes) #三张底牌


    #展示牌
    @classmethod
    def show(cls,i,p):
        print(p,end=": ")
        for poke in i: #遍历扑克牌
            print(poke,end="")
        print()
    #展示玩家的牌
    @classmethod
    def show_player(cls): #调用show()方法展示三个玩家和底牌
        cls.show(cls.player1,"玩家1")
        cls.show(cls.player2,"玩家2")
        cls.show(cls.player3,"玩家3")
        cls.show(cls.last_poke,"底牌")

Poke.init_poke()
Poke.wash_poke()
Poke.send_poke()
Poke.show_player()

猜你喜欢

转载自blog.csdn.net/qq_40808154/article/details/88676523
今日推荐