-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgraphics.py
352 lines (278 loc) · 10.4 KB
/
graphics.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import pygame as p
import math
import os
import global_values as g
class Spritesheet:
"""
Class for sheets filled with surfaces
"""
def __init__(self, name, sx, sy):
self.name = name
self.surface = load_image(self.name)
self.sx = sx
self.sy = sy
self.anims = []
self.masks = []
for y in range( int(self.surface.get_height()//sy) ):
self.anims.append([])
self.masks.append([])
for x in range( int(self.surface.get_width()//sx) ):
new_surface = p.Surface((self.sx, self.sy), p.SRCALPHA)
new_surface.blit(self.surface, (0,0), (x*self.sx, y*self.sy, self.sx, self.sy))
self.anims[-1].append(new_surface)
new_mask = p.mask.from_surface(new_surface)
self.masks[-1].append(new_mask)
cache_name = f"{self.name}_{x}_{y}"
g.image_cache[cache_name] = new_surface
g.reverse_image_cache[new_surface] = SurfacePickle(new_surface, cache_name)
print(self.name,":",int(self.surface.get_width()//sx), int(self.surface.get_height()//sy))
g.spritesheets[self.name] = self
def create_animation(self, index, timer, ping_pong=False, global_time=True, repeat=True, reverse=False):
"""
Create animation from specific index
"""
anim = Animation(self.anims[index], timer, ping_pong=ping_pong, global_time=global_time, repeat=repeat, reverse=reverse)
return anim
def create_animation_system(self, anim_index_dict, timer, ping_pong=False, global_time=True, repeat=True, reverse=False):
"""
Create animation system from specific index
"""
anim_dict = {}
for name, index in anim_index_dict.items():
anim = Animation(self.anims[index], timer, ping_pong=ping_pong, global_time=global_time, repeat=repeat, reverse=reverse)
anim_dict[name] = anim
anim_system = AnimationSystem(anim_dict)
return anim_system
class Animation:
"""
Class for holding and showing a collection of sprites over time
"""
def __init__(self, frames, timer, ping_pong=False, global_time=True, repeat=True, reverse=False):
self.frames = frames
self.max_timer = timer
self.ping_pong = ping_pong
self.global_time = global_time
self.repeat = repeat
self.reverse = reverse
if not self.repeat:
self.global_time = False
self.active = True
if not global_time:
self.start_update_time = p.time.get_ticks()
def reset(self):
self.start_update_time = p.time.get_ticks()
def get_frame(self):
"""
Get the current displayed frame
"""
if self.ping_pong:
frame_count = (len(self.frames)*2)-1
else:
frame_count = len(self.frames)
if self.global_time:
frame_index = ((p.time.get_ticks()/1000)/self.max_timer) % frame_count
else:
new_update_time = p.time.get_ticks()
diff = (new_update_time-self.start_update_time)/1000
frame_index = (diff/self.max_timer) % frame_count
if not self.repeat:
if diff/self.max_timer >= frame_count:
if self.ping_pong:
frame_index = 0
else:
frame_index = -1
old_frame_index = frame_index
if self.ping_pong and frame_index >= len(self.frames):
if frame_index == len(self.frames):
frame_index = len(self.frames)-0.001
else:
frame_index = len(self.frames)-(frame_index - len(self.frames))
if self.reverse:
if frame_index == -1:
frame_index = 0
else:
frame_index = len(self.frames)-int(frame_index+1)
return self.frames[int(frame_index)]
def __getstate__(self):
print("ANIMATION")
return pickle_state(self.__dict__)
def __setstate__(self, state):
self.__dict__ = unpickle_state(state)
class AnimationSystem:
"""
Class for playing multiple animations
"""
def __init__(self, anim_dict):
self.anim_dict = anim_dict
for key in self.anim_dict.keys():
self.playing_anim_name = key
break
self.playing_anim = self.anim_dict[self.playing_anim_name]
def set_anim(self, name):
#reset new anim
if name != self.playing_anim_name:
if not self.playing_anim.global_time:
self.playing_anim.start_update_time = p.time.get_ticks()
self.playing_anim_name = name
self.playing_anim = self.anim_dict[self.playing_anim_name]
#reset anim
if not self.playing_anim.global_time:
self.playing_anim.start_update_time = p.time.get_ticks()
def get_frame(self):
return self.playing_anim.get_frame()
def __getstate__(self):
print("ANIMATION SYSTEM")
return pickle_state(self.__dict__)
def __setstate__(self, state):
self.__dict__ = unpickle_state(state)
def load_image(name, path=g.GFX_DIRS, extension=".png", alpha=True):
"""
Load image, or take from cache if possible
"""
if not g.image_cache.get(name, None):
if not isinstance(path, tuple):
path = (path,)
for path_to_try in path:
filepath = os.path.join(path_to_try, name + extension)
if os.path.exists(filepath):
image = p.image.load(filepath)
if alpha:
image = image.convert_alpha()
else:
image = image.convert()
g.image_cache[name] = image
g.reverse_image_cache[image] = SurfacePickle(image, name)
break
if name not in g.image_cache:
raise ValueError(f"failed to find image: {name}")
return g.image_cache[name]
def get_surface(gfx):
"""
Get the drawable surface from a number of graphical sources
"""
if type(gfx) == str:
return load_image(gfx)
if type(gfx) == p.Surface:
return gfx
if isinstance(gfx, (Animation, AnimationSystem)):
return gfx.get_frame()
if type(gfx) == list or type(gfx) == tuple:
return g.spritesheets[gfx[0]].anims[gfx[1]][gfx[2]]
print("warning, cannot find: ",gfx)
return None
def get_surface_hash(surface):
"""
Hash a surface
"""
surf_hash = hash(surface) + hash(surface.get_width() *0.331 + surface.get_height() * 0.12321)
return surf_hash
class SurfacePickle():
def __init__(self, surf, name):
self.name = name
self.hash = get_surface_hash(surf)
def get_surface_pickle(surface):
return g.reverse_image_cache[surface]
def pickle_state(_state_dict):
"""
Pickle obj state, converting surfaces as required
"""
state_dict = _state_dict.copy()
#make pickle work
for k,v in state_dict.items():
if type(v) == p.Surface:
surf_pickle = get_surface_pickle(v)
state_dict[k] = surf_pickle
elif type(v) == list:
list_pickle = []
for i,vv in enumerate(v):
if type(vv) == p.Surface:
surf_pickle = get_surface_pickle(vv)
list_pickle.append(surf_pickle)
else:
list_pickle.append(vv)
state_dict[k] = list_pickle
return state_dict
def unpickle_state(_state_dict):
"""
Unpickle obj state, converting surface names as required
"""
state_dict = _state_dict.copy()
#return state_dict
for k,v in state_dict.items():
if type(v) == SurfacePickle:
try:
surf = g.image_cache[v.hash]
except:
surf = g.image_cache[v.name]
state_dict[k] = surf
elif type(v) == list:
list_unpickle = []
for i,vv in enumerate(v):
if type(vv) == SurfacePickle:
try:
surf = g.image_cache[vv.hash]
except:
surf = g.image_cache[vv.name]
list_unpickle.append(surf)
else:
list_unpickle.append(vv)
state_dict[k] = list_unpickle
return state_dict
def get_mask(gfx):
"""
Get the mask from some surface, or create it if it doesn't exist
"""
surf = get_surface(gfx)
surf_hash = get_surface_hash(surf)
res = g.mask_cache.get(surf_hash, None)
if res:
return res
else:
#create new
mask = p.mask.from_surface(surf)
g.mask_cache[surf_hash] = mask
return mask
def draw_text(font_name, string, pos, cx=False, cy=False, colour=g.convert_colour("black"), alpha=255):
"""
Draw some text
"""
font = g.fonts[font_name]
colour = g.convert_colour(colour)
health_text = font.render(string, False, colour)
w,h = font.size(string)
x = pos[0]
y = pos[1]
if cx:
x -= w/2
if cy:
y -= h/2
if alpha != 255:
health_text.set_alpha(alpha)
g.screen.blit(health_text, (x, y))
def draw_wrapped_text(font_name, string, rect, colour=g.convert_colour("black"), alpha=255, spacing=None):
words = string.split(" ")
font = g.fonts[font_name]
colour = g.convert_colour(colour)
x = rect.x
y = rect.y
line = ""
for word in words:
if word == "":
word = " "
w,h = font.size(line+" "+word)
if w > rect.w or "\n" in word:
#draw line
if y+h > rect.y:
draw_text(font_name, line, (x,y), colour=colour, alpha=alpha)
line = word
x = rect.x
if spacing:
y += spacing
else:
y += h
#if y > rect.bottom:
# return
else:
line += " "+word
if line:
draw_text(font_name, line, (x,y), colour=colour, alpha=alpha)