案例:
將一副不含大小王的撲克牌隨機分發給4位玩家,每人13張
示例:
**:
class
card()
:"""一張牌"""
ranks =
["a"
,"2"
,"3"
,"4"
,"5"
,"6"
,"7"
,"8"
,"9"
,"10"
,"j"
,"q"
,"k"
]#牌面數字a~k
suits =
["♣"
,"♦"
,"♥"
,"♠"
]#牌面花色
def__init__
(self,rank,suit,face_up =
true):
self.rank = rank #指的是牌面數字
self.suit = suit #指的是牌面花色
self.is_face_up = face_up #是否顯示牌的正面,true為正面,false為反面
def__str__
(self)
:#重寫print()方法,列印一張牌的資訊
if self.is_face_up:
return self.suit+self.rank
else
:return
"xx"
defpic_order
(self)
:#牌的順序號
if self.rank ==
"a":
#定義特殊牌的數字
facenum =
1elif self.rank ==
"j":
facenum =
11elif self.rank ==
"q":
facenum =
12elif self.rank ==
"k":
facenum =
13else
: facenum =
int(self.rank)
#定義花色的序號
if self.suit ==
"♣":
suit =
1elif self.suit ==
"♦":
suit =
2elif self.suit ==
"♥":
suit =
3else
: suit =
4return
(suit-1)
*13+facenum
defflip
(self)
:#翻牌方法
self.is_face_up =
not self.is_face_up
class
hand()
:"""乙個玩家裡的手牌"""
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
defclear
(self)
:#清空手牌
self.cards =
defadd
(self,card)
:#增加牌
defgive
(self,card,other_hand)
:#把一張牌給其他牌手
self.cards.remove(card)
other_hand.add(card)
class
poke
(hand)
:"""一副牌,無大小王"""
defpopulate
(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)
#打亂牌序
defdeal
(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)
#self.give(top_card,hand) #上兩句可用此句代替
else
:print
("牌已發完!"
)if __name__ ==
"__main__"
:print
("模擬發牌"
)#4個玩家
players =
[hand(
),hand(
),hand(
),hand()]
pokel = poke(
) pokel.populate(
)#生成一副牌
pokel.shuffle(
)#洗牌
pokel.deal(players,13)
#發給玩家每人13張牌
#顯示4個玩家的手牌
n =1for hand in players:
print
("牌手"
,n,end=
':')
print
(hand)
n +=
1#input("\npress any key to exit.")
Python撲克牌發牌(用類實現)
2.題解 編寫程式,4名牌手打牌,計算機隨機將52張牌 不含大小鬼 發給4名牌手,在螢幕上顯示每位牌手的牌。設計出3個類 card類 hand類和poke類。card類代表一張牌,其中facenum欄位指出是牌面數字1 13,suit欄位指出的是花色,值 梅 為梅花,方 為方塊,紅 為紅心,黑 為黑...
撲克牌原始順序 Python實現
前幾天在閒逛的時候,突然看到了乙個關於撲克牌的題目,感覺還挺有意思,就試著分析了一下並用python實現了一下。貼出原題 手中一幅撲克牌,假設順序為abcdef,把第一張放到桌面上,第二張挪到最後,第三張放到桌面,第四張挪到最後,一直到所有牌都在桌面 bcdef a cdefb defb ac ef...
模擬分發撲克牌(python實現)
52張撲克牌發個4個玩家,每人13張。要求 自動生成一幅撲克牌組 洗牌 發牌到玩家手中 將玩家手中撲克牌按花色大小整理好。思路一import random import operator defauto pokers poker for i in for j in a 2 3 4 5 6 7 8 9...