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

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

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

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

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

  1 #coding:gbk
  2 import random
  3 """
  4    --------------------------------------------- 第一部分:单张牌--------------------------------------------------------
  5 """
  6 class Card:
  7     def __init__(self,rank,suit):
  8         self.rank = rank
  9         self.suit = suit
 10         self.hard,self.soft = self._point()
 11 
 12     def _point(self):
 13         pass
 14 
 15 class numCard(Card):
 16     def __init__(self,rank,suit):
 17         super().__init__(rank,suit)
 18 
 19     def _point(self):
 20         self.hard = self.soft = self.rank
 21         return self.hard,self.soft
 22 
 23 class aceCard(Card):
 24     def __init__(self,rank,suit):
 25         super().__init__('A',suit)
 26 
 27     def _point(self):
 28         self.hard = 1
 29         self.soft = 11
 30         return self.hard,self.soft
 31 
 32 class faceCard(Card):
 33     def __init__(self,rank,suit):
 34         super().__init__( rank , suit )
 35 
 36     def _point(self):
 37         self.hard = self.soft = 10
 38         return self.hard,self.soft
 39 
 40 # somecard = [numCard('2','club'),aceCard('A','diamond'),faceCard('J','spade')]
 41 # for i in somecard:
 42 #     print( i.rank,i.suit,i.hard,i.soft)
 43 
 44 """
 45     -------------------------------------------------生成多幅牌---------------------------------------------------------
 46 """
 47 #版本1:
 48 # def deck(num):
 49 #     Decks = []
 50 #     for i in range(num):
 51 #         for j in ['club','heart','diamond','spade']:
 52 #             temp = [ str(x) for x in range(2,11) ]
 53 #             temp.extend(['J','Q','K','A'])
 54 #             for z in temp:
 55 #                 if z in "JQK":
 56 #                     Decks.append(numCard(z,j))
 57 #                 elif z == 'A':
 58 #                     Decks.append(aceCard(z,j))
 59 #                 else:
 60 #                     Decks.append(faceCard(z,j))
 61 #         random.shuffle(Decks)
 62 #     random.shuffle(Decks)
 63 #     return Decks
 64 #
 65 # Decks = deck(3)
 66 # for i in Decks:
 67 #         print( i.rank,i.suit,i.hard,i.soft)
 68 
 69 # 版本2:
 70 def card4( rank, suit ):
 71     class_= {1: aceCard, 11: faceCard, 12: faceCard,13: faceCard}.get(rank, numCard)
 72     return class_( rank, suit )
 73 
 74 Decks = []
 75 for i in range(3):
 76     Decks.extend( [ card4(rank,suit) for rank in range(1,14) for suit in ['Club','Heart','Diamond','Spade'] ] )
 77 random.shuffle(Decks)
 78 # for i in Decks:
 79 #         print( i.rank,i.suit,i.hard,i.soft)
 80 
 81 """
 82     -----------------------------------------------第三部分:手牌--------------------------------------------------------
 83     注意:
 84 """
 85 class Hand:
 86     dieFlag = False
 87     def __init__(self,*mycards):
 88         self.mycards = []
 89         self.mycards.extend(mycards)
 90         print('your beginning cards are: ',mycards[0].suit,mycards[0].rank,mycards[1].suit,mycards[1].rank)
 91         print('sum of your cards is:',self.count())
 92 
 93     def askcard(self,acard):
 94         nowpoint = self.count()
 95         if Hand.dieFlag:
 96             print('sum of your card is ',nowpoint,'you died')
 97         else:
 98             self.mycards.append(acard)
 99             print('you get card:',acard.suit,acard.rank)
100             nowpoint = self.count()
101             print('sum of your card is ',nowpoint)
102 
103     def count(self):
104         sumpoint = 0
105         for x in self.mycards:
106             sumpoint += int(x.soft)
107         if sumpoint > 21:
108             sumpoint = 0
109             for x in self.mycards:
110                 sumpoint += x.hard
111                 if sumpoint > 21:
112                     Hand.dieFlag = True
113                     print('boom!,you get',sumpoint)
114                     return sumpoint
115         else:
116             return sumpoint
117 
118 
119 hands = Hand(Decks.pop(),Decks.pop())
120 while not hands.dieFlag:
121     wt2askc = input('ask card?<yes/no>: ')
122     if wt2askc == 'yes' and not hands.dieFlag:
123             hands.askcard(Decks.pop())
124     else:
125         break
126 print('
finally,your get %d points'%hands.count())
版本一
  1 #coding:gbk
  2 import random
  3 class Card:
  4     def __init__(self,rank,suit):
  5         self.rank = rank
  6         self.suit = suit
  7 
  8 class numCard(Card):
  9     def __init__(self,rank,suit):
 10         super().__init__(rank,suit)
 11         self.hard = self.soft = self.rank
 12 
 13 class aceCard(Card):
 14     def __init__(self,rank,suit):
 15         super().__init__('A',suit)
 16         self.hard = 1
 17         self.soft = 11
 18 
 19 class faceCard(Card):
 20     def __init__(self,rank,suit):
 21         super().__init__( rank , suit )
 22         self.hard = self.soft = 10
 23 
 24 # somecard = [numCard('2','club'),aceCard('A','diamond'),faceCard('J','spade')]
 25 # for i in somecard:
 26 #     print( i.rank,i.suit,i.hard,i.soft)
 27 
 28 """
 29    --------------------------------------------- 第二部分:生成多副牌----------------------------------------------------
 30     一个名为Decks的列表,其元素为一张张牌
 31 """
 32 def card4( rank, suit ):
 33     class_= {1: aceCard, 11: faceCard, 12: faceCard,13: faceCard}.get(rank, numCard)
 34     return class_( rank, suit )
 35 
 36 class Decks(list):
 37     def __init__(self,num):
 38         super().__init__()
 39         for i in range(num):
 40             self.extend( card4(rank,suit) for rank in range(1,14) for suit in ['Club','Heart','Diamond','Spade'] )
 41         random.shuffle(self)
 42 
 43 decks = Decks(3)
 44 
 45 """
 46     -----------------------------------------------第三部分:手牌--------------------------------------------------------
 47 """
 48 class Hand:
 49     dieFlag = False
 50     def __init__(self,*mycards):
 51         self.mycards = []
 52         self.mycards.extend(mycards)
 53         print('your beginning cards are: ',mycards[0].suit,mycards[0].rank,mycards[1].suit,mycards[1].rank)
 54         print('sum of your cards is:',self.count())
 55 
 56     def askcard(self,acard):
 57         nowpoint = self.count()
 58         if Hand.dieFlag:
 59             print('sum of your card is ',nowpoint,'you died')
 60         else:
 61             print('you get card:',acard.suit,acard.rank)
 62             self.mycards.append(acard)
 63             nowpoint = self.count()
 64             print('sum of your card is ',nowpoint)
 65 
 66     def count(self):
 67         sumpoint = sum( c.hard for c in self.mycards)
 68         if sumpoint > 21:
 69             sumpoint = sum( c.soft for c in self.mycards)
 70             if sumpoint > 21:
 71                 Hand.dieFlag = True
 72         return sumpoint
 73 
 74 
 75 if __name__=="__main__":
 76     hands = Hand(decks.pop(),decks.pop())
 77     while not hands.dieFlag:
 78         wt2askc = input('ask card?<yes/no>: ')
 79         if wt2askc == 'yes' and not hands.dieFlag:
 80                 hands.askcard(decks.pop())
 81         else:
 82             break
 83     print('finally,your get %d points'%hands.count())
 84 
 85 #
 86 # 输出1:
 87 # your beginning cards are:  Heart 3 Spade 5
 88 # sum of your cards is: 8
 89 # ask card?<yes/no>: yes
 90 # you get card: Spade 9
 91 # sum of your card is  17
 92 # ask card?<yes/no>: no
 93 # finally,your get 17 points
 94 #
 95 # 输出2:
 96 # your beginning cards are:  Club 12 Club 3
 97 # sum of your cards is: 13
 98 # ask card?<yes/no>: yes
 99 # you get card: Club 6
100 # sum of your card is  19
101 # ask card?<yes/no>: yes
102 # you get card: Diamond 9
103 # sum of your card is  28
104 # finally,your get 28 points
版本二
原文地址:https://www.cnblogs.com/pengsixiong/p/5381105.html