关于python面向对象初探示例代码

高洛峰
发布: 2017-03-22 10:56:42
原创
1983 人浏览过

这篇文章详解关于python面向对象初探示例代码

import random

class Sprite:

    step = [-2,+2,-3,+3]

    def __init__(self,gm,point=None):
        self.gm = gm
        if point is None:
            self.point = random.randint(0,20)
        else:
            self.point = point

    def jump(self):
        astep = random.choice(Sprite.step)
        if 0 <= self.point + astep <= 20:
            self.point += astep

class Ant(Sprite):

    def __init__(self,gm,point=None):
        super().__init__(gm,point)
        self.gm.set_point(&#39;ant&#39;,self.point)

    def jump(self):
        super().jump()
        self.gm.set_point(&#39;ant&#39;,self.point)

class Worm(Sprite):

    def __init__(self,gm,point=None):
        super().__init__(gm,point)
        self.gm.set_point(&#39;worm&#39;,self.point)

    def  jump(self):
        super().jump()
        self.gm.set_point(&#39;worm&#39;,self.point)

class GameMap:
    def __init__(self):
        self.ant_point = None
        self.worm_point = None

    def catched(self):
        print(&#39;ant:&#39;,self.ant_point,&#39;worm:&#39;,self.worm_point)
        if self.ant_point is not None and self.worm_point is not None and self.ant_point == self.worm_point:
            return True

    def set_point(self,src,point):
        if src == &#39;ant&#39;:
            self.ant_point = point
        if src == &#39;worm&#39;:
            self.worm_point = point

if __name__ == &#39;__main__&#39;:
    gm = GameMap()
    worm = Worm(gm)
    ant = Ant(gm)
    while not gm.catched():
        worm.jump()
        ant.jump()
登录后复制


以上是关于python面向对象初探示例代码的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板