#Cards Module.py
class Card():
'''A playing card.'''
#牌面数字A-K
RANKS=['A','2','3','4','5','6','7','8','9','10','J','Q','K']
#牌面花色
SUITS=['梅','方','红','黑']
def __init__(self,rank,suit,face_up=True):
#指牌面数字
self.rank=rank
#指牌面花色
self.suit=suit
#是否显示牌正面,TRUE,FALSE
self.is_face_up=face_up
#打印一张牌的方法
def __str__(self):
if self.is_face_up:
rep=self.rank+self.suit
else:
rep='XX'
return rep
#牌的顺序号
def pic_order(self):
if self.rank=='A':
FaceNum=1
elif self.rank=='J':
FaceNum=11
elif self.rank=='Q':
FaceNum=12
elif self.rank=='K':
FaceNum=13
else:
FaceNum=int(self.rank)
if self.suit=='梅':
Suit=1
elif self.suit=='方':
Suit=2
elif self.suit=='红':
Suit=3
else:
Suit=4
return (Suit-1)*13+FaceNum
#翻牌方法
def flip(self):
self.is_face_up=not self.is_face_up
#一个玩家的手牌
class Hand():
'''A hand of playing cards.'''
#存储牌手的手牌
def __init__(self):
self.cards=[]
#重写print()方法
def __str__(self):
if self.cards:
rep=''
for card in self.cards:
rep+=str(card)+"\t"
else:
rep="无牌"
return rep
#清空牌手的手牌
def clear(self):
self.cards=[]
#增加牌
def add(self,card):
self.cards.append(card)
#把一张牌给别的牌手
def give(self,card,other_hand):
self.cards.remove(card)
other_hand.add(card)
#
class Poke(Hand):
'''A deck of playing cards.'''
#生成一副牌
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank,suit))
#洗牌
def shuffle(self):
import random
#打乱牌的顺序
random.shuffle(self.cards)
#发牌
def deal(self,hands,per_hand=13):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card=self.cards[0]
self.cards.remove(top_card)
hand.add(top_card)
else:
print("牌发完了")
#主程序
if __name__=="__main__":
print("This is a module with classes for playing cards.")
#四个玩家
players=[Hand(),Hand(),Hand(),Hand()]
poke=Poke()
#生成一副牌
poke.populate()
#洗牌
poke.shuffle()
#发牌
poke.deal(players,13)
#显示4位牌手的牌
n=1
for hand in players:
print("牌手",n,end=":")
print(hand)
n+=1
input("\nPress the enter key to exit.")
python08(扑克牌)
于 2023-04-16 18:30:49 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)