Python编程基础练习——扑克牌发牌问题
程序员文章站
2022-08-06 20:26:16
采用扑克牌类设计扑克牌发牌程序。4名牌手打牌,计算机随机将52张牌(不含大小鬼)发给4名牌手,并在屏幕上显示每位牌手的牌。##设计发牌顺序:class Card:"""a playing card."""RANKS = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"] #牌面数字1-13SUITS = ["黑","红","梅","方"]def __init__(self,rank,suit,face_up=True):s...
采用扑克牌类设计扑克牌发牌程序。4名牌手打牌,计算机随机将52张牌(不含大小鬼)发给4名牌手,并在屏幕上显示每位牌手的牌。
##设计发牌顺序:
class Card:
"""a playing card."""
RANKS = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"] #牌面数字1-13
SUITS = ["黑","红","梅","方"]
def __init__(self,rank,suit,face_up=True):
self.rank = rank
self.suit = suit
self.is_face_up = face_up
def __str__(self): ##重写print()方法, 打印一张牌的信息
if self.is_face_up:
rep = self.suit+self.rank
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
###Hand类
class Hand:
"""a hand of playing card."""
def __init__(self): ##cards 列表变量存储手中的牌
self.cards = []
def __str__(self): ##重写print()方法,打印手中的牌。
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)
##Poke类,Poke是Hand的子类。
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 shuf(self): #洗牌
import random
random.shuffle(self.cards) #打乱牌的顺序
def deal(self,hands,per_hand = 13): #发牌,发给玩家,每人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 modle with classes for playing cards.")
##4个玩家
players = [Hand(),Hand(),Hand(),Hand()]
poke1=Poke()
poke1.populate() #生成一副牌
poke1.shuf() #洗牌
poke1.deal(players,13) #给玩家发牌,每人13张
#显示4位牌手的牌
n = 1
for hand in players:
print("牌手",n,end="")
print(hand)
n += 1
input("\nPress the enter key to exit.")
print(Card.SUITS)
'''
result:
牌手 1红J 黑A 梅6 梅8 方J 方5 红8 方3 黑7 梅J 方A 黑J 梅4
牌手 2红10 梅3 梅7 黑2 黑9 红6 黑4 梅K 黑6 方9 梅5 红Q 红9
牌手 3梅A 红A 方10 方6 方4 红5 梅2 红7 方7 梅10 梅9 方8 方K
牌手 4红2 方2 黑3 方Q 红3 红4 黑Q 黑K 红K 黑8 梅Q 黑10 黑5
'''
'''
程序来自 2019年版,清华大学出版社 郑秋生,夏敏捷主编的《Python 项目案例开发从入门到实战》
'''
本文地址:https://blog.csdn.net/qq_40076228/article/details/109634137