遊戲介紹: 四名牌手打牌,電腦隨機將52張牌(不合大、小王)發給四名牌手,並在屏幕上顯示每位牌手的牌。app
程序設計步驟:三個類 Card類、Hand類和Poke類dom
Card類函數
Card類表明一張牌,其中,FaceNum字段指的是牌面數字1~13,Suit字段指的是花色,」梅」爲梅花,」方」爲方塊,」紅」爲紅桃,」黑」爲黑桃。ui
Card構造函數根據參數初始化封裝的成員變量,實現牌面大小和花色的初始化,以及是否顯示牌面,默認True爲顯示牌的正面 spa
1,Card構造函數根據參數初始化封裝的成員變量,實現牌面大小和花色的初始化,以及是否顯示牌面,默認True爲顯示牌正面;設計
2,_str_()方法時用來輸出牌面大小和花色;blog
3,pic_order()方法獲取牌的順序號,牌面按梅花1~13,方塊14- 26,紅桃27-39,黑桃40- 52順序編號(未洗牌以前),也就是說,梅花2順序號爲2,方塊A順序號爲14,方塊K順序號爲26;繼承
4.flip()是翻牌方法,改變牌面是否顯示的屬性值。遊戲
Hand類ip
Hand類表明一個玩家手裏拿的牌,其中,cards列表變量存儲牌手手中的牌。能夠增長牌、清空手裏的牌、把一張牌給別的牌手等操做。
Poke類
Poke類表明一副牌,一副牌看做是有52張牌的牌手,繼承Hand類。因爲其中cards列表變量要存儲52張牌,並且要進行發牌、洗牌操做,因此增長 populate(self) 生成存儲了52張牌的一手牌,存儲在cards列表變量中 , random模塊shuffle() 洗牌 , deal( self., hands,per_hand=13)可完成發牌動做 等方法。
參考代碼:
class Card(): ''' A playing card.''' RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] # 牌面數字 SUTTS = ["黑桃", "紅心", "梅花", "方塊"] 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 = 11 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 = [] # 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) class Poke(Hand): """ A deck of playing cards. """ def populate(self): # 生成一副牌 for suit in Card.SUTTS: 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): # 發牌每人默認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()] poke1 = Poke() poke1.populate() # 生成一副牌 poke1.shuffle() # 洗牌 poke1.deal(players, 13) # 發牌 n = 1 for hand in players: print("牌手", n, end = ":") print(hand) n = n + 1 input("\nPress the enter key to exit.")
運行結果: