首頁  >  文章  >  後端開發  >  關於python物件導向初探範例程式碼

關於python物件導向初探範例程式碼

高洛峰
高洛峰原創
2017-03-22 10:56:421978瀏覽

這篇文章詳解關於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()

0c6dc11e160d3b678d68754cc175188a

以上是關於python物件導向初探範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn