Example #1
0
    def collide(self, bird):
        bird_mask = bird.get_mask()
        top_mask = mask.from_surface(self.PIPE_TOP)
        bottom_mask = mask.from_surface(self.PIPE_BOTTOM)

        top_offset = (self.x - bird.x, self.top - round(bird.y))
        bottom_offset = (self.x - bird.x, self.bottom - round(bird.y))

        t_point = bird_mask.overlap(top_mask, top_offset)
        b_point = bird_mask.overlap(bottom_mask, bottom_offset)

        if t_point or b_point:
            return True

        return False
Example #2
0
    def collides_with(self, bird):
        bird_mask = bird.get_mask()
        top_mask = from_surface(self.PIPE_TOP)
        bot_mask = from_surface(self.PIPE_BOT)

        top_offset = (self.x - bird.x, self.top - round(bird.y))
        bot_offset = (self.x - bird.x, self.bot - round(bird.y))

        top_collision = bird_mask.overlap(top_mask, top_offset)
        bot_collision = bird_mask.overlap(bot_mask, bot_offset)

        if top_collision or bot_collision:
            return True
        else:
            return False
Example #3
0
 def __init__(self,
              tag,
              initial_position,
              rotation=0,
              fontname='fonts/Arial.ttf',
              fontzoom=5):
     Sprite.__init__(self)
     self.tag = tag
     self.rotation = rotation
     fonter = font.Font(fontname, int(tag['size'] * fontzoom)).render(
         tag['tag'], True, tag['color'])
     self.tag['size'] *= fontzoom
     fonter = transform.rotate(fonter, rotation)
     frect = fonter.get_bounding_rect()
     frect.x = -frect.x
     frect.y = -frect.y
     self.fontoffset = (-frect.x, -frect.y)
     font_sf = Surface((frect.width, frect.height), pygame.SRCALPHA, 32)
     font_sf.blit(fonter, frect)
     self.image = font_sf
     self.rect = font_sf.get_rect()
     self.rect.width += TAG_PADDING
     self.rect.height += TAG_PADDING
     self.rect.x = initial_position[0]
     self.rect.y = initial_position[1]
     self.mask = mask.from_surface(self.image)
     self.mask = self.mask.convolve(CONVMASK, None,
                                    (TAG_PADDING, TAG_PADDING))
Example #4
0
    def __init__(self,x,y,image_name):
        from TT import SCREEN_WIDTH,SCREEN_HEIGHT,archive,Load_Image_From_Zip
        sprite.Sprite.__init__(self)
        

        self.initialX = x
        self.initialY = y

        self.initial_image = transform.scale(Load_Image_From_Zip(archive,image_name),[int(SCREEN_WIDTH / 35.025),int(SCREEN_HEIGHT / 11.636)])
        self.Image = self.initial_image
        self.width = self.initial_image.get_width()
        self.height = self.initial_image.get_height()
        self.mask = mask.from_surface(self.Image)
        self.rect = self.Image.get_rect(center = (x + self.width / 2,y + self.height / 2))
        self.center = self.rect.center
        self.Xmage = Surface([0, 0]).convert_alpha()

        self.dx = 0
        self.dy = Tank.Speed
    

        self.stuck = False
        self.health = 3
        self.bullet_sprites = sprite.Group()

        self.speed_boosted = False
        self.health_boosted = False
Example #5
0
 def __init__(self, anim, start_pos, angle, power):
     super(Projectile, self).__init__(None, 5)
     self.curr_anim = anim
     self.image = self.curr_anim.next()
     self.mask = mask.from_surface(self.image)
     self.rect = self.image.get_rect(midbottom=start_pos)
     self.vel = -power * Vector2(cos(angle), sin(angle))
Example #6
0
 def __init__(self, res_container: ResourceContainer,
              enemy_data: EnemyData):
     super().__init__(res_container, enemy_data)
     self.radius = 80
     self._damage = 0.5
     self.invulnerable_start = 0
     self.mask = mask.from_surface(self.image)
Example #7
0
    def change_size(self, new_width):
        """
        Function used to change the size of the palette. Rebuilds image from source and
        generates new collision Rect
        :param new_width: new Paddle width in pixels (min. 22px)
        :return:
        """
        paddleAsset = Assets.paddles[self.paddle_color]
        new_width = max(new_width, 22)  # 22 = (border(8) + colorbar(3))*2
        paddle_mid = Surface((38, 15))  # (2*paddle.rect.width, paddle.rect.height))
        # paddle_mid.blit(self.image, (0, 0), Rect(11, 0, 38, 15))
        paddle_mid.blit(paddleAsset, (0, 0), Rect(11, 0, 38, 15))
        paddle_mid = transform.scale(paddle_mid, (new_width-22, self.rect.height))
        new_paddle = Surface((new_width, self.rect.height), SRCALPHA)  # blank surface
        # new_paddle.fill(pygame.Color(0, 0, 0, 0), new_paddle.get_rect())
        new_paddle.blit(paddle_mid, (11, 0))
        new_paddle.blit(paddleAsset, (0, 0), Rect(0, 0, 11, 15))
        new_paddle.blit(paddleAsset, (new_width - 11, 0),
                        Rect(paddleAsset.get_rect().width - 11, 0, 11, 15))
        paddle_new_x = self.rect.x + self.rect.width/2 - new_paddle.get_rect().width/2
        self.rect = Rect(paddle_new_x, self.rect.y, new_paddle.get_rect().width,
                         new_paddle.get_rect().height)
        self.mask = mask.from_surface(new_paddle)
        self.image = new_paddle
        self.attachment_points[1] = (self.rect.width-8, 0)
        # self.paddle.attachment_points[1] =

        if self.rect.x <= PLAYFIELD_PADDING[0]:
            self.rect.x = PLAYFIELD_PADDING[0] + 1
        elif self.rect.x + self.rect.width >= LEVEL_WIDTH - PLAYFIELD_PADDING[0]:
            self.rect.x = LEVEL_WIDTH - PLAYFIELD_PADDING[0] - self.rect.width - 1
Example #8
0
 def __init__(self, x, y, paddle_color, parent=None, owner=None):
     """
     Initialize it with spawn position
     :param x: x coordinate of the play-field
     :param y: y coordinate of the play-field
     :param paddle_color:
     :param parent: ?
     :param owner: ?
     :return:
     """
     Sprite.__init__(self)
     self.vx = 0
     self.vy = 0
     self.speed = 10
     self.paddle_color = paddle_color
     self.image = Assets.paddles[paddle_color]  # pygame.image.load("gfx/paddle.png")
     self.mask = mask.from_surface(self.image)
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.attachment_points = [(8, 0), (self.rect.width-8, 0)]
     self.attachments = []
     # self.attachments = [LaserGunAttachment(self)]
     self.parent = parent
     self.owner = owner
Example #9
0
    def __init__(self, points, color, *groups):
        super().__init__()

        self.dirty = 2
        self._layer = constants.LAYER_GROUND
        self.add(*groups)

        self.points = points
        self.origin = Point(min([p.x for p in points]),
                            min([p.y for p in points]))

        self.width = max([p.x for p in points]) - self.origin.x
        self.height = max([p.y for p in points]) - self.origin.y
        self.color = color

        self.image = PyGameSurface((
            self.width,
            self.height,
        ))
        self.image.set_colorkey(colors.BLACK)

        self.rect = Rect(self.origin.x, self.origin.y, self.width, self.height)

        self.update()

        # Make sure we don't try to make a mask from a 1-D image.
        if self.width * self.height == 0:
            raise ValueError()

        self.mask = mask.from_surface(self.image)
Example #10
0
class Red(Rect,object):
    
    
    class Bullet(Rect,object):
        
        img     = image.load('img/redbullet.png')
        rect    = img.get_rect()
        msk     = mask.from_surface(img,0)
        pow     = 10
        
        def __init__(self,midbottom):
            Rect.__init__(self,self.rect)
            self.midbottom  = midbottom
        
        def update(self):
            self.y += 10
        
        def render(self):
            bulletlayer.blit(self.img,self)
    
    img     = image.load('img/square.png')
    img2    = image.load('img/square2.png')
    msk     = mask.from_surface(img,0)
    
    def __init__(self,x,y):
        Rect.__init__(self,Red.img.get_rect(midbottom=(x,y)))
        self.axe        = x
        self.X, self.Y  = self.midbottom
        self.tau        = 0
        self.shield_    = 30
        self.foo        = 0
        self.tick       = 0
    
    def update(self):
        self.tick += 1
        self.tau += 1.8
        self.X = self.axe+sin(radians(self.tau))*80
        self.Y += 0.5
        self.midbottom = self.X, self.Y
        if self.left<ship.centerx<self.right and self.tick>=50:
            shotenemi.append(Red.Bullet(self.midbottom))
            self.tick = 0
    
    def render(self):
        if self.foo:
            self.foo -= 1
            scr.blit(Red.img2,self)
            return
        scr.blit(Red.img,self)

    @property
    def shield(self):
        return self.shield_

    @shield.setter
    def shield(self,n):
        self.shield_ = n
        self.foo = 5
        if n<0:
            explosion.update(explosion.Particles,self,(250,100,50),60,30)
Example #11
0
File: Wall.py Project: zbmott/golf
    def __init__(self, point1, point2, width=5, *groups):
        super().__init__()

        self.dirty = 2
        self._layer = constants.LAYER_WALL
        self.add(*groups)

        self.points = [point1, point2]
        self.width = width

        # This sprite's origin on the application's screen.
        # Necessary to draw the sprite correctly, as well as to calculate
        # collision rectangles correctly.
        self.origin = Point(min(point1.x, point2.x), min(point1.y, point2.y))

        self.point1 = point1 - self.origin
        self.point2 = point2 - self.origin

        v = math.Vector2(*(point2 - point1).as_2d_tuple())
        self.reflect_vector = math.Vector2(-1 * v.y, v.x)

        self.image = Surface((
            abs(point2.x - point1.x) + self.width,
            abs(point2.y - point1.y) + self.width
        ))
        self.image.set_colorkey(colors.BLACK)

        self.rect = self.image.get_rect()
        self.rect.x = self.origin.x
        self.rect.y = self.origin.y

        self.update()
        self.mask = mask.from_surface(self.image)
Example #12
0
    def __init__(self, image, position):
        pygame.sprite.Sprite.__init__(self)

        self.image = image
        self.rect = self.image.get_rect()
        self.mask = from_surface(self.image)
        self.rect.left, self.rect.top = position
Example #13
0
 def text(self, value):
     self._text = value
     self.image = self._render(value)
     self.rect = Rect((self.rect[0], self.rect[1]), self.image.get_rect()[2:])
     self.col_rect = self.rect.copy()
     self.mask = mask.from_surface(self.image)
     self.create_feet()
Example #14
0
 def __init__(self, tag, initial_position, rotation=0, fontname=DEFAULT_FONT, fontzoom=5):
     Sprite.__init__(self)
     self.tag = copy(tag)
     self.rotation = rotation
     
     font_spec = load_font(fontname)
     
     #fonter = font.Font(os.path.join(FONT_DIR, font_spec['ttf']), int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color'])
     # changing to allow for arbitrary local fonts
     fonter = font.Font(font_spec['ttf'], int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color'])
     self.tag['size'] *= fontzoom
     fonter = transform.rotate(fonter, rotation)
     frect = fonter.get_bounding_rect()
     frect.x = -frect.x
     frect.y = -frect.y
     self.fontoffset = (-frect.x, -frect.y)
     font_sf = Surface((frect.width, frect.height), pygame.SRCALPHA, 32)
     font_sf.blit(fonter, frect)
     self.image = font_sf
     self.rect = font_sf.get_rect()
     self.rect.width += TAG_PADDING
     self.rect.height += TAG_PADDING
     self.rect.x = initial_position[0]
     self.rect.y = initial_position[1]
     self.mask = mask.from_surface(self.image)
     self.mask = self.mask.convolve(CONVMASK, None, (TAG_PADDING, TAG_PADDING))
Example #15
0
    def test_from_surface(self):
        """  Does the mask.from_surface() work correctly?
        """

        mask_from_surface = mask.from_surface

        surf = surface.Surface((70, 70), SRCALPHA, 32)

        surf.fill((255, 255, 255, 255))

        amask = mask.from_surface(surf)
        #amask = mask_from_surface(surf)

        self.assertEqual(amask.get_at((0, 0)), 1)
        self.assertEqual(amask.get_at((66, 1)), 1)
        self.assertEqual(amask.get_at((69, 1)), 1)

        surf.set_at((0, 0), (255, 255, 255, 127))
        surf.set_at((1, 0), (255, 255, 255, 128))
        surf.set_at((2, 0), (255, 255, 255, 0))
        surf.set_at((3, 0), (255, 255, 255, 255))

        amask = mask_from_surface(surf)
        self.assertEqual(amask.get_at((0, 0)), 0)
        self.assertEqual(amask.get_at((1, 0)), 1)
        self.assertEqual(amask.get_at((2, 0)), 0)
        self.assertEqual(amask.get_at((3, 0)), 1)

        surf.fill((255, 255, 255, 0))
        amask = mask_from_surface(surf)
        self.assertEqual(amask.get_at((0, 0)), 0)
Example #16
0
    def test_from_surface(self):
        """  Does the mask.from_surface() work correctly?
        """

        mask_from_surface = mask.from_surface

        surf = surface.Surface((70,70), SRCALPHA, 32)

        surf.fill((255,255,255,255))

        amask = mask.from_surface(surf)
        #amask = mask_from_surface(surf)

        self.assertEqual(amask.get_at((0,0)), 1)
        self.assertEqual(amask.get_at((66,1)), 1)
        self.assertEqual(amask.get_at((69,1)), 1)

        surf.set_at((0,0), (255,255,255,127))
        surf.set_at((1,0), (255,255,255,128))
        surf.set_at((2,0), (255,255,255,0))
        surf.set_at((3,0), (255,255,255,255))

        amask = mask_from_surface(surf)
        self.assertEqual(amask.get_at((0,0)), 0)
        self.assertEqual(amask.get_at((1,0)), 1)
        self.assertEqual(amask.get_at((2,0)), 0)
        self.assertEqual(amask.get_at((3,0)), 1)

        surf.fill((255,255,255,0))
        amask = mask_from_surface(surf)
        self.assertEqual(amask.get_at((0,0)), 0)
Example #17
0
	def collides(self,monster):
		"""
			Checks if the monster collides with a specific monster
		"""
		if self.rect.colliderect(monster.rect):
			#Here need to pix perfect collision
 			trectmonst = self.rect.clip(monster.rect).move(-monster.rect.x,-monster.rect.y)
 			trectstick = self.rect.clip(monster.rect).move(-self.rect.x,-self.rect.y)

			tmonstmask = mask.from_surface(monster.image.subsurface(trectmonst))
 			tcurrentmask = mask.from_surface(self.image.subsurface(trectstick))

			col = tcurrentmask.overlap(tmonstmask,(0,0))
                	if col == None: return False,0,0
                	else: return True,col[0]+self.rect.x,col[1]+self.rect.y

		else: return False,0,0
Example #18
0
 def flip(self):
     pos = (self.rect.x, self.rect.y)
     angle = 90 if self.rotation == 0 else - 90
     self.image = transform.rotate(self.image, angle)
     self.rect = self.image.get_rect()
     self.rect.x, self.rect.y = pos
     self.mask = mask.from_surface(self.image)
     self.mask = self.mask.convolve(CONVMASK, None, (TAG_PADDING, TAG_PADDING))
Example #19
0
 def __init__(self, game, pos, direction, speed=4):
     Sprite.__init__(self)
     self.game = game
     self.image = game.get_tile_surface('b.dot')
     self.mask = mask.from_surface(self.image)
     self.pos = Vector(pos)
     self.direction = direction
     self.speed = speed
 def map_collision(self, mapp, obj_rect, obj_mask):
     """Return True if map and object collide"""
     surf_map = Surface((obj_rect.width, obj_rect.height),
                        pygame.SRCALPHA)
     surf_map.blit(mapp.collision_text, (0, 0), obj_rect)
     mask_map = mask.from_surface(surf_map)
     if mask_map.overlap(obj_mask, (0, 0)) is not None:
         return True
     return False
Example #21
0
 def __init__(self, game):
     Sprite.__init__(self)
     self.game = game
     self.image = game.get_tile_surface('rot.hoch')
     self.mask = mask.from_surface(self.image)
     self.g = Group(self)
     self.pos = Vector(300, 510)
     self.speed = 4
     self.direction = RIGHT
Example #22
0
 def flip(self):
     pos = (self.rect.x, self.rect.y)
     angle = 90 if self.rotation == 0 else -90
     self.image = transform.rotate(self.image, angle)
     self.rect = self.image.get_rect()
     self.rect.x, self.rect.y = pos
     self.mask = mask.from_surface(self.image)
     self.mask = self.mask.convolve(CONVMASK, None,
                                    (TAG_PADDING, TAG_PADDING))
Example #23
0
 def __init__(self, sprite_filename, speed):
 
     Sprite.__init__(self)
     
     self.image = pygame.image.load(sprite_filename).convert_alpha()
     self.rect = self.image.get_rect()
     self.mask = mask.from_surface(self.image)
     
     self.speed = speed
Example #24
0
 def __init__(self, topleft: Tuple[int, int], size: Tuple[int, int],
              id_: int, *groups):
     super().__init__(*groups)
     self.image = Surface(size)
     self.rect = self.image.get_rect()
     self.rect.topleft = topleft
     self.mask = mask.from_surface(self.image)
     self.mask.fill()
     self.id = id_
Example #25
0
    def __init__(self, sprite_filename, speed):

        Sprite.__init__(self)

        self.image = pygame.image.load(sprite_filename).convert_alpha()
        self.rect = self.image.get_rect()
        self.mask = mask.from_surface(self.image)

        self.speed = speed
Example #26
0
    def __init__(self,own_tank):
        from TT import SCREEN_WIDTH,SCREEN_HEIGHT,archive,Load_Image_From_Zip

        sprite.Sprite.__init__(self)
        self.initial_image = transform.scale(Load_Image_From_Zip(archive,"pictures/bullet.png"),[int(SCREEN_WIDTH/195.14),int(SCREEN_HEIGHT/76)])
        self.image = self.initial_image 
        self.mask = mask.from_surface(self.image)
        self.rect = self.image.get_rect(center = own_tank.rect.center)

        self.situation = "stop"
Example #27
0
    def collide(self, bird):
        # getting the mash for the bird
        bird_mask = bird.get_mask()
        # creating the mask for our pipes
        top_mask = from_surface(self.PIPE_TOP)
        bottom_mask = from_surface(self.PIPE_BOTTOM)

        # offset means the distance between the masks
        top_offset = (self.x - bird.x, self.top - round(bird.y))
        bottom_offset = (self.x - bird.x, self.bottom - round(bird.y))

        # finding if the masks collide i.e. finding the point of collision,
        # returns None if no collision
        b_point = bird_mask.overlap(bottom_mask, bottom_offset)
        t_point = bird_mask.overlap(top_mask, top_offset)

        if t_point or b_point:
            return True
        return False
	def collide(self, group):
		if self.sprite.maskDirty:
			self.sprite.maskDirty = False
			AVRSprite.spriteLock.acquire()
			self.sprite.mask = mask.from_surface(self.transformedSurface)
			AVRSprite.spriteLock.release()
		
		sprites = sprite.spritecollide(self.sprite, group.group, False)
		results = []
		for s in sprites:
			if s == self.sprite:
				continue
			if s.maskDirty:
				s.maskDirty = False
				AVRSprite.spriteLock.acquire()
				s.mask = mask.from_surface(s.AVRSprite.transformedSurface)
				AVRSprite.spriteLock.release()
			if sprite.collide_mask(self.sprite, s) != None:
				results.append(s.AVRSprite.handle)
		return results
Example #29
0
    def collide(self, group):
        if self.sprite.maskDirty:
            self.sprite.maskDirty = False
            AVRSprite.spriteLock.acquire()
            self.sprite.mask = mask.from_surface(self.transformedSurface)
            AVRSprite.spriteLock.release()

        sprites = sprite.spritecollide(self.sprite, group.group, False)
        results = []
        for s in sprites:
            if s == self.sprite:
                continue
            if s.maskDirty:
                s.maskDirty = False
                AVRSprite.spriteLock.acquire()
                s.mask = mask.from_surface(s.AVRSprite.transformedSurface)
                AVRSprite.spriteLock.release()
            if sprite.collide_mask(self.sprite, s) != None:
                results.append(s.AVRSprite.handle)
        return results
Example #30
0
    def __init__(self, *groups):
        super().__init__(*groups)

        self.dirty = 2

        self.image = image.load(self.IMAGE_PATH)
        self.image.convert_alpha()

        self.mask = mask.from_surface(self.image)

        self.rect = self.image.get_rect()
Example #31
0
class SMAlien(Rect, object):
    """The black aliens"""

    #img = image.load('img/space11.png')
    img = image.load(os.path.join(maindir, 'img/space11.png'))
    msk = mask.from_surface(img, 1)

    class Bullet(Rect, object):

        #img = image.load('img/oursin.png')
        img = image.load(os.path.join(maindir, 'img/oursin.png'))
        rect = img.get_rect()
        pow = 5

        def __init__(self, midbottom):
            Rect.__init__(self, self.rect)
            self.midbottom = midbottom
            self.dx = random() - 0.5
            self.X = self.x
            self.dy = 4 + random()
            self.Y = self.y

        def update(self):
            self.Y += self.dy
            self.X += self.dx
            self.x = int(self.X)
            self.y = int(self.Y)

        def render(self):
            scr.blit(self.img, self)

    def __init__(self, x, y):
        Rect.__init__(self, self.img.get_rect(midbottom=(x, y)))
        self.axe = x
        self.X, self.Y = self.midbottom
        self.tau = 0
        self.tick = 0
        self.shield = 1

    def update(self):
        self.tick += 1
        self.tau += 1.8
        self.X = self.axe + sin(radians(self.tau)) * 300
        self.Y += 0.5
        self.midbottom = self.X, self.Y

        if self.left < ship.centerx < self.right and self.tick >= 10:
            shotenemi.append(self.Bullet(self.midbottom))
            shotenemi.append(self.Bullet(self.midbottom))
            shotenemi.append(self.Bullet(self.midbottom))
            self.tick = 0

    def render(self):
        scr.blit(self.img, self)
Example #32
0
 def __init__(self, x, y, w, h):
     Sprite.__init__(self)
     self.image = Surface((w, h), SRCALPHA, 32)        
     self.image.fill((255,0,0))
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.mask = mask.from_surface(self.image)
     
     self.border = Surface((self.rect.width, self.rect.height), SRCALPHA, 32)        
     pygame.draw.rect(self.border, (255, 0, 0), Rect(0 , 0, self.rect.width , self.rect.height), 1)
Example #33
0
	def GetRotatedCopy(self, angle):

		rotatedCopy = copy(self)

		rotatedCopy._surfaces = [transform.rotate(surface, angle) for surface in rotatedCopy._surfaces]
		rotatedCopy._masks = [mask.from_surface(surface) for surface in self._surfaces]

		if rotatedCopy._shadows:
			rotatedCopy._shadows = None
			rotatedCopy.CreateShadow()

		return rotatedCopy
Example #34
0
    def rotate(self,angle):

        rotated_surface = transform.rotozoom(self.initial_image,angle,1).convert_alpha()
        rotated_rect = rotated_surface.get_rect(center = self.rect.center)

        self.Image = rotated_surface
        self.rect = rotated_rect     
       
        self.dx = Tank.Speed * math.sin(math.radians(-angle))
        self.dy = Tank.Speed * math.cos(math.radians(-angle))

        self.mask = mask.from_surface(self.Image)
Example #35
0
	def GetScaledCopy(self, dimensions):

		scaledCopy = copy(self)

		scaledCopy._surfaces = [InterpolateToDimensions(surface, dimensions) for surface in scaledCopy._surfaces]
		scaledCopy._masks = [mask.from_surface(surface) for surface in self._surfaces]

		if scaledCopy._shadows:
			scaledCopy._shadows = None
			scaledCopy.CreateShadow()

		return scaledCopy
Example #36
0
    def __init__(self, position, speed, look=1, target=None):
        """ Create and aim bullet

        Target angle is -90 left, 0 straight down, 90 right
        :param position: Starting position: Sprite or [x, y]
        :param gfx: game graphics lib
        :param speed: speed of the bullet
        :param look: index of the bullet image
        :param target: Target to aim at None/int angle/[x,y]
        """
        super(EnemyBullet, self).__init__()

        # Set selected image, mask and rect
        self.image = GFX().bullets[look]
        self.mask = GFX().bullets_mask[look]
        self.rect = self.image.get_rect()

        # Set starting position
        if isinstance(position, Sprite):
            self.rect.centerx = position.rect.centerx
            self.rect.bottom = position.rect.bottom
        else:
            self.rect.centerx = position[0]
            self.rect.centery = position[1]

        # Attributes
        self.pos_x = float(self.rect.x)
        self.pos_y = float(self.rect.y)
        self.speedx = 0
        self.speedy = 0
        self.angle = 0

        if target is None:
            self.speedy = speed
        else:
            if isinstance(target, list):
                # Calculate angle to target
                self.angle = rt_angle(target[0] - self.rect.x,
                                      target[1] - self.rect.y)
            else:
                self.angle = target

            # Rotate bullet image
            if self.angle != 0:
                self.image = rotate(self.image, self.angle)
                self.mask = from_surface(self.image)
                self.rect = self.image.get_rect()

            # Perform vectoring based on angle
            self.angle += 90
            self.angle = radians(self.angle)
            self.speedx = cos(self.angle) * speed * -1
            self.speedy = sin(self.angle) * speed
Example #37
0
    def __init__(self, image):
        sprite.Sprite.__init__(self)
        self.image = image
        #On récupère le mask pour la méthode mask_collide
        self.mask = mask.from_surface(self.image)

        #on place la boite aléatoirement
        self.rect = self.image.get_rect()
        self.rect.centerx = randint(10, WIDTH - 10)
        self.rect.bottom = 0
        self.speedy = SPEED_BACKGROUND
        self.dead = False
Example #38
0
class Red(Rect, object):
    """The Red enemies"""

    #img = image.load('img/square.png')
    img = image.load(os.path.join(maindir, 'img/square.png'))
    rect = img.get_rect()
    msk = mask.from_surface(img, 0)

    class Bullet(Rect, object):

        #img = image.load('img/redbullet.png')
        img = image.load(os.path.join(maindir, 'img/redbullet.png'))
        rect = img.get_rect()
        msk = mask.from_surface(img, 0)
        pow = 10

        def __init__(self, midbottom):
            Rect.__init__(self, self.rect)
            self.midbottom = midbottom

        def update(self):
            self.y += 10

        def render(self):
            scr.blit(self.img, self)

    def __init__(self, x, y):
        Rect.__init__(self, Red.img.get_rect(midbottom=(x, y)))
        self.axe = x + 150
        self.X, self.Y = self.midbottom
        self.tau = 0
        self.shield = 1
        self.foo = 0
        self.tick = 0

    def update(self):
        self.tick += 1
        self.tau += 1.8
        self.X = self.axe + sin(radians(self.tau)) * 300
        self.Y += 0.5
        self.midbottom = self.X, self.Y

        if self.left < ship.centerx < self.right and self.tick >= 10:
            shotenemi.append(Red.Bullet(self.midbottom))
            self.tick = 0

    def render(self):
        if self.foo:
            self.foo -= 1
            scr.blit(Red.img, self)
            return
        scr.blit(Red.img, self)
Example #39
0
 def __init__(self, text, x, y, size):
     Sprite.__init__(self)
     fonter = font.Font(os.path.join(FONT_DIR, "Cantarell-Regular.ttf"), size).render(text, True, (0,0,0))
     frect = fonter.get_bounding_rect()
     frect.x = -frect.x
     frect.y = -frect.y
     font_sf = Surface((frect.width, frect.height), SRCALPHA, 32)
     font_sf.blit(fonter, frect)
     self.image = font_sf
     self.rect = font_sf.get_rect()        
     self.rect.x = x
     self.rect.y = y
     self.mask = mask.from_surface(self.image)
Example #40
0
    def __init__(self, surf: Surface, position: Rect, fps: int, *groups):
        super().__init__(*groups)
        self.image = surf
        self.rect: Rect = position
        self.mask = mask.from_surface(surf)

        self.v_x = 0
        self.v_y = 0
        self.s_x = Vector2(self.rect.width, 0)
        self.s_y = Vector2(0, self.rect.height)
        self.step_size = Vector2(0, 0)

        self.fps = fps
def split_row(parent, parent_cols, row, height, width):
    """split_frame helper function
    splits a single row of source surface
    """
    
    images = []
    masks = []
    
    for col in range(parent_cols):
        current_image = parent.subsurface((col*width, row*height, width, height))
        images.append(current_image)
        masks.append(mask.from_surface(current_image))
        
    return images, masks
Example #42
0
    def test_from_surface_2(self):
        surf = surface.Surface((300, 100), depth=32, flags=SRCALPHA)
        surf.fill((0, 0, 0, 0xff))
        for x in range(200):
            surf.set_at((x, 20), (0, 0, 0, x))
        M = mask.from_surface(surf)
        self.assertEqual(M.get_at((0, 0)), 1)
        self.assertEqual(M.get_at((20, 20)), 0)
        self.assertEqual(M.get_at((21, 20)), 0)
        self.assertEqual(M.get_at((50, 20)), 0)
        self.assertEqual(M.get_at((127, 20)), 0)
        self.assertEqual(M.get_at((128, 20)), 1)
        self.assertEqual(M.get_at((129, 20)), 1)
        self.assertEqual(M.get_at((200, 20)), 1)
        self.assertEqual(M.get_at((21, 21)), 1)
        # Different threshold

        M = mask.from_surface(surf, 50)
        self.assertEqual(M.get_at((50, 20)), 0)
        self.assertEqual(M.get_at((51, 20)), 1)
        self.assertEqual(M.get_at((127, 20)), 1)
        self.assertEqual(M.get_at((128, 20)), 1)
        self.assertEqual(M.get_at((129, 20)), 1)
Example #43
0
    def test_from_surface_2(self):
        surf = surface.Surface((300, 100), depth=32, flags=SRCALPHA)
        surf.fill((0, 0, 0, 0xff))
        for x in range(200):
            surf.set_at((x, 20), (0, 0, 0, x))
        M = mask.from_surface(surf)
        self.assertEqual(M.get_at((0, 0)), 1)
        self.assertEqual(M.get_at((20, 20)), 0)
        self.assertEqual(M.get_at((21, 20)), 0)
        self.assertEqual(M.get_at((50, 20)), 0)
        self.assertEqual(M.get_at((127, 20)), 0)
        self.assertEqual(M.get_at((128, 20)), 1)
        self.assertEqual(M.get_at((129, 20)), 1)
        self.assertEqual(M.get_at((200, 20)), 1)
        self.assertEqual(M.get_at((21, 21)), 1)
        # Different threshold

        M = mask.from_surface(surf, 50)
        self.assertEqual(M.get_at((50, 20)), 0)
        self.assertEqual(M.get_at((51, 20)), 1)
        self.assertEqual(M.get_at((127, 20)), 1)
        self.assertEqual(M.get_at((128, 20)), 1)
        self.assertEqual(M.get_at((129, 20)), 1)
Example #44
0
 def __init__(self, ai_settings, screen, letter):
     super(Bunker, self).__init__()
     self.screen = screen
     self.letter = letter
     self.ai_settings = ai_settings
     self.mydict = ai_settings.bunker_letters
     self.pygame_image = pygame.image.load(
         self.mydict[self.letter]['image'][0])
     self.image = Image.open(self.mydict[self.letter]['image'][0])
     self.rect = self.pygame_image.get_rect()
     self.width = self.rect.width
     self.height = self.rect.height
     self.rect.center = self.mydict[self.letter]['position']
     self.mask = mask.from_surface(self.pygame_image)
Example #45
0
    def __init__(self, word, word_o, color, angle):
        Sprite.__init__(self)
        self.word = word
        self.angle = angle

        # Determine Word dimensions
        w_rect = word_o.get_bounding_rect()
        w_rect.x = -w_rect.x + WORD_PADDING
        w_rect.y = -w_rect.y + WORD_PADDING
        w_rect.width += WORD_PADDING * 2
        w_rect.height += WORD_PADDING * 2

        # Draw Word on a surface
        word_sf = Surface((w_rect.width, w_rect.height), SRCALPHA, 32)
        word_sf.blit(word_o, w_rect)
        self.rect = word_sf.get_rect()
        self.image = word_sf.copy()
        self.msf = word_sf.copy()

        # Create custom mask
        m1 = mask.from_surface(self.msf)
        cr, crw = [], []
        for c in [x for x in range(w_rect.width) if x % PXL == 0]:
            for r in [y for y in range(w_rect.height) if y % PXL == 0]:
                if m1.get_at((c, r)) != 0:
                    crw.append((c - PXL, r - PXL))
                    crw.append((c - PXL, r))
                    crw.append((c, r - PXL))
                    crw.append((c, r))
                    crw.append((c + PXL, r + PXL))
                    crw.append((c, r + PXL))
                    crw.append((c + PXL, r))
                    crw.append((c + PXL, r - PXL))
                    crw.append((c - PXL, r + PXL))
                    cr.append((c, r))
        for c, r in crw:
            draw.rect(self.msf, color, Rect((c, r), (PXL, PXL)))
        for i in enumerate(cr):
            c, r = i[1]
            j = 1
            if i[0] + 1 >= len(cr):
                break
            next_cr = cr[i[0] + 1]
            while next_cr[0] == c and next_cr[1] != r + PXL * j:
                draw.rect(self.msf, color, Rect((c, r + j * PXL), (PXL, PXL)))
                j += 1

        self._rotate()
Example #46
0
 def __init__(self, x, y, owner=None):
     """
     Init with owner to give him points for each destroyed block
     :param x: x coordinate of the play-field
     :param y: y coordinate of the play-field
     :param owner: Player-class object
     :return:
     """
     Sprite.__init__(self)
     self.vx = 0
     self.vy = -8
     self.image = Assets.projectile_laser
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.mask = from_surface(self.image)
     self.owner = owner
     self.dead = False
Example #47
0
def pygame_convert(original, colorkey, force_colorkey, pixelalpha):
    """
    this method does several tests on a surface to determine the optimal
    flags and pixel format for each tile.

    this is done for the best rendering speeds and removes the need to
    convert() the images on your own

    original is a surface and MUST NOT HAVE AN ALPHA CHANNEL
    """
    from pygame import Surface, mask, RLEACCEL
    
    tile_size = original.get_size()

    # count the number of pixels in the tile that are not transparent
    px = mask.from_surface(original).count()

    # there are no transparent pixels in the image
    if px == tile_size[0] * tile_size[1]:
        tile = original.convert()

    # there are transparent pixels, and set to force a colorkey
    elif force_colorkey:
        tile = Surface(tile_size)
        tile.fill(force_colorkey)
        tile.blit(original, (0,0))
        tile.set_colorkey(force_colorkey, RLEACCEL)

    # there are transparent pixels, and tiled set a colorkey
    elif colorkey:
        tile = original.convert()
        tile.set_colorkey(colorkey, RLEACCEL)

    # there are transparent pixels, and set for perpixel alpha
    elif pixelalpha:
        tile = original.convert_alpha()

    # there are transparent pixels, and we won't handle them
    else:
        tile = original.convert()

    return tile
Example #48
0
 def __init__(self, tag, initial_position, rotation=0, fontname='fonts/Arial.ttf', fontzoom=5):
     Sprite.__init__(self)
     self.tag = tag
     self.rotation = rotation
     fonter = font.Font(fontname, int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color'])
     self.tag['size'] *= fontzoom
     fonter = transform.rotate(fonter, rotation)
     frect = fonter.get_bounding_rect()
     frect.x = -frect.x
     frect.y = -frect.y
     self.fontoffset = (-frect.x, -frect.y)
     font_sf = Surface((frect.width, frect.height), pygame.SRCALPHA, 32)
     font_sf.blit(fonter, frect)
     self.image = font_sf
     self.rect = font_sf.get_rect()
     self.rect.width += TAG_PADDING
     self.rect.height += TAG_PADDING
     self.rect.x = initial_position[0]
     self.rect.y = initial_position[1]
     self.mask = mask.from_surface(self.image)
     self.mask = self.mask.convolve(CONVMASK, None, (TAG_PADDING, TAG_PADDING))
Example #49
0
    def init_masks(self):
        """ Init the mask for the sprite. 

        NOTE: any additional rect created must be, in general, inside
        of col_rect. That way collisions will work properly
        
        """
        
        # Create a mask with the image
        # TODO, NOTE TO SELF: The mask will use the first frame
        # in the animation! ALWAYS
        self.mask = mask.from_surface(self.image)
        #~ self.view_mask()

        # Feet mask
        self.feet_mask = mask.Mask((self.rect.width, 1))
        h = self.rect.height
        s_at = self.feet_mask.set_at
        g_at = self.mask.get_at
        for x in xrange(self.rect.width):
            if g_at((x, h - 1)):
                s_at((x, 0), 1)
Example #50
0
def load_images_pygame(tmxdata, mapping, *args, **kwargs):
    """
    given tmx data, return an array of images.

    why use this?  to change the tileset on the fly without reloading the
    the entire .tmx file.  metadata will be preserved. (test this)
    """

    from itertools import product
    from pygame import Surface, mask
    import pygame, os


    def handle_transformation(tile, flags):
        if flags:
            fx = flags & TRANS_FLIPX == TRANS_FLIPX
            fy = flags & TRANS_FLIPY == TRANS_FLIPY
            r  = flags & TRANS_ROT == TRANS_ROT

            if r:
                # not sure why the flip is required...but it is.
                newtile = pygame.transform.rotate(tile, 270)
                newtile = pygame.transform.flip(newtile, 1, 0)

                if fx or fy:
                    newtile = pygame.transform.flip(newtile, fx, fy)

            elif fx or fy:
                newtile = pygame.transform.flip(tile, fx, fy)

            # preserve any flags that may have been lost after the transformation
            return newtile.convert(tile)

        else:
            return tile


    pixelalpha     = kwargs.get("pixelalpha", False)
    force_colorkey = kwargs.get("force_colorkey", False)
    force_bitdepth = kwargs.get("depth", False)

    if force_colorkey:
        try:
            force_colorkey = pygame.Color(*force_colorkey)
        except:
            msg = "Cannot understand color: {}"
            raise Exception, msg.format(force_colorkey)

    tmxdata.images = [0] * tmxdata.maxgid

    for firstgid, t in sorted((t.firstgid, t) for t in tmxdata.tilesets):
        path = os.path.join(os.path.dirname(tmxdata.filename), t.source)

        image = pygame.image.load(path)

        w, h = image.get_size()
        tile_size = (t.tilewidth, t.tileheight)
        real_gid = t.firstgid - 1

        if t.trans:
            tileset_colorkey = pygame.Color("#{}".format(t.trans)) 

        # i dont agree with margins and spacing, but i'll support it anyway
        # such is life.  okay.jpg
        tilewidth = t.tilewidth + t.spacing
        tileheight = t.tileheight + t.spacing

        # some tileset images may be slightly larger than the tile area
        # ie: may include a banner, copyright, ect.  this compensates for that
        width = ((int((w-t.margin*2) + t.spacing) / tilewidth) * tilewidth) - t.spacing
        height = ((int((h-t.margin*2) + t.spacing) / tileheight) * tileheight) - t.spacing

        # using product avoids the overhead of nested loops
        p = product(xrange(t.margin, height+t.margin, tileheight),
                    xrange(t.margin, width+t.margin, tilewidth))

        for (y, x) in p:
            real_gid += 1
            gids = tmxdata.mapGID(real_gid)
            if gids == []: continue

            # we do some tests to correctly handle the tile and set the right
            # blitting flags.  just grab a section of it.
            temp = image.subsurface(((x,y), tile_size))

            # count the number of pixels in the tile that are not transparent
            px = mask.from_surface(temp).count()

            # there are no transparent pixels in the image
            if px == tile_size[0] * tile_size[1]:
                tile = temp.convert()

            # there are transparent pixels, and set to force a colorkey
            elif force_colorkey:
                tile = Surface(tile_size)
                tile.fill(force_colorkey)
                tile.blit(temp, (0,0))
                tile.set_colorkey(force_colorkey, pygame.RLEACCEL)

            # there are transparent pixels, and tiled set a colorkey
            elif t.trans:
                tile = temp.convert()
                tile.set_colorkey(tileset_colorkey, pygame.RLEACCEL)

            # there are transparent pixels, and set for perpixel alpha
            elif pixelalpha:
                tile = temp.convert_alpha()

            # there are transparent pixels, and we won't handle them
            else:
                tile = temp.convert()

            for gid, flags in gids:
                tmxdata.images[gid] = handle_transformation(tile, flags)


    del tmxdata.imagemap
    del tmxdata.maxgid

    return tmxdata
Example #51
0
 def _update_mask(self):
     self.mask = mask.from_surface(self.image)
     self.mask = self.mask.convolve(CONVMASK, None, (TAG_PADDING, TAG_PADDING))
Example #52
0
ECCENTRICITY = 1.5

LOWER_START = 0.45
UPPER_START = 0.55

FONT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fonts')
DEFAULT_FONT = 'Droid Sans'
DEFAULT_PALETTE = 'default'
FONT_CACHE = simplejson.load(open(os.path.join(FONT_DIR, 'fonts.json'), 'r'))

pygame.init()
convsurf = Surface((2 * TAG_PADDING, 2 * TAG_PADDING))
convsurf.fill((255, 0, 255))
convsurf.set_colorkey((255, 0, 255))
draw.circle(convsurf, (0, 0, 0), (TAG_PADDING, TAG_PADDING), TAG_PADDING)
CONVMASK = mask.from_surface(convsurf)

LAYOUT_HORIZONTAL = 0
LAYOUT_VERTICAL = 1
LAYOUT_MOST_HORIZONTAL = 2
LAYOUT_MOST_VERTICAL = 3
LAYOUT_MIX = 4

LAYOUTS = (
           LAYOUT_HORIZONTAL,
           LAYOUT_VERTICAL,
           LAYOUT_MOST_HORIZONTAL,
           LAYOUT_MOST_VERTICAL,
           LAYOUT_MIX
           )
Example #53
0
def load_images_pygame(tmxdata, mapping, *args, **kwargs):
    """
    given tmx data, return an array that is suitable as for the tmxdata object.
    why use this?  to change the tileset on the fly without reloading the
    the entire .tmx file.  metadata will be preserved.
    """

    from itertools import product
    from pygame import Surface, mask
    import pygame, os


    def handle_transformation(tile, flags):
        fx = flags & TRANS_FLIPX == TRANS_FLIPX
        fy = flags & TRANS_FLIPY == TRANS_FLIPY
        r  = flags & TRANS_ROT == TRANS_ROT

        if r:
            # not sure why the flip is required...but it is.
            newtile = pygame.transform.rotate(tile, 270)
            newtile = pygame.transform.flip(tile, 1, 0)

        if fx or fy:
            newtile = pygame.transform.flip(tile, fx, fy)

        # preserve any flags that may have been lost after the transformation
        newtile = newtile.convert(tile)

        return newtile

    pixelalpha     = kwargs.get("pixelalpha", False)
    force_colorkey = kwargs.get("force_colorkey", False)
    force_bitdepth = kwargs.get("depth", False)

    if force_colorkey:
        try:
            force_colorkey = pygame.Color(*force_colorkey)
        except:
            msg = "Cannot understand color: {}".format(force_colorkey)
            raise Exception, msg

    tmxdata.images = [0] * tmxdata.maxgid

    usedgids = tmxdata.loadgids[:]
    usedgids.extend(tmxdata.transgids.keys())

    for firstgid, t in sorted([ (t.firstgid, t) for t in tmxdata.tilesets ]):
        path = os.path.join(os.path.dirname(tmxdata.filename), t.source)

        image = pygame.image.load(path)

        w, h = image.get_size()
        tile_size = (t.tilewidth, t.tileheight)
        gid = firstgid

        # some tileset images may be slightly larger than the tiles area
        # ie: may include a banner, copyright, ect.  this compensates for that
        x_range = xrange(0, int(w / t.tilewidth) * t.tilewidth, t.tilewidth)
        y_range = xrange(0, int(h / t.tileheight) * t.tileheight, t.tileheight)

        # using product avoids the overhead of nested loops
        for (y, x) in product(y_range, x_range):

            # prevent loading of tiles that are never used in the loader
            if not gid in usedgids:
                gid += 1
                continue

            # determine if the tile contains any transparent area
            temp = image.subsurface(((x,y), tile_size))

            # if not, then we don't set any special blitting flags
            # make a copy so that the parent surface isn't lingering in memory
            px = mask.from_surface(temp).count()
            if px == tile_size[0] * tile_size[1]:
                tile = temp.convert()

            else:
                if force_colorkey:
                    tile = Surface(tile_size)
                    tile.fill(force_colorkey)
                    tile.blit(temp, (0,0))
                    tile.set_colorkey(force_colorkey, pygame.RLEACCEL)
                elif t.trans:
                    tile = temp.convert()
                    tile.set_colorkey(t.trans, pygame.RLEACCEL)

            tmxdata.images[tmxdata.gidmap[gid]] = tile

            # handle transformations, if needed
            if gid in tmxdata.transgids.keys():
                for newgid, flags in tmxdata.transgids[gid]:
                    tmxdata.images[newgid]=handle_transformation(tile,flags)

            gid += 1

    del tmxdata.imagemap
    del tmxdata.loadgids
    del tmxdata.transgids
    del tmxdata.maxgid

    return tmxdata
 def get_collision_mask(self):
     """Return the mask of teh current frame"""
     surface = Surface((self.surf_rect.width, self.surf_rect.height),
                       pygame.SRCALPHA)
     surface.blit(self.texture, (0, 0), self.surf_rect)
     return mask.from_surface(surface)
Example #55
0
 def _update_mask(self):
     self.mask = mask.from_surface(self.msf)