def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        parent = Sprite('grossinis_sister1.png')
        self.add( parent )
        parent.position = ( x/2, y/2 )

        sprite = Sprite('grossinis_sister2.png')
        sprite.position = 100,140
        sprite.do( RotateBy( duration=2, angle=360 ) )
        sprite.do( ScaleBy( duration=2, scale=2 ) )
        sprite.do( MoveBy( duration=2, delta=(200,0) ) )
        parent.add( sprite )
        sprite.opacity = 128
        self.sprite1 = sprite

        sprite = Sprite('grossini.png')
        self.add( sprite )
        sprite.position = 100,140
        sprite.do( RotateBy( duration=2, angle=360 ) )
        sprite.do( ScaleBy( duration=2, scale=2 ) )
        sprite.do( MoveBy( duration=2, delta=(200,0) ) )

        self.sprite2 = sprite
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        parent = Sprite('grossinis_sister1.png')
        self.add(parent)
        parent.position = (x // 2, y // 2)

        sprite = Sprite('grossinis_sister2.png')
        sprite.position = 100, 140
        sprite.do(RotateBy(duration=2, angle=360))
        sprite.do(ScaleBy(duration=2, scale=2))
        sprite.do(MoveBy(duration=2, delta=(200, 0)))
        parent.add(sprite)
        sprite.opacity = 128
        self.sprite1 = sprite

        sprite = Sprite('grossini.png')
        self.add(sprite)
        sprite.position = 100, 140
        sprite.do(RotateBy(duration=2, angle=360))
        sprite.do(ScaleBy(duration=2, scale=2))
        sprite.do(MoveBy(duration=2, delta=(200, 0)))

        self.sprite2 = sprite
Exemple #3
0
 def __init__(self):
     super(Snake, self).__init__()
     self.score = 30
     self.head = Sprite('img/circle.png', color=random.choice(rand_color))
     self.head.scale = 1.5
     self.head.set_position(director.get_window_size()[0] / 2,
                            director.get_window_size()[1] / 2)
     eyeball = Sprite('img/circle.png', color=(253, 55, 80))
     eyeball.scale = 0.5
     eye_left = Sprite('img/circle.png')
     eye_left.y = 5
     eye_left.scale = 0.5
     eye_left.add(eyeball)
     eye_right = Sprite('img/circle.png')
     eye_right.y = -5
     eye_right.scale = 0.5
     eye_right.add(eyeball)
     mouth = Sprite('img/circle.png', color=(0, 0, 0))
     mouth.x = +5
     mouth.scale = 0.3
     self.head.add(mouth)
     self.head.add(eye_left)
     self.head.add(eye_right)
     self.add(self.head)
     self.schedule_interval(self.update, random.random() * 0.2 + 0.1)
Exemple #4
0
 def __init__(self, person, phrase=None):
     phrase = phrase if phrase else ""
     portrait = person.portrait
     x, y = director.get_window_size()
     y = portrait.height
     pos = (x/3, y/2)
     self.duration = len(phrase)/CHARS_PER_MINUTE
     super(Phrase, self).__init__(portrait, pos)
     text = Sprite(fone)
     text.position = ((DIALOG_WIDTH+portrait.width+STEP)/2, 0)
     text.add(Label(phrase,
              height=DIALOG_HEIGHT, width=DIALOG_WIDTH,
              color=person.text_color, multiline=True, anchor_x='center'))
     self.add(text)
Exemple #5
0
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        self.batch = cocos.sprite.BatchNode()
        self.add( self.batch )

        self.sprite = Sprite('grossini.png')
        self.sprite.position = x/2, y/2

        self.sprite2 = Sprite('grossini.png')
        self.sprite2.position = 20, 30

        self.sprite5 = Sprite('grossini.png')
        self.sprite5.position = -20, 30

        self.sprite3 = Sprite('grossini.png')
        self.sprite3.position = -20, -30

        self.sprite4 = Sprite('grossini.png')
        self.sprite4.position = 20, -30

        self.sprite.add( self.sprite2, z=-1, name="temp" )
        self.sprite3.add( self.sprite4, z=1 )
        self.batch.add( self.sprite  )
        self.sprite.add( self.sprite3, z=-1 )
        self.sprite2.add( self.sprite5, z=1 )
        self.sprite.remove("temp")
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        self.image = pyglet.resource.image('grossini.png')
        self.image.anchor_x = self.image.width / 2
        self.image.anchor_y = self.image.height / 2

        self.sprite = Sprite('grossini.png', (x / 2, y / 2))
        self.sprite2 = Sprite('grossini.png', (20, 20), rotation=90)
        self.sprite3 = Sprite('grossini.png', (-20, -20), rotation=270)

        self.sprite.add(self.sprite2)
        self.sprite.add(self.sprite3)
        self.add(self.sprite)
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        self.image = pyglet.resource.image("grossini.png")
        self.image.anchor_x = self.image.width / 2
        self.image.anchor_y = self.image.height / 2

        self.sprite = Sprite("grossini.png", (x / 2, y / 2))
        self.sprite2 = Sprite("grossini.png", (20, 20), rotation=90)
        self.sprite3 = Sprite("grossini.png", (-20, -20), rotation=270)

        self.sprite.add(self.sprite2)
        self.sprite.add(self.sprite3)
        self.add(self.sprite)
    def __init__(self):
        super( TestLayer, self ).__init__()
        
        x,y = director.get_window_size()
        
        sprite1 = Sprite('grossini.png')
        sprite1.position = x/2, y/2
        sprite1.children_anchor = 0,-100
        self.add( sprite1  )

        sprite2 = Sprite('grossini.png')
        sprite2.position = 50,0
        sprite1.add( sprite2  )

        sprite3 = Sprite('grossini.png')
        sprite3.position = -50,0
        sprite1.add( sprite3 )
    def __init__(self, is_enemy=False):  # 初始化并设置状态为玩家
        super(Snake, self).__init__()  # 初始化
        self.is_dead = False  # 初始化状态为存活
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)  # 随机颜色
        if is_enemy:  # 随机怪物位置
            self.position = random.randrange(150,
                                             650), random.randrange(100, 300)
            if 300 < self.x < 500:
                self.x += 200
        else:  # 随机玩家位置
            self.position = random.randrange(350,
                                             450), random.randrange(180, 230)
        self.is_enemy = is_enemy  # 传入状态
        self.head = Sprite('circle.png', color=self.color)  # 设置头的颜色
        self.scale = 1.5  # 设置头的尺寸
        eye = Sprite('circle.png')  # 设置眼睛
        eye.y = 5  # 设置眼睛的Y轴
        eye.scale = 0.5  # 设置眼睛的尺寸
        eyeball = Sprite('circle.png', color=define.BLACK)  # 设置眼球的颜色
        eyeball.scale = 0.5  # 设置眼球的尺寸
        eye.add(eyeball)  # 在眼睛中添加眼球
        self.head.add(eye)  # 在头中添加眼睛
        eye = Sprite('circle.png')  # 设置眼睛
        eye.y = -5  # 设置眼睛的Y轴
        eye.scale = 0.5  # 设置眼睛的尺寸
        eyeball = Sprite('circle.png', color=define.BLACK)  # 设置眼球的颜色
        eyeball.scale = 0.5  # 设置眼球的尺寸
        eye.add(eyeball)  # 在眼睛中添加眼球
        self.head.add(eye)  # 设置眼睛

        self.add(self.head)  # 把头添加进身体

        self.speed = 200  # 设置怪物速度
        if not is_enemy:  # 设置玩家速度
            self.speed = 150
        self.path = [self.position] * 100  # 用一个列表记录蛇头经过的位置,身子则根据路径中对应数据更新位置

        self.schedule(self.update)  # 在时间安排表中加入snake的更新
        if self.is_enemy:  # 更新怪物
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)
Exemple #10
0
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300,
                                             1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
        else:
            self.position = random.randrange(700,
                                             900), random.randrange(350, 450)
        self.is_enemy = is_enemy
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 150
        if not is_enemy:
            self.speed = 180
        self.path = [self.position] * 100

        self.schedule(self.update)
        if self.is_enemy:
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)
Exemple #11
0
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super( TestLayer, self ).__init__()
        
        x,y = director.get_window_size()

        self.sprite = Sprite( 'grossini.png', (x/2, y/2) )
        self.add( self.sprite )
        
        self.sprite2 = Sprite( 'grossinis_sister1.png',  (0, 101) )
        self.sprite.add( self.sprite2 )
        
        self.sprite3 = Sprite( 'grossinis_sister2.png', (0, 102) )
        self.sprite2.add( self.sprite3 )
        
        self.sprite.do( Rotate(360,10) ) 
        self.sprite2.do( ScaleBy(2,5)+ScaleBy(0.5,5) ) 
        self.sprite2.do( Rotate(360,10) ) 
        self.sprite3.do( Rotate(360,10) ) 
        self.sprite3.do( ScaleBy(2,5)+ScaleBy(0.5,5) ) 
Exemple #12
0
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        self.sprite = Sprite('grossini.png', (x / 2, y / 2))
        self.add(self.sprite)

        self.sprite2 = Sprite('grossinis_sister1.png', (0, 101))
        self.sprite.add(self.sprite2)

        self.sprite3 = Sprite('grossinis_sister2.png', (0, 102))
        self.sprite2.add(self.sprite3)

        self.sprite.do(Rotate(360, 10))
        self.sprite2.do(ScaleBy(2, 5) + ScaleBy(0.5, 5))
        self.sprite2.do(Rotate(360, 10))
        self.sprite3.do(Rotate(360, 10))
        self.sprite3.do(ScaleBy(2, 5) + ScaleBy(0.5, 5))
Exemple #13
0
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300, 1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
        else:
            self.position = random.randrange(700, 900), random.randrange(350, 450)
        self.is_enemy = is_enemy
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 150
        if not is_enemy:
            self.speed = 180
        self.path = [self.position] * 100

        self.schedule(self.update)
        if self.is_enemy:
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)
    def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        sprite1 = Sprite('grossini.png')
        self.add( sprite1  )
        sprite1.position = 300,300

        sprite2 = Sprite('grossini.png')
        sprite1.add( sprite2  )
        sprite2.position = -50,-50

        sprite3 = Sprite('grossini.png')
        sprite2.add( sprite3 )
        sprite3.position = 150,150
        sprite3.rotation = 0
        sprite3.opacity = 128

        self.sprite3 = sprite3

        sprite1.do( ScaleBy(1.5, 10) )
        sprite2.do( MoveBy((100,-150),5) )
        sprite3.do( RotateBy(360,20) )
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        sprite1 = Sprite("grossini.png")
        self.add(sprite1)
        sprite1.position = 300, 300

        sprite2 = Sprite("grossini.png")
        sprite1.add(sprite2)
        sprite2.position = -50, -50

        sprite3 = Sprite("grossini.png")
        sprite2.add(sprite3)
        sprite3.position = 150, 150
        sprite3.rotation = 0
        sprite3.opacity = 128

        self.sprite3 = sprite3

        sprite1.do(ScaleBy(1.5, 10))
        sprite2.do(MoveBy((100, -150), 5))
        sprite3.do(RotateBy(360, 20))
Exemple #16
0
class Snake(cocos.cocosnode.CocosNode):
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300, 1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
        else:
            self.position = random.randrange(700, 900), random.randrange(350, 450)
        self.is_enemy = is_enemy
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 150
        if not is_enemy:
            self.speed = 180
        self.path = [self.position] * 100

        self.schedule(self.update)
        if self.is_enemy:
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)

    def add_body(self):
        b = Sprite('circle.png', color=self.color)
        b.scale = 1.5
        self.body.append(b)
        if self.x == 0:
            print self.position
        b.position = self.position
        self.parent.batch.add(b, 9999 - len(self.body))

    def init_body(self):
        self.score = 30
        self.length = 4
        self.body = []
        for i in range(self.length):
            self.add_body()

    def update(self, dt):
        self.angle = (self.angle + 360) % 360

        arena = self.parent
        if self.is_enemy:
            self.check_crash(arena.snake)
        for s in arena.enemies:
            if s != self and not s.is_dead:
                self.check_crash(s)
        if self.is_dead:
            return

        if abs(self.angle - self.angle_dest) < 2:
            self.angle = self.angle_dest
        else:
            if (0 < self.angle - self.angle_dest < 180) or (
                self.angle - self.angle_dest < -180):
                self.angle -= 500 * dt
            else:
                self.angle += 500 * dt
        self.head.rotation = -self.angle

        self.x += math.cos(self.angle * math.pi / 180) * dt * self.speed
        self.y += math.sin(self.angle * math.pi / 180) * dt * self.speed
        self.path.append(self.position)

        lag = int(round(1100.0 / self.speed))
        for i in range(self.length):
            idx = (i + 1) * lag + 1
            self.body[i].position = self.path[-min(idx,len(self.path))]
            if self.body[i].x == 0:
                print self.body[i].position
        m_l = max(self.length * lag * 2, 60)
        if len(self.path) > m_l:
            self.path = self.path[-m_l * 2:]

    def update_angle(self, keys):
        x, y = 0, 0
        if 65361 in keys:  # 左
            x -= 1
        if 65362 in keys:  # 上
            y += 1
        if 65363 in keys:  # 右
            x += 1
        if 65364 in keys:  # 下
            y -= 1
        directs = ((225, 180, 135), (270, None, 90), (315, 0, 45))
        direct = directs[x + 1][y + 1]
        if direct is None:
            self.angle_dest = self.angle
        else:
            self.angle_dest = direct

    def add_score(self, s=1):
        if self.is_dead:
            return
        self.score += s
        l = (self.score - 6) / 6
        if l > self.length:
            self.length = l
            self.add_body()

    def ai(self, dt):
        self.angle_dest = (self.angle_dest + 360) % 360
        if (self.x < 100 and 90 < self.angle_dest < 270) or (
            self.x > define.WIDTH - 100 and (
                self.angle_dest < 90 or self.angle_dest > 270)
        ):
            self.angle_dest = 180 - self.angle_dest
        elif (self.y < 100 and self.angle_dest > 180) or (
            self.y > define.HEIGHT - 100 and self.angle_dest < 180
        ):
            self.angle_dest = -self.angle_dest
        else:
            arena = self.parent
            self.collision_detect(arena.snake)
            for s in arena.enemies:
                if s != self:
                    self.collision_detect(s)

    def collision_detect(self, other):
        if self.is_dead or other.is_dead:
            return
        for b in other.body:
            d_y = b.y - self.y
            d_x = b.x - self.x
            if abs(d_x) > 200 or abs(d_y) > 200:
                return
            if d_x == 0:
                if d_y > 0:
                    angle = 90
                else:
                    angle = -90
            else:
                angle = math.atan(d_y / d_x) * 180 / math.pi
                if d_x < 0:
                    angle += 180
            angle = (angle + 360) % 360
            if abs(angle - self.angle_dest) < 5:
                self.angle_dest += random.randrange(90, 270)

    def check_crash(self, other):
        if self.is_dead or other.is_dead:
            return
        if (self.x < 0 or self.x > define.WIDTH) or (
            self.y < 0 or self.y > define.HEIGHT
        ):
            self.crash()
            return
        for b in other.body:
            dis = math.sqrt((b.x - self.x) ** 2 + (b.y - self.y) ** 2)
            if dis < 24:
                self.crash()
                return

    def crash(self):
        if not self.is_dead:
            self.is_dead = True
            self.unschedule(self.update)
            self.unschedule(self.ai)
            arena = self.parent
            for b in self.body:
                arena.batch.add(Dot(b.position, b.color))
                arena.batch.add(Dot(b.position, b.color))
                arena.batch.remove(b)

            arena.remove(self)
            arena.add_enemy()
            del self.path
            if self.is_enemy:
                arena.enemies.remove(self)
                del self.body
                del self
            else:
                arena.parent.end_game()
Exemple #17
0
class Snake(cocos.cocosnode.CocosNode):
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300,
                                             1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
        else:
            self.position = random.randrange(700,
                                             900), random.randrange(350, 450)
        self.is_enemy = is_enemy
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 150
        if not is_enemy:
            self.speed = 180
        self.path = [self.position] * 100

        self.schedule(self.update)
        if self.is_enemy:
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)

    def add_body(self):
        b = Sprite('circle.png', color=self.color)
        b.scale = 1.5
        self.body.append(b)
        if self.x == 0:
            print self.position
        b.position = self.position
        self.parent.batch.add(b, 9999 - len(self.body))

    def init_body(self):
        self.score = 30
        self.length = 4
        self.body = []
        for i in range(self.length):
            self.add_body()

    def update(self, dt):
        self.angle = (self.angle + 360) % 360

        arena = self.parent
        if self.is_enemy:
            self.check_crash(arena.snake)
        for s in arena.enemies:
            if s != self and not s.is_dead:
                self.check_crash(s)
        if self.is_dead:
            return

        if abs(self.angle - self.angle_dest) < 2:
            self.angle = self.angle_dest
        else:
            if (0 < self.angle - self.angle_dest <
                    180) or (self.angle - self.angle_dest < -180):
                self.angle -= 500 * dt
            else:
                self.angle += 500 * dt
        self.head.rotation = -self.angle

        self.x += math.cos(self.angle * math.pi / 180) * dt * self.speed
        self.y += math.sin(self.angle * math.pi / 180) * dt * self.speed
        self.path.append(self.position)

        lag = int(round(1100.0 / self.speed))
        for i in range(int(self.length)):
            idx = (i + 1) * lag + 1
            self.body[i].position = self.path[-min(idx, len(self.path))]
            if self.body[i].x == 0:
                print(self.body[i].position)
        m_l = max(self.length * lag * 2, 60)
        if len(self.path) > m_l:
            self.path = self.path[int(-m_l * 2):]

    def update_angle(self, keys):
        x, y = 0, 0
        if 65361 in keys:  # 左
            x -= 1
        if 65362 in keys:  # 上
            y += 1
        if 65363 in keys:  # 右
            x += 1
        if 65364 in keys:  # 下
            y -= 1
        directs = ((225, 180, 135), (270, None, 90), (315, 0, 45))
        direct = directs[x + 1][y + 1]
        if direct is None:
            self.angle_dest = self.angle
        else:
            self.angle_dest = direct

    def add_score(self, s=1):
        if self.is_dead:
            return
        self.score += s
        l = (self.score - 6) / 6
        if l > self.length:
            self.length = l
            self.add_body()

    def ai(self, dt):
        self.angle_dest = (self.angle_dest + 360) % 360
        if (self.x < 100 and 90 < self.angle_dest < 270) or (
                self.x > define.WIDTH - 100 and
            (self.angle_dest < 90 or self.angle_dest > 270)):
            self.angle_dest = 180 - self.angle_dest
        elif (self.y < 100
              and self.angle_dest > 180) or (self.y > define.HEIGHT - 100
                                             and self.angle_dest < 180):
            self.angle_dest = -self.angle_dest
        else:
            arena = self.parent
            self.collision_detect(arena.snake)
            for s in arena.enemies:
                if s != self:
                    self.collision_detect(s)

    def collision_detect(self, other):
        if self.is_dead or other.is_dead:
            return
        for b in other.body:
            d_y = b.y - self.y
            d_x = b.x - self.x
            if abs(d_x) > 200 or abs(d_y) > 200:
                return
            if d_x == 0:
                if d_y > 0:
                    angle = 90
                else:
                    angle = -90
            else:
                angle = math.atan(d_y / d_x) * 180 / math.pi
                if d_x < 0:
                    angle += 180
            angle = (angle + 360) % 360
            if abs(angle - self.angle_dest) < 5:
                self.angle_dest += random.randrange(90, 270)

    def check_crash(self, other):
        if self.is_dead or other.is_dead:
            return
        if (self.x < 0 or self.x > define.WIDTH) or (self.y < 0 or
                                                     self.y > define.HEIGHT):
            self.crash()
            return
        for b in other.body:
            dis = math.sqrt((b.x - self.x)**2 + (b.y - self.y)**2)
            if dis < 24:
                self.crash()
                return

    def crash(self):
        if not self.is_dead:
            self.is_dead = True
            self.unschedule(self.update)
            self.unschedule(self.ai)
            arena = self.parent
            for b in self.body:
                arena.batch.add(Dot(b.position, b.color))
                arena.batch.add(Dot(b.position, b.color))
                arena.batch.remove(b)

            arena.remove(self)
            arena.add_enemy()
            del self.path
            if self.is_enemy:
                arena.enemies.remove(self)
                del self.body
                del self
            else:
                arena.parent.end_game()
Exemple #18
0
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        # rotation and childs, with default transform_anchor s
        self.sprite_a1 = Sprite("grossini.png", (x // 4, int(y * 0.66)))
        self.sprite_a2 = Sprite("grossini.png", (0, 0), rotation=30)
        self.sprite_a3 = Sprite("grossini.png", (0, 0), rotation=30)

        self.sprite_a1.add(self.sprite_a2)
        self.sprite_a2.add(self.sprite_a3)
        self.add(self.sprite_a1)

        # position and childs, with default transform_anchor s
        self.sprite_b1 = Sprite("grossinis_sister1.png", (x // 2, int(y * 0.66)))
        self.sprite_b2 = Sprite("grossinis_sister1.png", (100, 0))
        self.sprite_b3 = Sprite("grossinis_sister1.png", (100, 0))

        self.sprite_b1.add(self.sprite_b2)
        self.sprite_b2.add(self.sprite_b3)
        self.add(self.sprite_b1)

        # combo, with default transform_anchor s
        self.sprite_c1 = Sprite("grossinis_sister2.png", (int(x * 0.33), int(y * 0.33)))
        self.sprite_c2 = Sprite("grossinis_sister2.png", (100, 0), rotation=30)
        self.sprite_c3 = Sprite("grossinis_sister2.png", (100, 0), rotation=30)

        self.sprite_c1.add(self.sprite_c2)
        self.sprite_c2.add(self.sprite_c3)
        self.add(self.sprite_c1)
Exemple #19
0
class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super(TestLayer, self).__init__()

        x, y = director.get_window_size()

        # rotation and childs, with default transform_anchor s
        self.sprite_a1 = Sprite('grossini.png', (x // 4, int(y * 0.66)))
        self.sprite_a2 = Sprite('grossini.png', (0, 0), rotation=30)
        self.sprite_a3 = Sprite('grossini.png', (0, 0), rotation=30)

        self.sprite_a1.add(self.sprite_a2)
        self.sprite_a2.add(self.sprite_a3)
        self.add(self.sprite_a1)

        # position and childs, with default transform_anchor s
        self.sprite_b1 = Sprite('grossinis_sister1.png',
                                (x // 2, int(y * 0.66)))
        self.sprite_b2 = Sprite('grossinis_sister1.png', (100, 0))
        self.sprite_b3 = Sprite('grossinis_sister1.png', (100, 0))

        self.sprite_b1.add(self.sprite_b2)
        self.sprite_b2.add(self.sprite_b3)
        self.add(self.sprite_b1)

        # combo, with default transform_anchor s
        self.sprite_c1 = Sprite('grossinis_sister2.png',
                                (int(x * 0.33), int(y * 0.33)))
        self.sprite_c2 = Sprite('grossinis_sister2.png', (100, 0), rotation=30)
        self.sprite_c3 = Sprite('grossinis_sister2.png', (100, 0), rotation=30)

        self.sprite_c1.add(self.sprite_c2)
        self.sprite_c2.add(self.sprite_c3)
        self.add(self.sprite_c1)
Exemple #20
0
class Snake(cocos.cocosnode.CocosNode):
    gene_list = []
    curr_gens = []
    snake_num = 0
    dead_num = 0
    times = define.POP_SIZE * [0]
    scores = define.POP_SIZE * [0]

    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        Snake.snake_num += 1
        self.birth = time.time()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300, 1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
                # else:
                #     self.position = random.randrange(700, 900), random.randrange(350, 450)
        self.is_enemy = True
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        self.score = 0
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 140
        self.path = [self.position] * 100

        # with open("generation"+str(current_gen)+".ini", 'r') as r:
        #     data = r.read()
        current_gen = Snake.snake_num / define.POP_SIZE
        if Snake.snake_num - 9 >= 0:
            current_gen = (Snake.snake_num - 9) / define.POP_SIZE
        print ("snakenum", Snake.snake_num)
        print("currentgen", current_gen)
        print("genelist len", len(Snake.gene_list))
        if len(Snake.gene_list) == 0:
            print("genelist", Snake.gene_list)
            with open("generation" + str(current_gen) + ".ini", "r") as r:
                data = r.read()
            Snake.gene_list = (data.split("\n"))
            if current_gen == 0:
                Snake.curr_gens = Snake.gene_list[7:]
            else:
                Snake.curr_gens = Snake.gene_list[:]
            print("currgens", Snake.curr_gens)
            print("currgens len", len(Snake.curr_gens))
        self.threhold, self.hunger, self.alive = translateDNA([Snake.gene_list.pop()])

        if Snake.dead_num != 0 and Snake.dead_num % define.DEAD_NUM == 0:
            fitness = get_fitness(Snake.scores, Snake.times)
            pop = select(Snake.curr_gens, fitness)
            pop_copy = pop[:]
            # print("pop", pop)
            # print("pop copy", pop_copy)
            # print("pop copy", pop_copy.ndim)
            data = []
            for parent in pop:
                child = crossover(parent, pop_copy)
                child = mutate(child)
                temp = [str(i) for i in child]
                data.append(''.join(temp))
            with open("generation" + str(current_gen + 1) + ".ini", 'a') as w:
                w.write('\n'.join(data))

        self.schedule(self.update)
        self.schedule(self.my_ai)  # random.random() * 0.1 + 0.05

    def add_body(self):

        b = Sprite('circle.png', color=self.color)
        b.scale = 1.5
        self.body.append(b)
        if self.x == 0:
            print(self.position)

        b.position = self.position
        self.parent.batch.add(b, 9999 - len(self.body))

    def my_ai(self, dt):

        self.angle_dest = (self.angle_dest + 360) % 360
        if self.x < 250 and 90 < self.angle_dest < 270:
            self.angle_dest = random.randrange(-90, 90)
        elif self.x > (define.WIDTH - 250):
            if self.angle_dest < 90 or self.angle_dest > 270:
                print (self.angle_dest)
                self.angle_dest = random.randrange(90, 270)
        elif self.y < 250 and self.angle_dest > 180:
            self.angle_dest = random.randrange(0, 180)
        elif self.y > define.HEIGHT - 250 and self.angle_dest < 180:
            self.angle_dest = random.randrange(180, 360)
        else:
            anemey = self._get_nearest_em()
            if anemey is not None:
                self.angle_dest = self.select_direction(anemey)

    def _judge_pos(self, enemey):

        em_x, em_y = enemey.position
        m_x, m_y = self.position
        em_angle = enemey.angle
        return math.tan(em_angle) * m_x + (em_y * math.tan(em_angle) * em_x) - m_y > 0

    def _get_nearest_em(self):

        arena = self.parent
        m_x, m_y = self.position

        Min = 100000
        Min_body = -1
        Min_em = -1
        for em in arena.enemies:
            for bd in em.body:
                d_x, d_y = bd.position
                _y = d_y - m_y
                _x = d_x - m_x
                distance = math.sqrt(_y ** 2 + _x ** 2)
                if distance < Min:
                    Min = distance
                    Min_body = bd
                    Min_em = em
        # print(Min)
        # for bd in Min_em.body:
        #     bd.color = define.BLACK
        if Min > self.threhold:
            return None
        else:
            return Min_em

    def _judge_oneside(self, k, em_pos, aim_pos):

        em_x, em_y = em_pos
        aim_x, aim_y = aim_pos
        me_x, me_y = self.position
        f1 = em_y - (k * (em_x - me_x) + me_y)
        f2 = aim_y - (k * (aim_x - me_x) + me_y)
        return f1 * f2 < 0

    def _judge_inrange(self, angle_round, theta):  # 判断是否在范围内

        if angle_round[0] < 0:
            return angle_round[0] + 360 <= theta + 360 < angle_round[1] + 360
        else:
            return angle_round[0] <= theta < angle_round[1]

    def select_direction(self, enemey):

        m_x, m_y = self.position
        em_angle = enemey.angle
        if self._judge_pos(enemey):
            if em_angle > 180:
                angle_round = (em_angle - 360, em_angle - 180)
            else:
                angle_round = (em_angle - 180, em_angle)
        else:
            if em_angle > 180:
                angle_round = (em_angle - 180, em_angle)
            else:
                angle_round = (em_angle, em_angle + 180)

        angle_list = [1] * 180
        arena = self.parent
        k = math.tan(em_angle * math.pi / 180)
        for dot in arena.dots:
            d_x, d_y = dot.position
            _y = d_y - m_y
            _x = d_x - m_x
            distance = math.sqrt(_y ** 2 + _x ** 2)
            if distance > self.threhold:
                continue
            if _x != 0:
                theta = math.atan(abs(_y) / abs(_x)) * 180 / math.pi
            else:
                theta = 0
            score = self.hunger / distance
            # count1 = count2 = count3 = 0
            # if self._judge_oneside(k, enemey.position, dot.position):
            # print('dot')
            if _x > 0 and _y > 0:
                aim_angle = theta
            elif _x < 0 and _y > 0:
                aim_angle = 180 - theta
            elif _x < 0 and _y < 0:
                aim_angle = theta - 180
            else:
                aim_angle = -theta
            # count1 += 1
            if self._judge_inrange(angle_round, aim_angle):
                # count2 += 1
                relative_angle = int(aim_angle - angle_round[0])
                try:
                    # count3 += 1
                    angle_list[relative_angle] += score
                except:
                    print(k, self.position, enemey.position, dot.position, relative_angle, aim_angle, angle_round)
        for em in arena.enemies:
            for bd in em.body:
                d_x, d_y = bd.position
                _y = d_y - m_y
                _x = d_x - m_x
                distance = math.sqrt(_y ** 2 + _x ** 2)
                if distance > self.threhold:
                    continue
                if _x != 0:
                    theta = math.atan(abs(_y) / abs(_x)) * 180 / math.pi
                else:
                    theta = 0
                try:
                    score = self.alive / distance
                except:
                    continue
                # if self._judge_oneside(k, enemey.position, bd.position):
                if _x > 0 and _y > 0:
                    aim_angle = theta
                elif _x < 0 and _y > 0:
                    aim_angle = 180 - theta
                elif _x < 0 and _y < 0:
                    aim_angle = theta - 180
                else:
                    aim_angle = -theta
                if self._judge_inrange(angle_round, aim_angle):
                    relative_angle = int(aim_angle - angle_round[0])
                    try:
                        angle_list[relative_angle] -= score
                    except:
                        print(k, self.position, enemey.position, bd.position, relative_angle, aim_angle,
                              angle_round)
                else:
                    pass
        score_array = np.array(angle_list, dtype=float)
        min_score = np.min(score_array)
        score_array = score_array + abs(min_score)
        # print (score_array)
        # score_sum = np.sum(score_array)
        # p_array = score_array / score_sum
        # print(score_sum)
        # print(p_array*100)
        # print(np.sum(p_array))
        try:
            angle = np.argmax(score_array)
            # arg_array = np.argsort(score_array)
            # arg_array = arg_array[:5]
            # score_array = score_array[arg_array]
            # score_sum = np.sum(score_array)
            # p_array = score_array / score_sum
            # angle = np.random.choice(a=arg_array, p=p_array)
            # print(score_array,arg_array,p_array)
            # angle = np.random.choice(a=180, p=p_array)
        except:
            print(score_array)
        # print (angle)
        return (angle_round[0] + angle + 360) % 360

    def init_body(self):

        self.score = 30
        self.length = 4
        self.body = []
        for i in range(self.length):
            self.add_body()

    def update(self, dt):

        # print(self.position)
        self.angle = (self.angle + 360) % 360

        arena = self.parent
        if self.is_enemy:
            self.check_crash(arena.snake)
        for s in arena.enemies:
            if s != self and not s.is_dead:
                self.check_crash(s)
        if self.is_dead:
            return

        if abs(self.angle - self.angle_dest) < 2:
            self.angle = self.angle_dest
        else:
            if (0 < self.angle - self.angle_dest < 180) or (
                            self.angle - self.angle_dest < -180):
                self.angle -= 500 * dt
            else:
                self.angle += 500 * dt
        self.head.rotation = -self.angle

        self.x += math.cos(self.angle * math.pi / 180) * dt * self.speed
        self.y += math.sin(self.angle * math.pi / 180) * dt * self.speed
        self.path.append(self.position)

        lag = int(round(1100.0 / self.speed))
        for i in range(int(self.length)):
            idx = (i + 1) * lag + 1
            self.body[i].position = self.path[-min(idx, len(self.path))]
            if self.body[i].x == 0:
                print(self.body[i].position)
        m_l = max(self.length * lag * 2, 60)
        if len(self.path) > m_l:
            self.path = self.path[int(-m_l * 2):]

    def update_angle(self, keys):
        x, y = 0, 0
        if 65361 in keys:  # 左
            x -= 1
        if 65362 in keys:  # 上
            y += 1
        if 65363 in keys:  # 右
            x += 1
        if 65364 in keys:  # 下
            y -= 1
        directs = ((225, 180, 135), (270, None, 90), (315, 0, 45))
        direct = directs[x + 1][y + 1]
        if direct is None:
            self.angle_dest = self.angle
        else:
            self.angle_dest = direct

    def add_score(self, s=1):
        if self.is_dead:
            return
        self.score += s
        l = (self.score - 6) / 6
        if l > self.length:
            self.length = l
            self.add_body()

    def ai(self, dt):

        self.angle_dest = (self.angle_dest + 360) % 360
        if (self.x < 100 and 90 < self.angle_dest < 270) or (
                        self.x > define.WIDTH - 100 and (
                                self.angle_dest < 90 or self.angle_dest > 270)
        ):
            self.angle_dest = 180 - self.angle_dest
        elif (self.y < 100 and self.angle_dest > 180) or (
                        self.y > define.HEIGHT - 100 and self.angle_dest < 180
        ):
            self.angle_dest = -self.angle_dest
        else:
            arena = self.parent
            self.collision_detect(arena.snake)
            for s in arena.enemies:
                if s != self:
                    self.collision_detect(s)

    def collision_detect(self, other):
        if self.is_dead or other.is_dead:
            return
        for b in other.body:
            d_y = b.y - self.y
            d_x = b.x - self.x
            if abs(d_x) > 200 or abs(d_y) > 200:
                return
            if d_x == 0:
                if d_y > 0:
                    angle = 90
                else:
                    angle = -90
            else:
                angle = math.atan(d_y / d_x) * 180 / math.pi
                if d_x < 0:
                    angle += 180
            angle = (angle + 360) % 360
            if abs(angle - self.angle_dest) < 5:
                self.angle_dest += random.randrange(90, 270)

    def check_crash(self, other):
        if self.is_dead or other.is_dead:
            return
        if (self.x < 0 or self.x > define.WIDTH) or (
                        self.y < 0 or self.y > define.HEIGHT
        ):
            self.crash()
            return
        for b in other.body:
            dis = math.sqrt((b.x - self.x) ** 2 + (b.y - self.y) ** 2)
            if dis < 24:
                # other.score += 10
                self.crash()
                return

    def crash(self):
        if not self.is_dead:
            life_time = time.time() - self.birth
            # print(Snake.dead_num%define.DEAD_NUM)
            Snake.times[Snake.dead_num % define.DEAD_NUM] = life_time
            Snake.scores[Snake.dead_num % define.DEAD_NUM] = self.score
            Snake.dead_num += 1
            self.is_dead = True
            self.unschedule(self.update)
            self.unschedule(self.my_ai)
            arena = self.parent
            for b in self.body:
                # dot = Dot(b.position, b.color)
                # arena.batch.add(dot)
                # arena.batch.add(dot)
                # arena.dots.append(dot)
                arena.batch.remove(b)

            arena.remove(self)
            arena.add_enemy()
            del self.path
            # if self.is_enemy:
            arena.enemies.remove(self)
            del self.body
            del self
class Snake(cocos.cocosnode.CocosNode):  # 继承ColorLayer类,实现snake
    def __init__(self, is_enemy=False):  # 初始化并设置状态为玩家
        super(Snake, self).__init__()  # 初始化
        self.is_dead = False  # 初始化状态为存活
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)  # 随机颜色
        if is_enemy:  # 随机怪物位置
            self.position = random.randrange(150,
                                             650), random.randrange(100, 300)
            if 300 < self.x < 500:
                self.x += 200
        else:  # 随机玩家位置
            self.position = random.randrange(350,
                                             450), random.randrange(180, 230)
        self.is_enemy = is_enemy  # 传入状态
        self.head = Sprite('circle.png', color=self.color)  # 设置头的颜色
        self.scale = 1.5  # 设置头的尺寸
        eye = Sprite('circle.png')  # 设置眼睛
        eye.y = 5  # 设置眼睛的Y轴
        eye.scale = 0.5  # 设置眼睛的尺寸
        eyeball = Sprite('circle.png', color=define.BLACK)  # 设置眼球的颜色
        eyeball.scale = 0.5  # 设置眼球的尺寸
        eye.add(eyeball)  # 在眼睛中添加眼球
        self.head.add(eye)  # 在头中添加眼睛
        eye = Sprite('circle.png')  # 设置眼睛
        eye.y = -5  # 设置眼睛的Y轴
        eye.scale = 0.5  # 设置眼睛的尺寸
        eyeball = Sprite('circle.png', color=define.BLACK)  # 设置眼球的颜色
        eyeball.scale = 0.5  # 设置眼球的尺寸
        eye.add(eyeball)  # 在眼睛中添加眼球
        self.head.add(eye)  # 设置眼睛

        self.add(self.head)  # 把头添加进身体

        self.speed = 200  # 设置怪物速度
        if not is_enemy:  # 设置玩家速度
            self.speed = 150
        self.path = [self.position] * 100  # 用一个列表记录蛇头经过的位置,身子则根据路径中对应数据更新位置

        self.schedule(self.update)  # 在时间安排表中加入snake的更新
        if self.is_enemy:  # 更新怪物
            self.schedule_interval(self.ai, random.random() * 0.1 + 0.05)

    def add_body(self):  # 添加进身体
        b = Sprite('circle.png', color=self.color)  # 设置颜色
        b.scale = 1.5  # 设置尺寸
        self.body.append(b)  # 添加进身体
        b.position = self.position  # 传入位置
        self.parent.batch.add(b, 9999 - len(self.body))  # 添加进batch为后续更新

    def init_body(self):  # 初始化身体
        self.score = 30  # 初始化得分
        self.length = 4  # 初始化长度
        self.body = []  # 初始化身体的构成
        for i in range(self.length):  # 添加进身体
            self.add_body()

    def update(self, dt):  # 更新
        self.angle = (self.angle + 360) % 360  # 加360取模,保证为正角度

        arena = self.parent  # 传入arena
        if self.is_enemy:  # 若为怪物则检查是否发生碰撞
            self.check_crash(arena.snake)
        for s in arena.enemies:  # 检查是否与怪物发生碰撞
            if s != self and not s.is_dead:
                self.check_crash(s)
        if self.is_dead:  # 发生碰撞则返回
            return

        if abs(self.angle - self.angle_dest) < 2:  # 角度差很小则直接更新为按键方向
            self.angle = self.angle_dest
        else:
            if (0 < self.angle - self.angle_dest <
                    180) or (self.angle - self.angle_dest <
                             -180):  # 改变的方向与原方向夹角小于180或大于-180
                self.angle -= 500 * dt  # 方向改变速率,dt为两次update之间的间隔时间(schedule中设定)
            else:  # 改变的方向与原方向夹角大于180或大于-180
                self.angle += 500 * dt  # 方向改变速率,dt为两次update之间的间隔时间(schedule中设定)
        self.head.rotation = -self.angle  # 头旋转的角度要匹配转动的方向

        self.x += math.cos(
            self.angle * math.pi / 180) * dt * self.speed  # 更新X轴位置
        self.y += math.sin(
            self.angle * math.pi / 180) * dt * self.speed  # 更新Y轴位置
        self.path.append(self.position)  # 将更新好的位置添加进记录path的列表

        lag = int(round(1100.0 / self.speed))  # 设置更新身体的延迟(四舍五入)
        for i in range(int(self.length)):  # 依次更新记录身体位置的列表
            idx = (i + 1) * lag + 1  # 第i个部位的偏移
            self.body[i].position = self.path[-min(idx, len(
                self.path))]  # 将蛇身的位置根据蛇头经过的路径依次更新,取小的目的为防止越界
        m_l = max(self.length * lag * 2, 60)  # 对当前长度在数据更新过程中可能的最大长度
        if len(self.path) > m_l:  # 拓展列表空间以保存更多数据
            self.path = self.path[int(-m_l * 2):]  # 扩大1倍

    def update_angle(self, keys):  # 更新运动角度
        x, y = 0, 0
        if 65361 in keys:  # 左
            x -= 1
        if 65362 in keys:  # 上
            y += 1
        if 65363 in keys:  # 右
            x += 1
        if 65364 in keys:  # 下
            y -= 1
        directs = ((225, 180, 135), (270, None, 90), (315, 0, 45))  # 不同的角度
        direct = directs[x + 1][y + 1]  # 角度合成
        if direct is None:  # 方向不变
            self.angle_dest = self.angle
        else:
            self.angle_dest = direct

    def add_score(self, s=1):  # 添加得分
        if self.is_dead:  # 已经死了则返回
            return
        self.score += s  # 加分
        l = (self.score + 2) / 8  # 每多8分长度加1
        if l > self.length:
            self.length += 1
            self.add_body()

    def ai(self, dt):  # 怪物的转向
        self.angle_dest = (self.angle_dest + 360) % 360  # 加360取模,保证为正角度
        if (self.x < 100 and 90 < self.angle_dest < 270) or (
                self.x > define.WIDTH - 100 and
            (self.angle_dest < 90
             or self.angle_dest > 270)):  # 怪物即将与左右边框发生撞墙则转向
            self.angle_dest = 180 - self.angle_dest
        elif (self.y < 100 and self.angle_dest > 180) or (
                self.y > define.HEIGHT - 100
                and self.angle_dest < 180):  # 怪物即将与上下边框发生撞墙则转向
            self.angle_dest = -self.angle_dest
        else:
            arena = self.parent  # 传入arena
            self.collision_detect(arena.snake)  # 怪物面对玩家的躲避检测
            for s in arena.enemies:  # 怪物间的躲避检测
                if s != self:
                    self.collision_detect(s)

    def collision_detect(
        self, other
    ):  # 躲避检测,对于在头部范围内的其他蛇身,计算蛇身与蛇头连线的角度,和自身的运动方向进行比较,如果角度相差很小,就意味着会撞上,于是调整当前运动方向。
        if self.is_dead or other.is_dead:  # 两条蛇中有一个已经死了则返回
            return
        for b in other.body:  # 两者的距离
            d_y = b.y - self.y
            d_x = b.x - self.x
            if abs(d_x) > 300 or abs(d_y) > 300:  # 距离足够大则安全
                return
            if d_x == 0:  # 两者位于同一X上(此时夹角的tan不存在,所以需要特判)
                if d_y > 0:
                    angle = 90
                else:
                    angle = -90
            else:
                angle = math.atan(d_y / d_x) * 180 / math.pi  # 计算夹角
                if d_x < 0:
                    angle += 180
            angle = (angle + 360) % 360  # 加360取模,保证为正角度
            if abs(angle -
                   self.angle_dest) < 5:  # 蛇身和蛇头的角度和运动方向角度相差很小说明可能发生碰撞则转向
                self.angle_dest += random.randrange(90, 270)

    def check_crash(self, other):  # 玩家与怪物碰撞检测
        if self.is_dead or other.is_dead:  # 两者中有一个已经死了则返回
            return
        if (self.x < 0 or self.x > define.WIDTH) or (
                self.y < 0 or self.y > define.HEIGHT):  # 撞墙则死亡
            self.crash()
            return
        for b in other.body:  # 根据两者的直线距离判断是否发生了碰撞
            dis = (b.x - self.x)**2 + (b.y - self.y)**2
            if dis < 576:  # 距离小于24则发生碰撞
                self.crash()
                return

    def crash(self):  # 碰撞处理
        if not self.is_dead:
            self.is_dead = True  # 状态设定为死亡
            self.unschedule(self.update)  # 在时间安排表中移除更新
            self.unschedule(self.ai)  # 在时间安排表中移除怪物
            arena = self.parent  # 传入arena
            for b in self.body:  # 分解身体为Dot
                arena.batch.add(Dot(b.position, b.color))
                arena.batch.add(Dot(b.position, b.color))
                arena.batch.remove(b)  # 从batch中移除

            arena.remove(self)  # 从arena中移除
            arena.add_enemy()  # 重新添加新的怪物
            del self.path  # 删除记录的路径
            if self.is_enemy:  # 死的是怪物
                arena.enemies.remove(self)  # 从enemies中移除
                del self.body  # 删除
                del self
            else:
                arena.parent.end_game()  # 死的是玩家则游戏结束
Exemple #22
0
    def __init__(self, is_enemy=False):
        super(Snake, self).__init__()
        Snake.snake_num += 1
        self.birth = time.time()
        self.is_dead = False
        self.angle = random.randrange(360)  # 目前角度
        self.angle_dest = self.angle  # 目标角度
        self.color = random.choice(define.ALL_COLOR)
        if is_enemy:
            self.position = random.randrange(300, 1300), random.randrange(200, 600)
            if 600 < self.x < 1000:
                self.x += 400
                # else:
                #     self.position = random.randrange(700, 900), random.randrange(350, 450)
        self.is_enemy = True
        self.head = Sprite('circle.png', color=self.color)
        self.scale = 1.5
        self.score = 0
        eye = Sprite('circle.png')
        eye.y = 5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)
        eye = Sprite('circle.png')
        eye.y = -5
        eye.scale = 0.5
        eyeball = Sprite('circle.png', color=define.BLACK)
        eyeball.scale = 0.5
        eye.add(eyeball)
        self.head.add(eye)

        self.add(self.head)

        self.speed = 140
        self.path = [self.position] * 100

        # with open("generation"+str(current_gen)+".ini", 'r') as r:
        #     data = r.read()
        current_gen = Snake.snake_num / define.POP_SIZE
        if Snake.snake_num - 9 >= 0:
            current_gen = (Snake.snake_num - 9) / define.POP_SIZE
        print ("snakenum", Snake.snake_num)
        print("currentgen", current_gen)
        print("genelist len", len(Snake.gene_list))
        if len(Snake.gene_list) == 0:
            print("genelist", Snake.gene_list)
            with open("generation" + str(current_gen) + ".ini", "r") as r:
                data = r.read()
            Snake.gene_list = (data.split("\n"))
            if current_gen == 0:
                Snake.curr_gens = Snake.gene_list[7:]
            else:
                Snake.curr_gens = Snake.gene_list[:]
            print("currgens", Snake.curr_gens)
            print("currgens len", len(Snake.curr_gens))
        self.threhold, self.hunger, self.alive = translateDNA([Snake.gene_list.pop()])

        if Snake.dead_num != 0 and Snake.dead_num % define.DEAD_NUM == 0:
            fitness = get_fitness(Snake.scores, Snake.times)
            pop = select(Snake.curr_gens, fitness)
            pop_copy = pop[:]
            # print("pop", pop)
            # print("pop copy", pop_copy)
            # print("pop copy", pop_copy.ndim)
            data = []
            for parent in pop:
                child = crossover(parent, pop_copy)
                child = mutate(child)
                temp = [str(i) for i in child]
                data.append(''.join(temp))
            with open("generation" + str(current_gen + 1) + ".ini", 'a') as w:
                w.write('\n'.join(data))

        self.schedule(self.update)
        self.schedule(self.my_ai)  # random.random() * 0.1 + 0.05
	def add_image_sprite(self):

		print("ImageLayer.add_image_layer()")

		pil = PIL.Image.open(self.image_file)
		pyglet_img = pyglet.image.load(self.image_file)
		target_w = self.window_width
		target_h = self.window_height
		orig_w = pil.size[0]
		orig_h = pil.size[1]

		id = self.next_id
		print(pil)

		( xscale, yscale,
		  result_w, result_h, dx, dy ) = SizeFitting.scaleToSize(
										 orig_w, orig_h,
				                         target_w, target_h,
		                                 FitType.ScaleFitAspectFit)
		imgsprite = Sprite(pyglet_img)
		imgsprite.anchor = (0, 0)
		imgsprite.transform_anchor = (result_w/2, result_h/2)

		bg_w = int(float(target_w) / xscale)
		bg_h = int(float(target_h) / yscale)

		background = SolidColorImagePattern(
			color=self.color_black
		).create_image(width=bg_w, height=bg_h)

		bgsprite = Sprite(background)
		bgsprite.add(imgsprite, z=id, name="image%d" % id)
		bgsprite.anchor = (0, 0)
		bgsprite.scale = xscale


		self.add(bgsprite, z=id, name="spritelayer%d" % id)


		self.animate(bgsprite, imgsprite)


		## !!! CENTERING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		self.position = (target_w/2, target_h/2)
		## Remove the lign below to center on display (as oppposed to anchoing at (0,0)
#		imgsprite.position = (-(target_w-result_w)/2/xscale, -(target_h-result_h)/2/yscale )

		## !!!!!!!!!!!!!!
		##############

		########## DEBUG
		bg = bgsprite
		lists = [ "orig_w result_w bg_w target_w xscale".split(" "),
		          "orig_h result_h bg_h target_h yscale".split(" "),
		          "bg.width bg.height bg.anchor bg.transform_anchor".split(" "),
		          "self.position self.get_local_transform() self.get_world_transform()".split(" ")
				]
		debug = "id: %2d " %id
		for list in lists:
			debug += "\n"
			for  key in list:
				debug += "{k:>5}: {v:>4}  ".format(k=key, v=eval(key))
		print debug