面向对象实例练习
"""
@Time : 2024/1/18 15:42
@Auth : Of Course I Still Love You
@File :面向对象.py
@IDE :PyCharm
@note:Love is all the reasons and answers
"""
""" card 类"""
class Card:
Rank = ['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
self.is_face_up = face_up
def __str__(self):
if self.is_face_up:
rep = self.suit + self.rank
else:
rep = "xx"
return rep
def pic_order(self):
if self.rank == 'A':
Face_num = 1
elif self.rank == 'J':
Face_num = 11
elif self.rank == 'Q':
Face_num = 12
elif self.rank == 'K':
Face_num = 13
else:
Face_num = 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 + Face_num
def flip(self):
self.is_face_up = not self.is_face_up
class Hand:
"""代表一个玩家的手牌"""
def __init__(self):
self.cards = []
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)
"""Poke 类代表一 副牌 ,可以 看作是有 52 张牌的牌手 ,
所以继承Hand 类 。
由千其中cards列表变量要存储52张牌 ,
而且要发牌、洗牌 ,
所以增加如下方法:"""
class Poke(Hand):
def populate(self):
for suit in Card.SUITs:
for rank in Card.Rank:
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 wi th classes for playing cards')
players = [Hand(), Hand(), Hand(), Hand()]
pokel = Poke()
pokel.populate()
pokel.shuffle()
pokel.deal(players, 13)
n = 1
for hand in players:
print("牌手", n, end=":")
print(hand)
n += 1
input('\n 请按回车键退出')