大家好,本文将围绕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)
#1.初始化牌
@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"],""))
#2.洗牌
@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] #进行交换牌
#3.发牌
@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) #三张底牌
#4.展示牌
@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()