python面对对象编程----1:BlackJack(21点)

时间:2021-06-26 17:30:38

昨天读完了《Mastering Object-oriented Python》的第一部分,做一些总结。

首先,第一部分总过八章,名字叫Pythonic Classes via Special Methods,也就是讲如何通过特殊方法构造以及设计类的。

其次,第一部分通篇使用的类的例子是BlackJack,也就是21点纸牌游戏,本篇先跳出来实现下21点游戏的代码,这里看明白了免得后面只使用部分时产生不清楚。【21点玩法】

以下代码我写了两个版本,版本一是原本自己按最普通的写法写的,版本二是用了部分书里的东西做了优化的,对照起来看能够发现版本二中不少优美的技巧。# py3.4.3

 #coding:gbk
import random
"""
--------------------------------------------- 第一部分:单张牌--------------------------------------------------------
"""
class Card:
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
self.hard,self.soft = self._point() def _point(self):
pass class numCard(Card):
def __init__(self,rank,suit):
super().__init__(rank,suit) def _point(self):
self.hard = self.soft = self.rank
return self.hard,self.soft class aceCard(Card):
def __init__(self,rank,suit):
super().__init__('A',suit) def _point(self):
self.hard = 1
self.soft = 11
return self.hard,self.soft class faceCard(Card):
def __init__(self,rank,suit):
super().__init__( rank , suit ) def _point(self):
self.hard = self.soft = 10
return self.hard,self.soft # somecard = [numCard('2','club'),aceCard('A','diamond'),faceCard('J','spade')]
# for i in somecard:
# print( i.rank,i.suit,i.hard,i.soft) """
-------------------------------------------------生成多幅牌---------------------------------------------------------
"""
#版本1:
# def deck(num):
# Decks = []
# for i in range(num):
# for j in ['club','heart','diamond','spade']:
# temp = [ str(x) for x in range(2,11) ]
# temp.extend(['J','Q','K','A'])
# for z in temp:
# if z in "JQK":
# Decks.append(numCard(z,j))
# elif z == 'A':
# Decks.append(aceCard(z,j))
# else:
# Decks.append(faceCard(z,j))
# random.shuffle(Decks)
# random.shuffle(Decks)
# return Decks
#
# Decks = deck(3)
# for i in Decks:
# print( i.rank,i.suit,i.hard,i.soft) # 版本2:
def card4( rank, suit ):
class_= {1: aceCard, 11: faceCard, 12: faceCard,13: faceCard}.get(rank, numCard)
return class_( rank, suit ) Decks = []
for i in range(3):
Decks.extend( [ card4(rank,suit) for rank in range(1,14) for suit in ['Club','Heart','Diamond','Spade'] ] )
random.shuffle(Decks)
# for i in Decks:
# print( i.rank,i.suit,i.hard,i.soft) """
-----------------------------------------------第三部分:手牌--------------------------------------------------------
注意:
"""
class Hand:
dieFlag = False
def __init__(self,*mycards):
self.mycards = []
self.mycards.extend(mycards)
print('your beginning cards are: ',mycards[0].suit,mycards[0].rank,mycards[1].suit,mycards[1].rank)
print('sum of your cards is:',self.count()) def askcard(self,acard):
nowpoint = self.count()
if Hand.dieFlag:
print('sum of your card is ',nowpoint,'you died')
else:
self.mycards.append(acard)
print('you get card:',acard.suit,acard.rank)
nowpoint = self.count()
print('sum of your card is ',nowpoint) def count(self):
sumpoint = 0
for x in self.mycards:
sumpoint += int(x.soft)
if sumpoint > 21:
sumpoint = 0
for x in self.mycards:
sumpoint += x.hard
if sumpoint > 21:
Hand.dieFlag = True
print('boom!,you get',sumpoint)
return sumpoint
else:
return sumpoint hands = Hand(Decks.pop(),Decks.pop())
while not hands.dieFlag:
wt2askc = input('ask card?<yes/no>: ')
if wt2askc == 'yes' and not hands.dieFlag:
hands.askcard(Decks.pop())
else:
break
print('\nfinally,your get %d points'%hands.count())

版本一

 #coding:gbk
import random
class Card:
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit class numCard(Card):
def __init__(self,rank,suit):
super().__init__(rank,suit)
self.hard = self.soft = self.rank class aceCard(Card):
def __init__(self,rank,suit):
super().__init__('A',suit)
self.hard = 1
self.soft = 11 class faceCard(Card):
def __init__(self,rank,suit):
super().__init__( rank , suit )
self.hard = self.soft = 10 # somecard = [numCard('2','club'),aceCard('A','diamond'),faceCard('J','spade')]
# for i in somecard:
# print( i.rank,i.suit,i.hard,i.soft) """
--------------------------------------------- 第二部分:生成多副牌----------------------------------------------------
一个名为Decks的列表,其元素为一张张牌
"""
def card4( rank, suit ):
class_= {1: aceCard, 11: faceCard, 12: faceCard,13: faceCard}.get(rank, numCard)
return class_( rank, suit ) class Decks(list):
def __init__(self,num):
super().__init__()
for i in range(num):
self.extend( card4(rank,suit) for rank in range(1,14) for suit in ['Club','Heart','Diamond','Spade'] )
random.shuffle(self) decks = Decks(3) """
-----------------------------------------------第三部分:手牌--------------------------------------------------------
"""
class Hand:
dieFlag = False
def __init__(self,*mycards):
self.mycards = []
self.mycards.extend(mycards)
print('your beginning cards are: ',mycards[0].suit,mycards[0].rank,mycards[1].suit,mycards[1].rank)
print('sum of your cards is:',self.count()) def askcard(self,acard):
nowpoint = self.count()
if Hand.dieFlag:
print('sum of your card is ',nowpoint,'you died')
else:
print('you get card:',acard.suit,acard.rank)
self.mycards.append(acard)
nowpoint = self.count()
print('sum of your card is ',nowpoint) def count(self):
sumpoint = sum( c.hard for c in self.mycards)
if sumpoint > 21:
sumpoint = sum( c.soft for c in self.mycards)
if sumpoint > 21:
Hand.dieFlag = True
return sumpoint if __name__=="__main__":
hands = Hand(decks.pop(),decks.pop())
while not hands.dieFlag:
wt2askc = input('ask card?<yes/no>: ')
if wt2askc == 'yes' and not hands.dieFlag:
hands.askcard(decks.pop())
else:
break
print('finally,your get %d points'%hands.count()) #
# 输出1:
# your beginning cards are: Heart 3 Spade 5
# sum of your cards is: 8
# ask card?<yes/no>: yes
# you get card: Spade 9
# sum of your card is 17
# ask card?<yes/no>: no
# finally,your get 17 points
#
# 输出2:
# your beginning cards are: Club 12 Club 3
# sum of your cards is: 13
# ask card?<yes/no>: yes
# you get card: Club 6
# sum of your card is 19
# ask card?<yes/no>: yes
# you get card: Diamond 9
# sum of your card is 28
# finally,your get 28 points

版本二