python面对对象编程----1:BlackJack(21点)
昨天读完了《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
版本二
python面对对象编程----1:BlackJack(21点)的更多相关文章
- python面对对象编程----2:__init__
面对对象编程估计我们最早接触到的就是__init__了,也就是实例的初始化处理过程: 1:来看看最基础的__init__ class Card(object): #抽象类Card,并不用于实例化 de ...
- python面对对象编程------4:类基本的特殊方法__str__,__repr__,__hash__,__new__,__bool__,6大比较方法
一:string相关:__str__(),__repr__(),__format__() str方法更面向人类阅读,print()使用的就是str repr方法更面对python,目标是希望生成一个放 ...
- python面对对象编程-------5:获取属性的四种办法:@property, __setattr__(__getattr__) ,descriptor
一:最基本的属性操作 class Generic: pass g= Generic() >>> g.attribute= "value" #创建属性并赋值 > ...
- python面对对象编程----------7:callable(类调用)与context(上下文)
一:callables callables使类实例能够像函数一样被调用 如果类需要一个函数型接口这时用callable,最好继承自abc.Callable,这样有些检查机制并且一看就知道此类的目的是c ...
- python面对对象编程---------6:抽象基类
抽象基本类的几大特点: 1:要定义但是并不完整的实现所有方法 2:基本的意思是作为父类 3:父类需要明确表示出那些方法的特征,这样在写子类时更加简单明白 用抽象基本类的地方: 1:用作父类 2:用作检 ...
- python面对对象编程中会用到的装饰器
1.property 用途:用来将对像的某个方法伪装成属性来提高代码的统一性. class Goods: #商品类 discount = 0.8 #商品折扣 def __init__(self,nam ...
- python面对对象编程------3:写集合类的三种方法
写一个集合类的三种方法:wrap,extend,invent 一:包装一个集合类 class Deck: def __init__( self ): self._cards = [card6(r+1, ...
- Python学习6——再谈抽象(面对对象编程)
1.对象魔法 在面对对象编程中,术语对象大致意味着一系列数据(属性)以及一套访问和操作这些数据的方法. 使用对象而非全局变量以及函数的原因有多个,而最重要的好处不过以下几点: 多态:可对不同类型的对象 ...
- Python - 面对对象(其他相关,异常处理,反射,单例模式,等..)
目录 Python - 面对对象(其他相关,异常处理,反射,等..) 一.isinstance(obj, cls) 二.issubclass(sub, super) 三.异常处理 1. 异常处理 2. ...
随机推荐
- ext中嵌入flash
方法1: xtype: 'fieldset', border: 0, title: "", items[{ xtype: 'flash', url: 'Test.swf' }] u ...
- ASP.NET WEB API 2 框架揭秘 读书笔记(一)
第一章 概述 主要内容是介绍Web的基本概念,Restfull的基本概念及特性.最后介绍创建简单WebApi程序的步骤. Web的基本概念 IP/TCP协议簇分层,分为两种 链路层->网络层-& ...
- canvas新属性
lineCap默认值是butt,还有aquare,round 使用:context.lineCap="butt" lineJoin miter是默认 还可以是round,bevel ...
- php中的双引号和单引号的区别?
1.单引号里面的字符串直接全部转义,原样输出(即:单引号内部的变量不会被执行) 2.双引号里面的变量会被替换(即:变量会执行) 例如:$name = 'hello';echo "the $n ...
- href 里面 链接前面加/与不加的区别?(绝对路径与相对路径)
在写href链接时,有绝对路径与相对路径,href 里面 链接前面加/与不加的区别? href="/cp/images/lis.jpg" 相对路径 cp前面/会获取当前路径,组合成 ...
- php cookie不刷新及时生效的实现代码
<?php /** * 不刷新 cookie及时生效 */ cookie("mycookie","cookievalue",time()+60); coo ...
- kafka+storm连接
本项目为maven项目,需要添加必要的storm库,以及kafka依赖,使用storm自带的storm-kafka进行连接,根据自己集群环境 <dependency> <groupI ...
- 重构后的程序:通过rsync命令抓取日志文件
push.sh #!/bin/bash function push() { local ip=$ local user=$ local password=$ local path=$ local lo ...
- 转:Centos6.3添加解码器播放MP3和常见视频音频
原文来自于:http://blog.csdn.net/odaynot/article/details/8462273 参考地址: http://wiki.centos.org/AdditionalRe ...
- c语言里用结构体和指针函数实现面向对象思想
一.基础研究 观察如下两个程序a.c和b.c: A.c: B.c: 这两个程序都是要实现在屏幕上第10行40列打印一个绿色的字符c: 这两个程序的数据组织方式是一样的,都是使用结构体,而且对共性和个性 ...