Пример #1
1
 def _get_raw_shadow(self):
     target_img = self.target.get_image(self.capture_state)
     r = target_img.get_rect()
     #the shadow will be larger in order to make free space for fadeout.
     r.inflate_ip(2*self.shadow_radius, 2*self.shadow_radius)
     img = Surface(r.size)
     img.fill((255, 255, 255, 255))
     img.blit(target_img, (self.shadow_radius, self.shadow_radius))
     if self.sun_angle <= 0.:
         raise Exception("Sun angle must be greater than zero.")
     elif self.sun_angle != 45. and self.vertical:
         w, h = img.get_size()
         new_h = h / tan(self.sun_angle * pi / 180.)
         screen_size = functions.get_screen().get_size()
         new_h = abs(int(min(new_h, max(screen_size))))
         img = scale(img, (w, new_h))
     if self.angle_mode == "flip":
         img = flip(img, self.mode_value[0], self.mode_value[1])
     elif self.angle_mode == "rotate":
         img = rotate(img, self.mode_value)
     else:
         raise Exception("angle_mode not available: " + str(self.angle_mode))
     shadow = pilgraphics.get_shadow(img,
                                     radius=self.shadow_radius,
                                     black=self.black,
                                     alpha_factor=self.alpha_factor,
                                     decay_mode=self.decay_mode,
                                     color=self.color)
     return shadow
Пример #2
0
    def shortAttack(self):
        self.attacking = True
        if self.game.Player.player_face == 'front':
            # I do not know why this vector needs to be 0 while the others are like, 1
            self.directional_attack_image = rotate(self.attack_image, 180)
            self.sub_vector = [0, 0]
        elif self.game.Player.player_face == 'left':
            self.directional_attack_image = rotate(self.attack_image, 90)
            self.sub_vector = [-1, 0]
        elif self.game.Player.player_face == 'back':
            self.directional_attack_image = rotate(self.attack_image, 0)
            self.sub_vector = [0, -1]
        elif self.game.Player.player_face == 'right':
            self.directional_attack_image = rotate(self.attack_image, 270)
            self.sub_vector = [0.8, 0] # editing this seems to change the speed of the right dagger swing a bit

        self.game.Player.can_move = False
        self.receding = False
        self.potent = True
        self.weapon_rect = Rect(1, 1, 1, 1)
        p_coords = [self.game.Player.player_r.x, self.game.Player.player_r.y]
        a_coords = [p_coords[0] + self.game.Player.getRigging()[0], p_coords[1] + self.game.Player.getRigging()[1]]
        if self.game.Player.player_face == 'right' or self.game.Player.player_face == 'left':
            a_coords = [a_coords[0] - self.attack_image.get_height(), a_coords[1] - self.attack_image.get_width()]
        self.blit_pos = a_coords
        self.attack_ticks = self.range
 def get_environment_wind_stream_sprites(
     cls, size: (int, int)) -> {Enum, List[Surface]}:
     sprites = {
         WindDirection.UP: [
             cls.get_image(path.join("props", "wind_stream_1.png")),
             cls.get_image(path.join("props", "wind_stream_2.png"))
         ],
         WindDirection.DOWN: [
             transform.flip(e, False, True) for e in [
                 cls.get_image(path.join("props", "wind_stream_1.png")),
                 cls.get_image(path.join("props", "wind_stream_2.png"))
             ]
         ],
         WindDirection.LEFT: [
             transform.rotate(e, -90) for e in [
                 cls.get_image(path.join("props", "wind_stream_1.png")),
                 cls.get_image(path.join("props", "wind_stream_2.png"))
             ]
         ],
         WindDirection.RIGHT: [
             transform.rotate(e, 90) for e in [
                 cls.get_image(path.join("props", "wind_stream_1.png")),
                 cls.get_image(path.join("props", "wind_stream_2.png"))
             ]
         ],
     }
     for key in sprites.keys():
         sprites[key] = [
             scaling_repeat(sprite, size) for sprite in sprites.get(key)
         ]
     return sprites
Пример #4
0
 def player_animations(self):
     flight_sprites = [
         self.get_sprite("player_neutral_flight_1"),
         self.get_sprite("player_neutral_flight_2"),
         self.get_sprite("player_neutral_flight_3")
     ]
     durations = [18 for _ in range(len(flight_sprites))]
     animations = [
         Animation(name='neutral',
                   frames=[self.get_sprite("player_neutral")],
                   durations=[1234],
                   hitbox_size=Vector2(18, 48),
                   offsets=[Vector2(-25, -5)]),
         Animation(name='fly_neutral',
                   frames=flight_sprites,
                   durations=durations,
                   hitbox_size=Vector2(18, 48),
                   offsets=[(-25, -5) for _ in flight_sprites]),
         Animation(name='fly_left',
                   frames=[transform.rotate(s, 20) for s in flight_sprites],
                   durations=durations,
                   hitbox_size=Vector2(25, 48),
                   offsets=[Vector2(-29, -15) for _ in flight_sprites]),
         Animation(
             name='fly_right',
             frames=[transform.rotate(s, -20) for s in flight_sprites],
             durations=durations,
             hitbox_size=Vector2(25, 48),
             offsets=[Vector2(-28, -15) for _ in flight_sprites])
     ]
     animations = {a.name: a for a in animations}
     animations['bullet'] = self.yellow_bullet()
     return animations
Пример #5
0
    def __init__(self, name, parent):
        super().__init__(parent)
        self.name = name
        self.image = Surface((ANCHO, ALTO - 32))
        self.rect = self.image.get_rect()

        self.f = self.crear_fuente(16, underline=True)

        f2 = self.crear_fuente(16)
        self.rt1_uns = transform.rotate(
            f2.render('Relative Values', True, COLOR_TEXTO, COLOR_BOX), 90)
        self.rt1_sel = transform.rotate(
            f2.render('Absolute Values', True, COLOR_TEXTO, COLOR_BOX), 90)
        rt1_rect = self.rt1_uns.get_rect(x=12, y=70)
        self.relative_text = self.rt1_uns
        self.relative_text_area = rt1_rect.inflate(10, 10)

        rt2 = transform.rotate(
            f2.render('Absolute Values', True, COLOR_TEXTO, COLOR_BOX), 90)
        rt2_rect = rt2.get_rect(x=6, y=220)

        render = self.f.render(name + ' Panel', True, COLOR_TEXTO, COLOR_BOX)
        render_rect = render.get_rect(centerx=(ANCHO // 4) * 1.5, y=0)

        self.image.fill(COLOR_BOX)
        self.image.blit(render, render_rect)
        self.image.blit(self.relative_text, self.relative_text_area)
        self.image.blit(rt2, rt2_rect)
Пример #6
0
 def __init__(self, timer):
     init()
     self.screen = display.set_mode((GAME_WIDTH, GAME_HEIGHT))
     display.set_caption("Whack a MOLE")
     self.img_bg = image.load("assets/background.png")
     self.img_hole = image.load("assets/hole.png")
     self.img_hammer = image.load("assets/mallet.png")
     self.img_bang = image.load("assets/bang.png")
     self.img_oops = image.load("assets/oops.png")
     self.img_click = image.load("assets/click.png")
     self.img_space = image.load("assets/space.png")
     self.img_night = image.load("assets/night.png")
     self.img_sunset = image.load("assets/sunset.png")
     self.img_night = transform.scale(self.img_night,
                                      (GAME_WIDTH, GAME_HEIGHT))
     self.img_sunset = transform.scale(self.img_sunset,
                                       (GAME_WIDTH, GAME_HEIGHT))
     self.img_space = transform.scale(self.img_space,
                                      (GAME_WIDTH, GAME_HEIGHT))
     self.img_click = transform.scale(self.img_click,
                                      (GAME_WIDTH, GAME_HEIGHT))
     self.img_hole = transform.scale(self.img_hole, (200, 45))
     self.img_hammer = transform.scale(self.img_hammer, (200, 200))
     self.img_bang = transform.scale(self.img_bang, (150, 150))
     self.img_oops = transform.scale(self.img_oops, (150, 150))
     self.img_hammer_hit = transform.rotate(self.img_hammer.copy(), 35)
     self.img_hammer_norm = transform.rotate(self.img_hammer.copy(), 10)
     self.timer = timer
     self.fixed_timer = timer
     self.reset()
     self.run()
Пример #7
0
    def updateGraphics():
        for s in AVRSprite.spriteList.values():
            if s.sizeDirty:
                s.scaledSurface = transform.smoothscale(s.surface, s.size)
                s.transformedSurface = transform.rotate(
                    s.scaledSurface, s.angle)
                s.sprite.image = s.transformedSurface
                s.sprite.rect = s.transformedSurface.get_rect()
                s.sprite.rect.center = s.pos
                s.sprite.maskDirty = True

            elif s.rotateDirty:
                s.transformedSurface = transform.rotate(
                    s.scaledSurface, s.angle)
                s.sprite.image = s.transformedSurface
                s.sprite.rect = s.transformedSurface.get_rect()
                s.sprite.rect.center = s.pos
                s.sprite.maskDirty = True

            elif s.posDirty:
                s.sprite.rect.center = s.pos
                s.posDirty = False
            s.posDirty = True
            s.rotateDirty = True
            s.sizeDirty = True
Пример #8
0
    def __init__(self, pos, size, svgFile, rotation=0.0):
        super().__init__(pos, size)

        # use the same size for the icon as the grid element
        width, height = self.rect.size

        # pressed version scale
        ds = 0.9
        dx = dy = (1 -
                   ds) / 2  # the position offset to use in x and y directions

        # use pynanosvg to convert svg file to bytes
        svg = Parser.parse_file(svgFile)  #, PPI) ..I do not understand DPI

        # figure out the scaling, making sure not to draw outside the lines
        scale = min(width / svg.width, height / svg.height)
        buf = rasterizer.rasterize(svg, width, height, scale)
        self.surfDefault = image.frombuffer(buf, self.rect.size, 'RGBA')

        # make a mini version for activation state
        buf = rasterizer.rasterize(svg,
                                   width,
                                   height,
                                   scale * ds,
                                   tx=dx * width,
                                   ty=dy * height)
        self.surfPressed = image.frombuffer(buf, self.rect.size, 'RGBA')

        # apply rotation
        if (rotation != 0.0):
            self.surfDefault = transform.rotate(self.surfDefault, rotation)
            self.surfPressed = transform.rotate(self.surfPressed, rotation)

        # initialize the active surface
        self.surf = self.surfDefault
Пример #9
0
    def __init__(self, radius, angle):
        'Init'
        if angle < 0:
            angle = -angle
        if angle > 180:
            angle = angle % 180
        diameter = radius * 2
        if (diameter, angle) in Portion.portions:
            self.surface = Portion.portions[(diameter, angle)]
            return

        # We need to build the portion, let's start with a circle.
        circ = pygame.Surface((diameter, diameter))
        pygame.draw.circle(circ, COLOR2, (radius, radius), radius, 0)

        # Cut the circle in half by drawing it halfway of another surface.
        circ.fill(BLACK, (0, 0, diameter, radius))

        # Rotate the semicircle.
        circ = rotate(circ, 180 - angle)

        # Cut the same half again (just readjust based on circ's size).
        circ.fill(BLACK, (0, 0, circ.get_width(), circ.get_height() / 2))

        # Reposition the angle (halp up and half down) by rotating halfway.
        circ = rotate(circ, angle / 2)

        # Re-center after rotation because image get's bigger after that.
        self.surface = pygame.Surface((diameter, diameter))
        blit_centered(self.surface, circ)
        Portion.portions[(diameter, angle)] = self.surface
Пример #10
0
 def _rotate(self):
     #angle = 90 if self.rotation == 'vertical' else 0
     angle = 0
     pos = (self.rect.x, self.rect.y)
     self.image = transform.rotate(self.image, angle)
     self.msf = transform.rotate(self.msf, angle)
     self.rect = self.image.get_rect()
     self.rect.x, self.rect.y = pos
     self._update_mask()
Пример #11
0
    def _load_pack(name):
        pathfile = path.join(IMAGES_DIR, '%s.png' % name)
        image = img_load(pathfile)

        return {
            Direction.UP: image,
            Direction.LEFT: rotate(image, 90),
            Direction.DOWN: rotate(image, 180),
            Direction.RIGHT: rotate(image, 270),
        }
Пример #12
0
    def __init__(self, index, count_border, count_middle):

        self.first_time = True

        self.index = index
        self.row = index // gc.NUM_TILES_SIDE
        self.col = index % gc.NUM_TILES_SIDE

        name = ''
        if (index == 20):
            name = '0.png'
        elif (index == 4):
            name = '1.png'
        elif index == 0 or index == 1 or index== 2 or index == 3 or index == 5 or index == 9 or index == 10 or index == 14 or index == 15 or index == 19 or index == 21 or index == 22 or index == 23 or index == 24:
            name = box_border[count_border]
        elif index == 6 or index == 7 or index == 8 or index == 9 or index == 11  or index == 13 or index == 16 or index == 17 or index == 18:
            name = box_middle[count_middle]
        elif index == 12:
            name = box_center[0]
        self.name = name
        self.image_path_border = os.path.join(gc.ASSET_DIR_BORDER, self.name)
        self.image_path_middle = os.path.join(gc.ASSET_DIR_MIDDLE, self.name)
        self.image_path_center = os.path.join(gc.ASSET_DIR_CENTER, self.name)
        self.image_path_start_end = os.path.join(gc.ASSET_DIR_START_END, self.name)

        if self.name in box_start_end:
            self.image_start_end = image.load(self.image_path_start_end)
            self.image = self.image_start_end
        elif self.name in box_border:
            self.image_border = image.load(self.image_path_border)
            self.image = self.image_border
        elif self.name in box_middle:
            self.image_middle = image.load(self.image_path_middle)
            self.image = self.image_middle
        elif self.name in box_center:
            self.image_center = image.load(self.image_path_center)
            self.image = self.image_center

        self.image = transform.scale(self.image, (gc.IMAGE_SIZE - 2 * gc.MARGIN, gc.IMAGE_SIZE - 2 * gc.MARGIN))

        #images border in correct position (rotation)
        if self.name in box_border and self.first_time == True:
            if self.name != '5.png' and self.name != '52.png':
                if self.row == 0:
                    self.image = transform.rotate(self.image, 180)
                elif self.row == 4:
                    self.image = transform.rotate(self.image, 0)
                elif self.col == 0:
                    self.image = transform.rotate(self.image, 270)
                elif self.col == 4:
                    self.image = transform.rotate(self.image, 90)

        if self.name in box_center:
            rotation_mode_center = [0, 90, 180, 270]
            self.image = transform.rotate(self.image, rotation_mode_center[random.randrange(0, 4)])
 def blit_templates(self, surface):
     x = 0
     y = 0
     #not memory nor performance efficient, but clear:
     if self.mode == "flip":
         corners = {
             "topleft": self.topleft_img,
             "bottomleft": flip(self.topleft_img, False, True),
             "bottomright": flip(self.topleft_img, True, True),
             "topright": flip(self.topleft_img, True, False)
         }
         sides = {
             "top": self.top_img,
             "left": rotate(self.top_img, 90),
             "bottom": rotate(self.top_img, 180),
             "right": rotate(self.top_img, 270)
         }
     elif self.mode == "rotate":
         corners = {
             "topleft": self.topleft_img,
             "bottomleft": rotate(self.topleft_img, 90),
             "bottomright": rotate(self.topleft_img, 180),
             "topright": rotate(self.topleft_img, 270)
         }
         sides = {
             "top": self.top_img,
             "left": rotate(self.top_img, 90),
             "bottom": rotate(self.top_img, 180),
             "right": rotate(self.top_img, 270)
         }
     cornsize = {
         key: value.get_size()
         for key, value in iter(corners.items())
     }
     sidsize = {key: value.get_size() for key, value in iter(sides.items())}
     #Blitting Sides
     nx = (self.size[0] - cornsize["topleft"][0] - cornsize["topright"][0])\
                                                      // sidsize["top"][0]
     ny = (self.size[1] - cornsize["topleft"][1] - cornsize["bottomleft"][1])\
                                                      // sidsize["left"][1]
     endx = nx * sidsize["top"][0] + cornsize["topleft"][0]
     endy = ny * sidsize["left"][1] + cornsize["topleft"][1]
     sizex = endx + cornsize["topright"][0]
     sizey = endy + cornsize["bottomleft"][1]
     self.size = (sizex, sizey)
     for i in range(nx):
         x = i * sidsize["top"][0] + cornsize["topleft"][0]
         surface.blit(sides["top"], (x, 0))
         x = i * sidsize["bottom"][0] + cornsize["bottomleft"][0]
         surface.blit(sides["bottom"], (x, sizey - sidsize["bottom"][1]))
     for i in range(ny):
         y = i * sidsize["left"][1] + cornsize["topleft"][1]
         surface.blit(sides["left"], (0, y))
         y = i * sidsize["right"][1] + cornsize["topright"][1]
         surface.blit(sides["right"], (sizex - sidsize["right"][0], y))
     #Blitting corners
     surface.blit(corners["topleft"], (0, 0))
     surface.blit(corners["bottomleft"], (0, endy))
     surface.blit(corners["bottomright"], (endx, endy))
     surface.blit(corners["topright"], (endx, 0))
Пример #14
0
    def buildLabels(self):
        """\
        Pre-renders text labels to surfaces for different 45 degree
        angles.

        On exit:
        self.label is a list of surfaces containing rendered labels
        self.slabel is the same but coloured for when the particle is selected
        self.labelxo is a list of x-offsets for each label's centre.
        self.labelyo is a list of y-offsets fo reach label's centre.
        self.desclabel is the description label displayed when selected
        """
        from pygame.transform import rotozoom, rotate

        font = pygame.font.Font(None, 14)

        label = font.render(
            " " + abbreviate(self.name) + " ",
            True,
            (0, 0, 0),
        )
        self.label = []  # 'selected' labels
        self.labelxo = []
        self.labelyo = []
        self.label.append(rotate(label, 90))
        self.label.append(rotozoom(label, 45, 1.0))
        self.label.append(label)
        self.label.append(rotozoom(label, -45, 1.0))

        slabel = font.render(
            " " + abbreviate(self.name) + " ",
            True,
            (96, 96, 255),
        )
        self.slabel = []
        self.slabel.append(rotate(slabel, 90))
        self.slabel.append(rotozoom(slabel, 45, 1.0))
        self.slabel.append(slabel)
        self.slabel.append(rotozoom(slabel, -45, 1.0))

        #        print self.slabel[0].get_width(),self.slabel[0].get_height()

        self.radius = max(self.slabel[0].get_width(),
                          self.slabel[0].get_height()) / 2
        #        self.radius = max(self.slabel[0].get_width(),self.slabel[0].get_height())

        for l in self.label:
            self.labelxo.append(-l.get_width() / 2)
            self.labelyo.append(-l.get_height() / 2)

        font = pygame.font.Font(None, 20)
        self.desclabel = font.render(
            self.attributetype.upper() + " : " + self.name, True, (0, 0, 0),
            (255, 255, 255))
Пример #15
0
 def move(self):
     if (self.x > 0 or self.vel > 0) and (self.x < W_WIDTH - self.img_width or self.vel < 0):
         self.x += self.vel
     if self.vel > 0:
         self.img = transform.rotate(image.load(IMAGE_PLAYER), -10)
         self.y = W_HEIGHT - 115
     if self.vel < 0:
         self.img = transform.rotate(image.load(IMAGE_PLAYER), 10)
         self.y = W_HEIGHT - 115
     if self.vel == 0:
         self.img = image.load(IMAGE_PLAYER)
         self.y = W_HEIGHT - 110
 def draw(self, surface, image, head):
     """draw in pygame app"""
     direction_vector = self.get_2d_snake_direction()
     if np.all(direction_vector == [1, 0]):
         head = rotate(head, -90)
     elif np.all(direction_vector == [-1, 0]):
         head = rotate(head, 90)
     elif np.all(direction_vector == [0, 1]):
         head = rotate(head, 180)
     else:
         head = rotate(head, 0)
     surface.blit(head, (self.x[0], self.y[0]))
     for i in range(1, len(self.x)):
         surface.blit(image, (self.x[i], self.y[i]))
Пример #17
0
def rot_center(image, angle):
    """rotate an image while keeping its center and size"""
    rot_image = transform.rotate(image, angle)
    rot_rect = image.get_rect().copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image
Пример #18
0
 def draw_word(self, word):
     rot_image = transform.rotate(
                  word.image,
                  90 * word.platform.body.angle)
     self.window.display_surface.blit(
                 rot_image,
                 word.platform.body.position - word.offset)
Пример #19
0
 def get_spin(self):
     time_frac = self.time / 1000
     rotation = int(time_frac * 360)
     max_d = self.sprite_rect.w
     dx = int(max_d * time_frac)
     dy = int((4 * dx / max_d) * (dx - max_d))
     return rotate(self.sprite, rotation), (self.pos[0] - dx, self.pos[1] + dy)
Пример #20
0
    def __init__(
        self,
        dictionary,
        tile,
        pos,
        owner=None,
        known_index=None,
        small_tile=False,
        interact=False,
        rotation=0,
    ):
        if not hasattr(tile, 'get_raw_value'):
            #print('WARNING: Just attempted to pass a PieceType to TileRender!')
            tile = Piece(int(tile))

        DirtySprite.__init__(self)
        tile_surface = dictionary[tile.get_raw_value()].copy()
        tile_surface = transform.rotate(tile_surface, 90 * rotation)
        tile_surface = tile_surface.convert_alpha()
        self.image = tile_surface
        self.pos = pos
        self.rect = pos
        self.owner = owner
        self.known_index = known_index
        self.currently_pressed = False
        sizes = SMALL_TILE_SIZE if small_tile else TILE_SIZE
        self.tile_rect = Rect(self.rect[0], self.rect[1], sizes[0], sizes[1])
        self.can_interact = interact
Пример #21
0
    def createCharTexture(self, char, mode=None):
        """Create character's texture/bitmap as a Numeric array w/ width and height

        This uses PyGame and Numeric to attempt to create
        an anti-aliased luminance texture-map of the given
        character and return it as (data, width, height).
        """
        try:
            letter_render = self.font.render(char, 1, (255, 255, 255))
        except:
            traceback.print_exc()
            return None, font.CharacterMetrics(char, 0, 0)
        else:
            # XXX Figure out why this rotate appears to be required :(
            letter_render = transform.rotate(letter_render, -90.0)
            colour = surfarray.array3d(letter_render)
            alpha = surfarray.array_alpha(letter_render)
            colour[:, :, 1] = alpha
            colour = colour[:, :, :2]
            colour = contiguous(colour).astype('B')
            # This produces what looks like garbage, but displays correctly
            colour.shape = (
                colour.shape[1],
                colour.shape[0],
            ) + colour.shape[2:]
            return colour, font.CharacterMetrics(
                char,
                colour.shape[0],
                colour.shape[1],
            )
Пример #22
0
def _resolve_params(data, obj_col):
    """(dict, list) -> NoneType
    For each object in obj_col, resolve the non-type parameters on it, and render the object if applicable."""
    for obj in obj_col:
        if data["img"]:
            obj.img = load_img(data["img"])
        if data["flip"]:
            horiz, vert = None, None
            args = data["flip"].strip("()").split(",")
            if args[0] == "false":
                horiz = False
            else:
                horiz = True
            if args[1] == "false":
                vert = False
            else:
                vert = True

            obj.img = transform.flip(obj.img, horiz, vert)
        if data["rotate"]:
            obj.img = transform.rotate(obj.img, int(data["rotate"].split("=")[-1]))
        if data["scale"]:
            obj.img = transform.scale(obj.img, tuple(int(i) for i in data["scale"].strip("()").split(",")))

        obj.render(screen, update_queue)
Пример #23
0
    def updateScreen(self):
        "Draw everything on the screen"
        
        self.screen.fill(RGB_BLACK)
        
        #Draw Paddle and Ball
        self.screen.blit(transform.rotate(self.paddle.image,
                                self.paddle.angle), self.paddle.position)
        
        for ball in self.balls:
            self.screen.blit(ball.image, (ball.x, ball.y))

        #Draw Points Label and Points String
        self.screen.blit(self.pointsLabel, (10,10))
        self.screen.blit(self.pointsString, (80,10))
        
        #Draw Level Label and Level String
        self.screen.blit(self.levelLabel, (200, 10))
        self.screen.blit(self.levelString, (250, 10))
        
        #Draw non-destroyed Bricks for current level
        self.drawBricks()
        
        #Draw any bonuses that are on screen at the moment
        for boni in self.bonuses:
            self.screen.blit(boni.image, boni.rect)

        #Draw Mini-paddles signifying lifes left
        self.drawMiniPaddles()
        
        pygame.display.flip()
Пример #24
0
 def rotate(self, target):
     """Поворачивает игровой объект в сторону target"""
     angle = atan2(target[1] - self.rect.centery, target[0] - self.rect.centerx)
     angle = -degrees(angle)
     self.angle = angle
     self.image = rotate(self.original_image, angle)
     self.rect = self.image.get_rect(center=self.rect.center)
Пример #25
0
 def __init__(self, fruit, interp_step):
     """ Prepare the fruit's spr: a square diamond 
     with a number in the center.
     interp_step determines where to position the sprite, 
     based on the view's current sprite step. 
     """
     DirtySprite.__init__(self)
     self.fruit = fruit
     
     # make the square
     sq_surf = Surface((cell_size / 1.414, cell_size / 1.414))
     sq_surf.set_colorkey((255, 0, 255))  # magenta = color key
     sq_surf.fill(FRUIT_COLORS[fruit.fruit_type])
     # rotate for a diamond
     dm_surf = rotate(sq_surf, 45)
     blit_rect = Rect(0, 0, cell_size * 1.414, cell_size * 1.414)
     # blit the diamond as the fruit's image
     img = Surface((cell_size, cell_size))
     img.set_colorkey((255, 0, 255))  # magenta = color key
     img.fill((255, 0, 255))
     img.blit(dm_surf, blit_rect)
     
     # add text at the center
     self.font = Font(None, font_size) 
     txtsurf = self.font.render(str(fruit.fruit_num), True, (0, 0, 0))
     textpos = txtsurf.get_rect(center=(cell_size / 2, cell_size / 2))
     img.blit(txtsurf, textpos)
     
     # prepare rect to blit on screen
     self.resync(interp_step)
     
     self.image = img
Пример #26
0
def load(player_id_):
    ennemies_images = []
    player_id = player_id_
    #on récupère le fichier json des avions
    mob_data = json.load(open(SPEC_DIR, "r"))["body"]
    del mob_data[
        player_id]  #on supprime l'avion du joueur dans celui-ci pour pas qu'il apparaisse dans les ennemies
    #pour chaque avion
    for plane in mob_data:
        colors = []
        #pour chaque couleur
        for folder in os.listdir(plane["image"]):
            #pour chaque images
            imgs = []
            for file in os.listdir(path.join(plane["image"], folder)):
                #on charge et on transforme chaque image et on l'ajoute à l'array colors
                img = image.load(path.join(plane["image"], folder,
                                           file)).convert_alpha()
                img = transform.scale(img, (75, 50))
                img = transform.rotate(img, 180)
                imgs.append(img)
            colors.append(imgs)

        ennemies_images.append(colors)
    return (mob_data, ennemies_images)
Пример #27
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))
Пример #28
0
    def __animate(self, game):

        if ((game.frame % self.animInterval) == 0):
            self.anim_frame += 1

            if (self.anim_frame > self.maxFrames):
                self.anim_frame = 1
            if (self.anim_frame <= 0):
                self.anim_frame = self.maxFrames

        imageString = self.sprname + "_" + str(self.anim_frame)

        # if we flip the y then we must move adjust the rect.x
        if self.flips[1]:
            self.rect.x = self.orgRect.x + self.posPercent * self.orgRect.height - self.orgRect.height + TILE_SIZE
        else:
            self.rect.x = self.orgRect.x

        # clip part of the image
        img = transform.chop(
            game.images[imageString][0],
            Rect(0, 0, 0, self.posPercent * self.orgRect.height))

        # apply flipping and rotation if required
        if self.flips[0] or self.flips[1]:
            img = transform.flip(img, self.flips[0], self.flips[1])
        if self.rotation != 0:
            img = transform.rotate(img, self.rotation)

        self.setimage(img)
Пример #29
0
    def next_frame(self):
        """
        switch to the next image (or to the first if current is last)
        """
        if not self.paused and self.animation:
            self.changes += 1
            if self.changes % self.delay == 0:
                self.frame_number += 1
                if self.frame_number == len(self.frames):
                    self.frame_number = 0

                if self.cached_size != self.size:
                    new_frames = []
                    for frame in self.frames:
                        frame = transform.scale(
                            frame, (self.size.width, self.size.height))
                        new_frames.append(frame)
                    self.frames = new_frames
                    self.cached_size = self.size
                if (self.cached_angle != self.angle) and self.rotations:
                    new_frames = []
                    for frame in self.source_frames:
                        if self.angle == 180:
                            frame = transform.flip(frame, True, False)
                        else:
                            frame = transform.rotate(frame, self.angle)
                        frame = transform.scale(
                            frame, (self.size.width,
                                    self.size.height))  # todo: optimize
                        new_frames.append(frame)
                    self.frames = new_frames
                    self.cached_angle = self.angle

                self.frame = self.frames[self.frame_number]
Пример #30
0
    def __init__(self, game_env, source, target, flip):
        super(Sam, self).__init__()
        self.__game_env = game_env
        self.__angle = math.atan2(target[1] - source[1], target[0] -
                                  source[0])  # sam angle of fire in radian
        self.__speed = 5 + (
            1 if self.__game_env.dynamic.game_level % 2 == 0 else 0
        )  # default sam speed is 5 and increased each level

        if flip:  # sam image rotational angle based on the fire position
            rotation_angle = 90 - self.__angle * (180 / 3.1415)
        else:
            rotation_angle = 270 + self.__angle * (180 / 3.1415)

        self.surf = image.load(
            self.__game_env.static.sam).convert()  # loading sam image
        self.surf = transform.rotate(self.surf,
                                     rotation_angle)  # rotating the image
        self.surf = transform.flip(self.surf, flip,
                                   ~flip)  # flipping image as necessary
        self.surf.set_colorkey(
            (255, 255, 255), self.__game_env.RLEACCEL
        )  # setting the white color as the transperant area; RLEACCEL is used for better performance on non accelerated displays
        self.rect = self.surf.get_rect(center=(
            source[0], source[1]
        ))  # setting the position of the bullet as the input (souce_x, y_pos)
Пример #31
0
    def movement_controls(self, pressed, tilemap):
        if pressed[A]:
            self.rotation += 2
            self.rotate_vehicle(358)
            collision_result = collision_check(self, tilemap, Vec2d(0,0))
            if collision_result.collisions:
                self.rotation -= 2
                self.rotate_vehicle(2)   
        if pressed[D]:
            self.rotation -= 2
            self.rotate_vehicle(2)
            collision_result = collision_check(self, tilemap, Vec2d(0,0))
            if collision_result.collisions:
                self.rotation += 2
                self.rotate_vehicle(358)

        if pressed[W] and abs(self.speed) < self.top_speed:
            self.speed += self.acceleration
        if pressed[S] and abs(self.speed) < self.top_speed:
            self.speed -= self.acceleration

        if not pressed[W] and not pressed[S] and self.speed != 0:
            if abs(self.speed) < abs(self.acceleration):
                self.speed = 0
            else:
                self.speed -= math.copysign(self.acceleration, self.speed)
        if pressed[A] or pressed[D]:
            self.image = transform.rotate(self.base_image, self.rotation)
            self.rect = self.image.get_rect()
Пример #32
0
    def update_image(self, k):
        self.anime[k] += 1
        if k == 0:
            self.anime[1] = 0
            self.anime[2] = 0
            if self.anime[0] == 40:
                self.anime[0] = 0
            self.image = self.imagesN[self.anime[0] // 10]
        elif k == 1:
            self.anime[2] = 0
            if self.anime[1] == 40:
                self.anime[1] = 39
            else:
                self.image = self.imagesL[self.anime[1] // 10]
        elif k == 2:
            self.anime[1] = 0
            if self.anime[2] == 40:
                self.anime[2] = 39
            else:
                self.image = self.imagesR[self.anime[2] // 10]

        if self.slow:
            self.anime_slow += 1
            if self.anime_slow == 360:
                self.anime_slow = 0
            self.slow_effect = transform.rotate(self.slow_effect0,
                                                self.anime_slow)
            self.slow_rect = self.slow_effect.get_rect()
Пример #33
0
    def draw(self, surface):
        updated_rects = []
        texture = transform.rotate(self.__texture,
                                   -self.__angle * 180 / np.pi - 180)
        #texture = texture.convert_alpha()
        width, height = texture.get_size()
        pos = (self.__pos[0] - width / 2, self.__pos[1] - height / 2)
        try:
            updated_rects.append(surface.blit(texture, pos))
            updated_rects.append(
                draw_text(surface, self.__color, self.__name,
                          (pos[0], pos[1] - 32), 16))
            if self.__drift > 0:
                updated_rects.append(
                    draw_text(surface, self.__color,
                              f'DRIFT: {self.__drift:.0f}',
                              (pos[0] + 16, pos[1] - 16), 16))
            elif perf_counter(
            ) - self.__drift_end_time < 1 and self.__prev_drift > 0:
                if self.__drift == -1:
                    updated_rects.append(
                        draw_text(surface, (0, 255, 0),
                                  f'DRIFT: {self.__prev_drift:.0f}',
                                  (pos[0] + 16, pos[1] - 16), 16))
                elif self.__drift == -2:
                    updated_rects.append(
                        draw_text(surface, (255, 0, 0),
                                  f'DRIFT: {self.__prev_drift:.0f}',
                                  (pos[0] + 16, pos[1] - 16), 16))

        except:
            self.go_to_start()

        return updated_rects
Пример #34
0
    def updateScreen(self):
        "Draw everything on the screen"

        self.screen.fill(RGB_BLACK)

        #Draw Paddle and Ball
        self.screen.blit(
            transform.rotate(self.paddle.image, self.paddle.angle),
            self.paddle.position)

        for ball in self.balls:
            self.screen.blit(ball.image, (ball.x, ball.y))

        #Draw Points Label and Points String
        self.screen.blit(self.pointsLabel, (10, 10))
        self.screen.blit(self.pointsString, (80, 10))

        #Draw Level Label and Level String
        self.screen.blit(self.levelLabel, (200, 10))
        self.screen.blit(self.levelString, (250, 10))

        #Draw non-destroyed Bricks for current level
        self.drawBricks()

        #Draw any bonuses that are on screen at the moment
        for boni in self.bonuses:
            self.screen.blit(boni.image, boni.rect)

        #Draw Mini-paddles signifying lifes left
        self.drawMiniPaddles()

        pygame.display.flip()
Пример #35
0
    def __updateTankSurface(self, surface: Surface, color: Color,
                            direction: math.Vector2):
        surface.fill((0, 0, 0, 0))

        # rect inside surface
        surfaceSize = surface.get_size()
        surfaceRect = Rect(0, 0, surfaceSize[0], surfaceSize[1])
        tankRect = Rect(0, 0, self.size[0], self.size[1])
        diff = math.Vector2(surfaceRect.center) - math.Vector2(tankRect.center)
        tankRect.move_ip(diff)

        temp = surface.copy()
        draw.rect(temp, color, tankRect)

        # apply tank direction to surface
        degree = -math.Vector2(0, 1).angle_to(direction)
        temp = transform.rotate(temp, degree)

        # temp was enlarged by rotate (wtf):
        # calculate diff so that temp surface is positioned outside
        # of the destination surface below
        tempRectSize = temp.get_size()
        diff = math.Vector2(tempRectSize) - math.Vector2(surfaceSize)

        # copy back wanted portion from rotation
        surface.blit(temp, -diff / 2)
Пример #36
0
def get_shadow(target_img, shadow_radius=2, black=255, color_format="RGBA",
                alpha_factor=0.85, decay_mode="exponential", color=(0,0,0),
                sun_angle=30., vertical=True, angle_mode="flip", mode_value=(False, True)):
        r = target_img.get_rect()
        #the shadow will be larger in order to make free space for fadeout.
        r.inflate_ip(2*shadow_radius, 2*shadow_radius)
        img = Surface(r.size)
        img.fill((255, 255, 255, 255))
        img.blit(target_img, (shadow_radius, shadow_radius))
        if sun_angle <= 0.:
            raise Exception("Sun angle must be greater than zero.")
        elif sun_angle != 45. and vertical:
            w, h = img.get_size()
            new_h = h / tan(sun_angle * pi / 180.)
            screen_size = functions.get_screen().get_size()
            new_h = abs(int(min(new_h, max(screen_size))))
            img = scale(img, (w, new_h))
        if angle_mode == "flip":
            img = flip(img, mode_value[0], mode_value[1])
        elif self.angle_mode == "rotate":
            img = rotate(img, mode_value)
        else:
            raise Exception("angle_mode not available: " + str(angle_mode))
        shadow =             _pilshadow(img,
                                        radius=shadow_radius,
                                        black=black,
                                        alpha_factor=alpha_factor,
                                        decay_mode=decay_mode,
                                        color=color)
        #
        W, H = functions.get_screen_size()
        shadow.set_alpha(-1, RLEACCEL)
        return shadow.convert_alpha()
Пример #37
0
 def _get_raw_shadow(self):
     target_img = self.target.get_image(self.capture_state)
     r = target_img.get_rect()
     #the shadow will be larger in order to make free space for fadeout.
     r.inflate_ip(2 * self.shadow_radius, 2 * self.shadow_radius)
     img = Surface(r.size)
     img.fill((255, 255, 255, 255))
     img.blit(target_img, (self.shadow_radius, self.shadow_radius))
     if self.sun_angle <= 0.:
         raise Exception("Sun angle must be greater than zero.")
     elif self.sun_angle != 45. and self.vertical:
         w, h = img.get_size()
         new_h = h / tan(self.sun_angle * pi / 180.)
         screen_size = functions.get_screen().get_size()
         new_h = abs(int(min(new_h, max(screen_size))))
         img = scale(img, (w, new_h))
     if self.angle_mode == "flip":
         img = flip(img, self.mode_value[0], self.mode_value[1])
     elif self.angle_mode == "rotate":
         img = rotate(img, self.mode_value)
     else:
         raise Exception("angle_mode not available: " +
                         str(self.angle_mode))
     shadow = pilgraphics.get_shadow(img,
                                     radius=self.shadow_radius,
                                     black=self.black,
                                     alpha_factor=self.alpha_factor,
                                     decay_mode=self.decay_mode,
                                     color=self.color)
     return shadow
Пример #38
0
	def createCharTexture( self, char, mode=None ):
		"""Create character's texture/bitmap as a Numeric array w/ width and height

		This uses PyGame and Numeric to attempt to create
		an anti-aliased luminance texture-map of the given
		character and return it as (data, width, height).
		"""
		try:
			letter_render = self.font.render(
				char,
				1,
				(255,255,255)
			)
		except:
			traceback.print_exc()
			return None, font.CharacterMetrics(char,0,0)
		else:
			# XXX Figure out why this rotate appears to be required :(
			letter_render = transform.rotate( letter_render, -90.0)
			colour = surfarray.array3d( letter_render )
			alpha = surfarray.array_alpha( letter_render )
			colour[:,:,1] = alpha
			colour = colour[:,:,:2]
			colour = contiguous( colour )
			# This produces what looks like garbage, but displays correctly
			colour.shape = (colour.shape[1],colour.shape[0],)+colour.shape[2:]
			return colour, font.CharacterMetrics(
				char,
				colour.shape[0],
				colour.shape[1],
			)
Пример #39
0
 def angle(self, angle):
     self._angle = angle
     pos = self.pos
     self._surf = transform.rotate(self._orig_surf, angle)
     self.width, self.height = self._surf.get_size()
     self._calc_anchor()
     self.pos = pos
Пример #40
0
 def generate_resource_dct(self):
     """Genrerate animations with rotations and flipping."""
     dct = {Dir.NONE: None}
     # Raw
     diag_image = self.resource.image.get(self.diag_name)
     perp_image = self.resource.image.get(self.perp_name)
     # Rotate
     for r in range(4):
         dct[self.perp_dir[r]] = transform.rotate(perp_image, 90*r)
         dct[self.diag_dir[r]] = transform.rotate(diag_image, 90*r)
     # Opacify
     for image in dct.values():
         if image:
             opacify_ip(image, self.opacity)
     # Return
     return dct
Пример #41
0
	def __animate(self, game):

		if ((game.frame % self.animInterval) == 0):
			self.anim_frame += 1
		
			if (self.anim_frame > self.maxFrames):
				self.anim_frame = 1
			if (self.anim_frame <= 0):
				self.anim_frame = self.maxFrames

				
		imageString = self.sprname + "_" + str(self.anim_frame)
		
		# if we flip the y then we must move adjust the rect.x
		if self.flips[1]:
			self.rect.x = self.orgRect.x + self.posPercent * self.orgRect.height - self.orgRect.height + TILE_SIZE
		else:
			self.rect.x = self.orgRect.x
			
		# clip part of the image
		img = transform.chop(game.images[imageString][0], Rect(0,0,0,self.posPercent * self.orgRect.height))
		
		# apply flipping and rotation if required
		if self.flips[0] or self.flips[1]:
			img = transform.flip(img, self.flips[0], self.flips[1])
		if self.rotation != 0:
			img = transform.rotate(img, self.rotation)
			
		self.setimage(img)
Пример #42
0
    def render(self, surf):
        self.frame += 1

        # For animation of bird, loop through three images
        if self.frame <= self.ANIM_TIME:
            self.sprite = self.SPRITES[0]
        elif self.frame <= self.ANIM_TIME * 2:
            self.sprite = self.SPRITES[1]
        elif self.frame <= self.ANIM_TIME * 3:
            self.sprite = self.SPRITES[2]
        elif self.frame <= self.ANIM_TIME * 4:
            self.sprite = self.SPRITES[1]
        elif self.frame == self.ANIM_TIME * 4 + 1:
            self.sprite = self.SPRITES[0]
            self.frame = 0

        # so when bird is nose diving it isn't flapping
        if self.tilt <= -80:
            self.sprite = self.SPRITES[1]
            self.frame = self.ANIM_TIME * 2

        # tilt the bird
        rotated_sprite = rotate(self.sprite, self.tilt)
        new_rect = rotated_sprite.get_rect(center=self.sprite.get_rect(
            topleft=(self.x, self.y)).center)
        surf.blit(rotated_sprite, new_rect.topleft)
Пример #43
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))
Пример #44
0
def command_rotate_left(new_img, screen, file, rect):
    "rotate counter clockwise"
    wait_cursor()
    new_img = rotate(new_img, 90)
    rect = get_center(screen, new_img)
    my_update_screen(new_img, rect, file)
    normal_cursor()
    return (new_img, new_img, rect)
Пример #45
0
 def __init__(self, x, y):
     self.x = x
     self.y = y
     super(Spaceship, self).__init__('sprites/spaceship.png')
     transColor = self.image.get_at((0,0))
     self.image.set_colorkey(transColor)
     self.image = scale(self.image, (60, 70))
     self.image = rotate(self.image, 270)
Пример #46
0
 def _rotate (self, direct):		# code 0, 1, 2, 3
     """
     rotate tank by code:
     0 - 0 deg, 1 - 90 deg, 2 - 180, 3 - 270;
     """
     if self.direction != direct:
         self.image = transform.rotate(self.image, (self.direction - direct)*90)
         self.direction = direct
Пример #47
0
    def update(self, x, y, course, shutdirection, dead, frag):

        self.rect.x, self.rect.y, self.course, self.shutdirection, self.dead, self.frag = \
            x, y, course, shutdirection, dead, frag

        # если танк взорвали
        if (self.dead > 0):
            if (self.dead < self.config.DEAD_COUNT):

                # показываем анимацию взрыва
                self.image = Surface((self.config.WIDTH,self.config.HEIGHT))
                self.image.fill(Color(self.COLOR))
                self.image.set_colorkey(Color(self.COLOR))
                self.boltAnimDie.blit(self.image, (0, 0))

            else:

                # закончили показывать взрыв, респауним танк
                self.image = image.load(self.config.INIT_IMAGE)
                #  Анимация движения
                boltAnim = []
                for anim in self.config.ANIMATION:
                    boltAnim.append((anim, self.config.ANIMATION_DELAY))
                self.boltAnimMove = pyganim.PygAnimation(boltAnim)
                self.boltAnimMove.play()

        # направление
        else:

            self.image = Surface((self.config.WIDTH,self.config.HEIGHT)) # перерисовываем аватарку
            self.image.fill(Color(self.COLOR))                           # заливаем фон
            self.image.set_colorkey(Color(self.COLOR))                   # делаем фон прозрачным
            self.boltAnimMove.blit(self.image, (0, 0))                   # выводим анимацию

            # движение влево
            if self.shutdirection == "left":
                self.image = transform.rotate(self.image, 90)                # поворачиваем по направлению движения

            # движение вправо
            elif self.shutdirection == "right":
                self.image = transform.rotate(self.image, 270)

            # движение вниз
            elif self.shutdirection == "down":
                self.image = transform.rotate(self.image, 180)
Пример #48
0
 def generate_jumping_dct(self, pid):
     """Genrerate animations with rotations and flipping."""
     dct = {}
     # Raw
     diag_image = self.resource.image.get(self.diag_names[pid])
     perp_image = self.resource.image.get(self.perp_names[pid])
     # Rotate
     for r in (0, 3):
         dct[self.perp_dir[r]] = transform.rotate(perp_image, r*90)
         dct[self.diag_dir[r]] = transform.rotate(diag_image, r*90)
     if pid == 2:
         dct[self.perp_dir[3]] = transform.flip(dct[self.perp_dir[3]], 0, 1)
     dct[self.diag_dir[1]] = transform.flip(dct[self.diag_dir[0]], 1, 0)
     dct[self.diag_dir[2]] = transform.flip(dct[self.diag_dir[3]], 1, 0)
     dct[self.perp_dir[1]] = transform.flip(dct[self.perp_dir[3]], 1, 0)
     dct[self.perp_dir[2]] = transform.rotate(perp_image, 180)
     # Return
     return dct
Пример #49
0
    def render(self, screen):
        if self.animation_count == self.animation_count_max:
            self.animation_count = 0
        else:
            self.animation_count += 1

        angle = self.direction.angle_to((0, -1))

        if self.speed != 0:
            animation_index = int(int((self.animation_count * len(self.walk)) - 1)/self.animation_count_max)
            screen.blit(transform.rotate(self.walk[animation_index], angle), self.pos)
        else:
            if self.idle_animation != None:
               screen.blit(transform.rotate(self.idle_animation, angle), self.pos)

        if self.health_bar and len(self.walk) > 0:
            health_bar = Rect(self.pos.x, self.pos.y, (self.health * self.walk[0].get_width())/100, -5)
            draw.rect(screen, (255, 0, 0), health_bar, 0)
Пример #50
0
def command_rotate_left(new_img, screen, file, num_imgs, rect):
    "rotate counter clockwise"
    wait_cursor()
    start = start_timer()
    new_img = rotate(new_img, 90)
    rect = get_center(screen, new_img)
    my_update_screen(new_img, screen, rect, file, num_imgs, check_timer(start))
    normal_cursor()
    return (new_img, new_img, rect)
Пример #51
0
    def rotate(self):
        """Rotate the projectile to the direction it was fired in."""

        self.x, self.y = self.scene.player.facing
        rotation = degrees(atan2(self.x, self.y))
        self.image = transform.rotate(self.image, rotation)
        self.rect = self.image.get_rect(left=self.rect.left, top=self.rect.top)
        self.rect.centerx = self.scene.player.rect.centerx + (8 * self.x)
        self.rect.centery = self.scene.player.rect.centery + (8 * self.y)
Пример #52
0
 def draw(self, surf):
     frame = surf.get_rect()
     if self.highlighted:
         surf.fill(self.highlight_color)
     image = self.image
     image = transform.rotate(image, self._angle)
     r = image.get_rect()
     r.center = frame.center
     surf.blit(image, r)
Пример #53
0
 def _adjust_bearing(self):
     """
     Make the image the face the correct angle
     """
     expected_rotation = self._expected_bearing()
     if expected_rotation != self._rotation:
         self.image = transform.rotate(self._root_image, expected_rotation)
         self.rect = self.image.get_rect(center=self.rect.center)
         self._rotation = expected_rotation
Пример #54
0
def main():
    parser = argparse.ArgumentParser(description='Pack skin textures')
    parser.add_argument('src')
    parser.add_argument('dst')
    parser.add_argument('-u', dest='unpack', const=True,
                        type=bool, default=False, nargs="?")

    args = parser.parse_args()

    src_img = image.load(args.src)

    if args.unpack:
        dst_img = Surface((10, 50), flags=SRCALPHA)

        dst_img.blit(src_img, (0, 00), HEAD)
        dst_img.blit(src_img, (0, 10), STRAIGHT1)
        dst_img.blit(src_img, (0, 20), STRAIGHT2)
        dst_img.blit(src_img, (0, 30), TAIL)
        dst_img.blit(src_img, (0, 40), TURN)
    else:
        dst_img = Surface((40, 40), flags=SRCALPHA)

        single_tile = Surface((10, 10), flags=SRCALPHA)

        seq = ((HEAD, (0, 0)), (TAIL, (0, 30)), (TURN, (0, 40)))
        for tile, tile_pos in seq:
            single_tile.fill((0, 0, 0, 0))
            single_tile.blit(src_img, (0, 0), Rect(tile_pos, (10, 10)))

            for rot, offset in ROT_OFFSET.items():
                pos = add_vecs(tile.topleft, offset)
                dst_img.blit(transform.rotate(single_tile, rot), pos)

        for tile, tile_pos in ((STRAIGHT1, (0, 10)),
                               (STRAIGHT2, (0, 20))):
            single_tile.fill((0, 0, 0, 0))
            single_tile.blit(src_img, (0, 0), Rect(tile_pos, (10, 10)))

            dst_img.blit(single_tile, tile)

            pos = add_vecs(tile.topleft, (0, 10))
            dst_img.blit(transform.rotate(single_tile, -90), pos)

    image.save(dst_img, args.dst)
Пример #55
0
    def buildLabels(self):
        """\
        Pre-renders text labels to surfaces for different 45 degree
        angles.

        On exit:
        self.label is a list of surfaces containing rendered labels
        self.slabel is the same but coloured for when the particle is selected
        self.labelxo is a list of x-offsets for each label's centre.
        self.labelyo is a list of y-offsets fo reach label's centre.
        self.desclabel is the description label displayed when selected
        """
        from pygame.transform import rotozoom, rotate

        font = pygame.font.Font(None, 14)

        label = font.render(" "+abbreviate(self.name)+" ", True, (0,0,0), )
        self.label   = []   # 'selected' labels
        self.labelxo = []
        self.labelyo = []
        self.label.append(rotate(label, 90))
        self.label.append(rotozoom(label, 45, 1.0))
        self.label.append(label)
        self.label.append(rotozoom(label, -45, 1.0))

        slabel = font.render(" "+abbreviate(self.name)+" ", True, (96,96,255), )
        self.slabel  = []
        self.slabel.append(rotate(slabel, 90))
        self.slabel.append(rotozoom(slabel, 45, 1.0))
        self.slabel.append(slabel)
        self.slabel.append(rotozoom(slabel, -45, 1.0))

#        print self.slabel[0].get_width(),self.slabel[0].get_height()

        self.radius = max(self.slabel[0].get_width(),self.slabel[0].get_height())/2
#        self.radius = max(self.slabel[0].get_width(),self.slabel[0].get_height())

        for l in self.label:
            self.labelxo.append( - l.get_width()  / 2 )
            self.labelyo.append( - l.get_height() / 2 )

        font = pygame.font.Font(None, 20)
        self.desclabel = font.render(self.attributetype.upper()+" : "+self.name, True, (0,0,0), (255,255,255))
Пример #56
0
 def update(self):
     if self.deltay % 1 < 0.01:
         self.image = rotate(self.initimage, self.angle)
         self.angle += self.rotation
     self.rect.centerx += self.deltax
     self.rect.top += self.deltay
     self.deltay += 0.2
     self.deltax *= 1.02
     if self.rect.top > globalvars.WIN_RESX:
         self.parent.remove(self)
Пример #57
0
    def __init__(self, environment, _speed):
        """
        Creates the cat with the proper image
        """
        super().__init__(environment, _speed)

        self._wall_modifier = 0
        image_name = "media/Cat.png"
        self._root_image = transform.rotate(image.load(image_name), 180)
        self.image = self._root_image
Пример #58
0
	def loop(self, game, sprite):
		
		self.dy += 0.2
		
		self.rect.y += self.dy
		self.rect.x += self.dx
		
		img = transform.rotate(game.images['banana'][0], self.rotation)
		self.rotation += 4
		self.setimage(img)
Пример #59
0
 def longUpdate(self):
     if self.attacking:
         for x in xrange(5):
             attack_size = self.directional_attack_image.get_size()
             turn_point = [0, 0]
             if self.game.Player.isVertical():
                 turn_point = [attack_size[0]/2, 0]
             elif self.game.Player.isHorizontal():
                 turn_point = [0, attack_size[1]/2]
             self.mod_DAT = rotate(self.directional_attack_image, self.angle + 45)
             if self.angle < -90:
                 self.attacking = False
             self.angle -= 1