笨方法学python-13(习题43-46)

习题43:你来制作一个游戏

把之前习题41写的那个游戏用了进来,简单地实现了一个,分两个文件。

BBF.py

from sys import exit
from random import randint
class Game(object):
    def __init__(self,start):
        self.quips = [
            "You died. You kinda suck at this.",
            "Your mom would be proud. If she were smarter.",
            "Such a luser.",
            "I have a small puppy that's better at this."
        ]
        self.start = start
    def play(self):
        nexta = self.start
        while True:
            print("\n------------")
            room = getattr(self, nexta)
            nexta = room()
    def death(self):
        print(self.quips[randint(0, len(self.quips)-1)])
        exit(1)
    def central_corridor(self):
        print("central_corridor")
        action = input("choose(go, do, up, Does)>")
        if action == "go":
            print("googogogogo")
            return 'death'
        elif action == "up":
            print("upupupupupup")
            return 'death'
        elif action == "do":
            print("dododododo")
            return 'laster_weapon_armory'
        else:
            print("Does")
            return 'central_corridor'
    def laster_weapon_armory(self):
        print("laster_weapon_armory")
        code = "%d%d%d" %(randint(1,9), randint(1,9), randint(1,9))
        guess =input("[keypad]>")
        guesses = 0
        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]>")
        if guess == code:
            print("sha sha sha ")
            return 'the_bridge'
        else:
            print("you shi sha sha sha")
            return 'death'
    def the_bridge(self):
        print("the_bridge")
        action = input(">")
        if action == "a":
            print("aaaaaaa")
            return 'death'
        elif action == 'b':
            print("bbbbbb")
            return 'escape_pod'
        else:
            print('cccccccc')
            return "the_bridge"
    def escape_pod(self):
        print("escape_pod")
        good_pod = randint(1,5)
        guess = input("[pod #]>")
        if int(guess) != good_pod:
            print("good_pod")
            return 'death'
        else:
            print("won")
            exit(0)

myGame.py(自己写的部分)

from random import randint
from sys import exit
from BFF import Game
class Rule(object):
    def __init__(self):
        self._Game = Game("central_corridor")

    def firstDoor(self):
        print("We will give you 3 chances to guess th number which between 0 and 9 and be given randomly.")
        num = randint(0, 9)
       # print(num)
        guess = int(input("[keypad]>"))
        chance = 0
        while guess != num and chance <5:
            if(guess > num):
                print("It should be smaller, you only have %d chances left, try again." % (5-1))
            elif(guess < num):
                print("It should be bigger, you only have %d chances left, try again." % (5-1))
            chance += 1
            guess = int(input("[keypad]>"))
        if guess != num and chance >=5:
            self.Game().death()
        if guess == num:
            Rule().over()

    def secondDoor(self):
        self._Game.play()

    def over(self):
        print("Wish you have finish the game!")
        print("Do you want to play again?")
        key = input("(yes or no)>")
        if key == 'yes':
            Rule().choose()
        elif key == 'no':
            print("Good Bye!")
            exit(0)
        else:
            print("I cannot nunderstand what you say! Sorry, try again!")
            Rule().over()

    def choose(self):
        print("There are two choices for you to choose:(1 or 2)")
        choose = int(input("Your choose is:"))
        if choose == 1:
            print("Wlecome to the place.")
            #return 'firstDoor'
            Rule().firstDoor()
        elif choose == 2:
            print("Wlecome to the place.")
            Rule().secondDoor()
        else:
            print("Your printin is wrong! Try again.")
            Rule().choose()

if __name__ == "__main__":
    Rule().choose()

写的很粗略、很简单。


习题44:给你的游戏打分

类的风格

1、使用 “camel case(驼峰式大小写)”

例如你应该使用  SuperGoldFactory 而不是  super_gold_factory 。

2、__init__ 不应该做太多的事情,这会让 class 变得难以使用。

3、其它函数应该使用 “underscore format(下划线隔词)”

所以可以写  my_awesome_hair ,而不是  myawesomehair 或者  MyAwesomeHair 。

4、用一致的方式组织函数的参数。

如果 class 需要处理 users、dogs、和 cats,就保持这个次序(特别情况除外)。如果一个函数的参数是(dog, cat, user) ,另一个的是  (user, cat, dog) ,这会让函数使用起来很困难。

5、不要对全局变量或者来自模组的变量进行重定义或者赋值。

6、不要一根筋式地维持风格一致性。

7、永远永远都使用  class Name(object) 的方式定义 class。


习题45:对象、类以及从属关系

类(class)和对象(object)的区别

一些基本概念在习题42物以类聚那一块稍微说了点,详看上一条博客的最后。

这里说:类,是一个用来描述具有同类属性的实例的概括性词汇

也即:用class创建类,类是创建实例的模板,而实例是具体的对象,实例之间的数据相互独立


1.  研究一下为什么 Python 添加了这个奇怪的叫做  object 的 class,它究竟有什么含义呢?

一个类从另一个类中继承。而object表示这个类继承的最顶级的状态。

2. 有没有办法把  Class 当作  Object 使用呢?

3. 在习题中为 animals、fish、还有 people 添加一些函数,让它们做一些事情。看看当函数在 Animal 这样的“基类(base class)”里和在 Dog 里有什么区别。

4. 找些别人的代码,理清里边的“是啥”和“有啥”的关系。

5. 使用列表和字典创建一些新的一对应多的“has-many”的关系。

6. 你认为会有一种“has-many”的关系吗?阅读一下关于“多重继承(multiple inheritance)”的资料,然后尽量避免这种用法。


习题46:一个项目骨架

骨架目录具备让项目跑起来的基本内容。里面包含你的项目文件布局、自动化测试代码,模组,以及安装脚本。

要求安装下面的软件包:

1. pip – http://pypi.python.org/pypi/pip

2. distribute – http://pypi.python.org/pypi/distribute

3. nose – http://pypi.python.org/pypi/nose/

4. virtualenv – http://pypi.python.org/pypi/virtualenv



setup.py

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'description': 'My Project',
    'author': 'GCN',
    'url': 'URL to get it at.',
    'download_url': 'Where to download it.',
    'author_email': 'nan7gc@163.com',
    'version': '0.1',
    'install_requires': ['nose'],
    'packages': ['NAME'],
    'scripts': [],
    'name': 'projectname'
}
setup(**config)

NAME_tests.py

from nose.tools import *
import NAME
def setup():
    print("SETUP!")

def teardown():
    print("TEAR DOWN!")

def test_basic():
    print("I RAN!")


剃牦牛的事情已经做的差不多了,以后每次你要新建一个项目时,只要做下面的事情就可以了:

1. 拷贝这份骨架目录,把名字改成你新项目的名字。

2. 再将 NAME 模组更名为你需要的名字,它可以是你项目的名字,当然别的名字也行。

3. 编辑 setup.py 让它包含你新项目的相关信息。

4. 重命名  tests/NAME_tests.py ,让它的名字匹配到你模组的名字。

5. 使用  nosetests 检查有无错误。

6. 开始写代码吧。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故沉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值