四名牌手打牌,电脑随机将52张牌(不含大、小王)发给四名牌手,并在屏幕上显示每位牌手的牌。
主要是对面向对象编程的学习。
Card类是卡片类,带有数字属性与花色属性。并且重写了print()方法,我们直接打印卡片类时可以直接将数字和花色一同打印出来。
class Card(): # 卡片类
RANKS = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] # 牌面数字
SUIT = ['梅','方','红','黑'] # 花色
def __init__(self, rank, suit, face_up = True):
self.rank = rank # 设置牌面数字
self.suit = suit # 设置花色
def __str__(self): # 重写print()方法,打印一张牌的信息
return self.suit + self.rank
Hand类是玩家手牌类,主要属性是一个存放牌(即卡片)的数组,清空卡片方法,添加卡片方法,给卡片方法。重写了print()方法,便于我们直接打印类。
class Hand(): # 玩家手牌类
def __init__(self):
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)
这个类是实现的一副扑克牌的类,主要是有洗牌和发牌两个方法,由于其特性,可直接继承Hand类。
class Poke(Hand):
def populate(self): # 存储了52张牌
for suit in Card.SUIT:
for rank in Card.RANKS:
self.add(Card(rank,suit)) # 双层循环将组合好的牌添加到列表
def shuffle(self): # 洗牌
import random
random.shuffle(self.cards) # 使用random的shuffle()方法将列表里的元素打乱
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.give(top_card,hand) # 调用Hand类里的give()方法
else:
print("牌已发完!")
break
class Card(): # 卡片类
RANKS = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] # 牌面数字
SUIT = ['梅','方','红','黑'] # 花色
def __init__(self, rank, suit, face_up = True):
self.rank = rank # 设置牌面数字
self.suit = suit # 设置花色
def __str__(self): # 重写print()方法,打印一张牌的信息
return self.suit + self.rank
class Hand(): # 玩家手牌类
def __init__(self):
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)
class Poke(Hand):
def populate(self): # 存储了52张牌
for suit in Card.SUIT:
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.give(top_card,hand)
else:
print("牌已发完!")
break
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)
n = 1
for hand in players:
print('牌手', n, end=':')
print(hand)
n = n+1
input("Press the enter key to exit.")
《Python游戏设计案例实战》