-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathframework.py
629 lines (495 loc) · 15.5 KB
/
framework.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
"""
This file has everything for our game framework,
essentially it is one big wrapper around PyGame,
the goal of this is to make it more portable to
switch to other game frameworks if needed since
all you need to do is implement the generic interfaces
that everything else uses
"""
import pygame
import uuid
from utils import AbstractMethod, DefaultMethod, Singleton
from enum import Enum
class Sound(object):
def __init__(self, file):
self._file = 'assets/sounds/{0}.wav'.format(file)
self._sound = pygame.mixer.Sound(self._file)
def play(self):
self._sound.play(0)
def playNTimes(self, n):
self._sound.play(n)
def loop(self):
self._sound.play(-1)
def stop(self):
self._sound.stop()
class Text(object):
def __init__(self, text, fontSize=20, color=(255, 255, 255)):
self._text = str(text)
self._color = color
self._font = pygame.font.Font("assets/Players.ttf", fontSize)
@property
def text(self):
return self._text
def setText(self, text):
self._text = str(text)
def setColor(self, color):
self._color = color
def setBold(self):
self._font.set_bold(1)
@property
def image(self):
return self._font.render(self._text, False, self._color)
class Image(object):
def __init__(self, sheet, x, y, width, height):
self.rect = pygame.Rect((x, y, width, height))
self._image = pygame.Surface(self.rect.size, pygame.SRCALPHA)
self._image.blit(sheet, (0, 0), self.rect)
def flip(self):
""" Flips an image """
self._image = pygame.transform.flip(self._image, True, False)
self.rect = self._image.get_rect()
return self
def rotate(self, angle):
""" Rotates an image """
self._image = pygame.transform.rotate(self._image, -1 * angle)
self.rect = self._image.get_rect()
return self
def scale(self, factor):
""" Scales an image """
newWidth = int(self.width * factor)
newHeight = int(self.height * factor)
self._image = pygame.transform.scale(self._image, (newWidth, newHeight))
self.rect = self._image.get_rect()
return self
@property
def image(self):
return self._image
@property
def width(self):
""" Width of the sprite """
return self.rect.size[0]
@property
def height(self):
""" Height of the sprite """
return self.rect.size[1]
class SpriteSheet(object):
""" Used for loading sprites from a sprite sheet """
def __init__(self, filename):
self.invisible = pygame.image.load('assets/sprites/invisible_sheet.png')
#self.invisible = pygame.image.load('assets/sprites/white_sheet.png')
self.sheet = pygame.image.load('assets/sprites/{0}_sheet.png'.format(filename))
def sprite(self, x, y, width, height):
""" Loads image from x, y, x+width, y+height """
return Image(self.sheet, x, y, width, height)
def spriteFlipped(self, x, y, width, height):
""" Returns a sprite, but flipped horizontally """
return self.sprite(x, y, width, height).flip()
def invisibleSprite(self, width, height):
""" Returns invisible sprite"""
return Image(self.invisible, 0, 0, width, height)
class GameSprite(pygame.sprite.Sprite):
""" Sprite class that represents a sprite """
def __init__(self):
super().__init__()
self.x = 0
self.y = 0
self.image = pygame.Surface([0, 0])
self.rect = self.image.get_rect()
self.__isDying = False
def draw(self, screen):
""" Draws the object on the screen """
self.image = self.getSprite()
self.rect = self.image.get_rect()
self.rect.x = self.x
self.rect.y = self.y
screen.draw(self, self.x, self.y)
@DefaultMethod
def getSprite(self):
""" Returns the active sprite to display """
return self.image
@DefaultMethod
def remove(self):
""" Remove the sprite """
self.kill()
@property
def image(self):
return self._image
@image.setter
def image(self, img):
if isinstance(img, Image):
self._image = img.image
else:
self._image = img
if self._image is not None:
self.rect = self._image.get_rect()
self.rect.x = self.x
self.rect.y = self.y
@property
def width(self):
""" Width of the sprite """
return self.rect.size[0]
@property
def height(self):
""" Height of the sprite """
return self.rect.size[1]
@property
def top(self):
""" Top of the sprite """
return self.y
@top.setter
def top(self, t):
""" Sets where the top side of the sprite is """
self.y = t
@property
def bottom(self):
""" Bottom of the sprite """
return self.y + self.height
@bottom.setter
def bottom(self, b):
""" Sets the bottom position of the sprite """
self.y = b - self.height
@property
def right(self):
""" Right side of the sprite """
return self.x + self.width
@right.setter
def right(self, r):
""" Sets where the right side of the sprite is """
self.x = r - self.width
@property
def left(self):
""" Left side of the sprite """
return self.x
@left.setter
def left(self, l):
""" Sets where the left side of the sprite is """
self.x = l
@property
def centerX(self):
return self.x + ((1/2) * self.width)
@centerX.setter
def centerX(self, x):
self.x = x - ((1/2) * self.width)
@property
def centerY(self):
return self.y + ((1/2) * self.height)
@centerY.setter
def centerY(self, y):
self.y = y - ((1/2) * self.height)
def SpriteCollision(sprite, spriteGroup, kill=False):
""" Checks for collission between a sprite and a sprite group """
return pygame.sprite.spritecollide(sprite, spriteGroup, kill)
class GameObject(GameSprite):
""" Everything in the game should extend this class """
def __init__(self):
super().__init__()
self.__id = uuid.uuid4() # Something to uniquely identify every game object
@DefaultMethod
def update(self):
pass
@DefaultMethod
def collectedItem(self, item, collectionType):
pass
@DefaultMethod
def drawExtra(self, screen):
pass
@DefaultMethod
def collision(self, collisionType, direction, obj):
pass
def draw(self, screen):
""" Draws the object on the screen """
super(GameObject, self).draw(screen)
self.drawExtra(screen)
@property
def id(self):
return self.__id
class PlayableWithLives(GameObject):
def __init__(self):
super().__init__()
self.__lives = 3
self.__isDying = False
@property
def isDying(self):
return self.__isDying
@property
def lives(self):
return self.__lives
def spawn(self, x, y):
self.onSpawn()
self.x = x
self.y = y
self.__startingX = x
self.__startingY = y
self.__isDying = False
def respawnIfPossible(self):
if self.__lives <= 0:
self.kill()
else:
self.spawn(self.__startingX, self.__startingY)
def die(self):
self.__lives = self.__lives - 1
self.__isDying = True
self.onDeath()
@DefaultMethod
def onReset(self):
pass
@DefaultMethod
def onSpawn(self):
pass
@DefaultMethod
def onDeath(self):
pass
class GameCollectible(GameObject):
""" Something Collectible, like a hammer or the flaming oil can """
def __init__(self):
super().__init__()
self.__isClearable = False
@DefaultMethod
def onCollect(self, collectedBy, collectionType):
collectedBy.collectedItem(self)
self.kill()
@property
def canBeCleared(self):
return self.__isClearable
@staticmethod
def IsClearable():
def decorator(func):
def wrapper(self, *args, **kwargs):
self.__isClearable = True
return func(self, *args, **kwargs)
return wrapper
return decorator
class GameLevelManager:
"""
'Interface' for a Level Manager
"""
def __init__(self):
pass
@AbstractMethod
def drawLevel(self, screen):
pass
@AbstractMethod
def advanceLevel(self):
pass
@AbstractMethod
def getSpawnLocations(self):
pass
class SpriteGroup:
""" Group of Sprites (Wrapper around pygame sprite group) """
def __init__(self):
self._group = pygame.sprite.Group()
def add(self, sprite):
""" Adds a sprite to the group """
if not isinstance(sprite, GameSprite):
raise TypeError("Can only add instances of GameSprite to a Sprite Group")
return self._group.add(sprite)
def remove(self, sprite):
""" Removes a sprite """
return self._group.remove(sprite)
def has(self, sprite):
""" Checks if a sprite exists in the group """
return self._group.has(sprite)
def empty(self):
""" Clears the list """
return self._group.empty()
def sprites(self):
""" Returns all of the sprites """
return self._group.sprites()
def draw(self, screen):
""" Draws all of the sprites """
for sprite in self._group:
sprite.draw(screen)
def update(self, *args):
""" Updates all of the sprites """
for sprite in self._group:
sprite.update(*args)
def __iter__(self):
""" Iterator """
return iter(self.sprites())
def __contains__(self, sprite):
""" Contains operator """
return self.has(sprite)
def __len__(self):
return len(self._group)
class Screen:
""" Screen (pygame display) """
def __init__(self, width, height):
self._width = width
self._height = height
pygame.init()
self._display = pygame.display.set_mode((width, height))
def draw(self, sprite, x, y):
""" Draws a sprite on the screen """
if hasattr(sprite, 'image'):
self._display.blit(sprite.image, (x, y))
else:
self._display.blit(sprite, (x, y))
def fill(self, color):
""" Fills the screen with a color """
self._display.fill(color)
@property
def pygameScreen(self):
return self._display
@property
def width(self):
return self._width
@property
def height(self):
return self._height
class Window:
""" Wrapper around the PyGame GUI """
def __init__(self, width, height):
self._screen = Screen(width, height)
def close(self):
""" Closes the window """
pygame.quit()
def setTitle(self, title):
""" Sets the window title """
pygame.display.set_caption(title)
return self
def setIcon(self, icon):
""" Sets the window icon """
pygame.display.set_icon(pygame.image.load(icon))
return self
def flip(self):
""" Displays everything that has been drawn """
pygame.display.flip()
def draw(self, sprite, x, y):
""" Draws a sprite on the screen """
self._screen.draw(sprite, x, y)
def fill(self, color):
""" Fills the screen with a color """
self._screen.fill(color)
@property
def size(self):
""" Returns dimensions of the window """
return (self.width, self.height)
@property
def width(self):
""" Width of the window """
return self._screen.width
@property
def height(self):
""" Height of the window """
return self._screen.height
@property
def screen(self):
""" Returns screen for drawing """
return self._screen
@Singleton
class __ClockClass:
def __init__(self):
self._clock = None
self._delta = 0.0
self.fps = 60
def forceFPS(self, fps):
""" Forces a certain FPS """
if (self._clock is None):
self._clock = pygame.time.Clock()
self.fps = fps
t = self._clock.tick(self.fps)
self._delta = t / 1000.0
def resetDelta(self):
self._delta = 0
@property
def timeDelta(self):
""" Returns the detla time """
return self._delta
Clock = __ClockClass() # Only instance of the clock class
@Singleton
class __MusicPlayer:
def __init__(self):
self._backgroundName = ""
self._background = ""
self.backgroundPlaying = False
def newBackground(self, filename):
self.backgroundPlaying = True
self._backgroundName = filename
self._background = Sound(filename)
self._background.loop()
def playBackground(self):
if self.backgroundPlaying == False:
self.backgroundPlaying = True
self._background.loop()
def stopBackground(self):
self.backgroundPlaying = False
self._background.stop()
def playEffect(self, filename):
self._effectName = filename
self._effect = Sound(filename)
self._effect.play()
def playOnTop(self, filename):
self.backgroundPlaying = False
self._background.stop()
self.newEffect = Sound(filename)
self.newEffect.play()
Music = __MusicPlayer()
class Keys(Enum):
""" Enum wrapper for pygame keys """
LEFT = pygame.K_LEFT
RIGHT = pygame.K_RIGHT
DOWN = pygame.K_DOWN
UP = pygame.K_UP
SPACE = pygame.K_SPACE
W = pygame.K_w
A = pygame.K_a
S = pygame.K_s
D = pygame.K_d
R = pygame.K_r
Q = pygame.K_q
E = pygame.K_e
Num_1 = pygame.K_1
Num_2 = pygame.K_2
Num_3 = pygame.K_3
Num_4 = pygame.K_4
Num_5 = pygame.K_5
Num_6 = pygame.K_6
ENTER = pygame.K_RETURN
@Singleton
class __EventManagerClass:
""" Handles events for the framework """
def __init__(self):
self._listeners = {}
def handleEvents(self):
""" Looks at pygame events and publishes them """
for event in pygame.event.get():
eventStr = self.__str(event.type)
if eventStr == self.QUIT:
self.publish(eventStr, None)
elif eventStr == self.KEYDOWN:
self.publish(eventStr, event.key)
elif eventStr == self.KEYUP:
self.publish(eventStr, event.key)
def subscribe(self, event, func):
""" Subscribes to event and executes func when event happens """
if event not in self._listeners:
self._listeners[event] = [func]
else:
self._listeners[event].append(func)
def unsubscribe(self, event, func):
""" Unsubscribes from an event """
if event in self._listeners:
self._listeners.remove(func)
def publish(self, event, *data):
""" Dispatches an event and executes subscribers """
if event in self._listeners:
for func in self._listeners[event]:
func(*data)
def __str(self, k):
return "event_{0}".format(k)
"""
Everything below this is an "Enum" value for this class
"""
@property
def QUIT(self):
return self.__str(pygame.QUIT)
@property
def KEYDOWN(self):
return self.__str(pygame.KEYDOWN)
@property
def KEYUP(self):
return self.__str(pygame.KEYUP)
@property
def GAMEOVER(self):
return self.__str("GameOver")
Events = __EventManagerClass()