/
sprite_factory.py
70 lines (58 loc) · 2.61 KB
/
sprite_factory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# -*- coding: utf-8 -*-
from pygame import sprite, image, transform
'''
Fábrica de sprites para generar todos los sprites del juego (originalmente sólo bloques y power-ups)
'''
class SpriteFactory(sprite.Sprite):
classlist = []
def __init__(self, img, vel=[0, 0], sprite_type=None, animation_sheet=None, frames=0):
sprite.Sprite.__init__(self)
if type(img).__name__ == "str":
self.image = image.load(img).convert_alpha()
else:
self.image = img.convert_alpha()
self.rect = self.image.get_rect()
# Para reubicación tras reescalado
self.position_master = self.rect.topleft
self.sprite_type = sprite_type
# Banderas que usaremos para iniciar animaciones o movimiento cuando el juego las requiera
self.moving = False
self.animate = False
self.state = ""
self.vel = vel
if self.sprite_type == 'SV' or self.sprite_type == 'GD':
self.breakable = False
else:
self.breakable = True
self.animation_sheet = animation_sheet # Image (Surface)
if self.animation_sheet is not None:
self.frames = frames
self.current_frame = 0
self.animation_sheet_rect = self.animation_sheet.get_rect()
def update(self, pos_x=0, pos_y=0, surfaces=None):
self.rect.x += pos_x
self.rect.y += pos_y
if self.animate:
self.play_animation(self.frames, surfaces)
def play_animation(self, frames, surfaces=None):
if surfaces is None:
if self.current_frame >= frames - 1:
self.current_frame = 0
self.animate = False
elif self.current_frame < frames and surfaces is None:
self.current_frame += 1
new_area = (self.current_frame * self.rect.width, 0, self.rect.width, self.rect.height)
# Ver que sólo se cambia la imagen, no es necesario volver a obtener el rectángulo porque ya está definido
center = self.rect.center
self.image = self.animation_sheet.subsurface(new_area)
elif surfaces is not None:
# La animación no repetirá el ciclo aquí, sino que finalizará en el sprite final
if self.current_frame >= self.frames - 1:
self.animate = False
else:
self.current_frame += 1
center = self.rect.center
self.image = transform.scale2x(self.animation_sheet.subsurface(surfaces[self.current_frame]))
self.rect = self.image.get_rect()
self.rect.center = center
return self.animate