-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathobserver.py
86 lines (61 loc) · 2.16 KB
/
observer.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
from consts import Consts
from entity import Entity
import pygame as pg
class Observer:
"""
A base class for the observer class
"""
def on_notify(self, event):
raise NotImplemented
class GameOverObserver(Observer):
"""
A concrete observer class, used to handle the game over event
Methods
----------
on_notify(self, event)
Checks the received event and handles it if it is the SET_GAME_OVER event
"""
def on_notify(self, event): # obj is, in this case, the bool that makes the game stop
if event.name == Consts.SET_GAME_OVER:
Consts.GAME_OVER = Consts.IS_GAME_OVER
class Subject:
"""
A base class for the subject class
Methods
----------
add_observer(self, obs)
Adds a new observer to the list of observers that the subject needs to notify
remove_observer(self, obs)
Removes the specified observer from the list
notify(self, event)
Sends the event to each subscribed observer
"""
def __init__(self):
self.observers = []
def add_observer(self, obs: Observer):
self.observers.append(obs)
def remove_observer(self, obs: Observer):
self.observers.remove(obs)
def notify(self, event):
for obs in self.observers:
obs.on_notify(event)
class GameOverSubject(Subject):
"""
Concrete subject class that checks the moment in which the event SET_GAME_OVER is created/fired
It basically checks the collision between each laser and the obstacles
Methods
----------
update(self, hit_left, hit_right)
Checks if it's time to fire the event SET_GAME_OVER by making the collisions between each laser and obstacles
"""
def __init__(self):
super().__init__()
self.entity = Entity.get_instance()
def update(self, hit_left, hit_right):
# collisions algorithm
if self.entity.is_awake() and not hit_left and not hit_right:
# call set_game_over event
ev = pg.event.Event(Consts.CUSTOM_GAME_EVENT,
{"name": Consts.SET_GAME_OVER})
# pg.event.post(ev)
self.notify(ev)