-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevents.js
75 lines (61 loc) · 2.19 KB
/
events.js
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
// This is the place to define event names.
const EVENT = {
'WAKEUP': 'wakeup',
'EXIT_SHIP': 'exit_ship',
'EXAMINE_SHIP': 'examine_ship',
'EXAMINE_DEBRIS': 'examine_debris',
'EXAMINE_COINS': 'examine_coins',
'EXAMINE_NOTHING': 'examine_nothing',
'HUNGRY1': 'hungry1',
'HUNGRY2': 'hungry2',
'HUNGRY3': 'hungry3',
'STARVATION': 'starvation'
};
/* This class is deprecated until we find a better usage for it
* This class implements the Publish-Subscribe pattern in order
* to manage an event system for game events.
class EventSystem{
constructor(){
// Object containing events and their coresponding callbacks
// to be executed on publish.
this.subscribers = {};
// Explicit binding so we don't lose context of the methods.
// Might not be required but just in case.
this.subscribe = this.subscribe.bind(this);
this.publish = this.publish.bind(this);
}
/*
* Adds the event to the list of listening subscribers
* along with the callback to be executed.
* event: string. Name of the event
* callback: function. The function to be executed when the event is called.
subscribe(event, callback) {
// Check if event exists, create if not.
this.subscribers[event] = this.subscribers[event] || [];
this.subscribers[event] = this.subscribers[event].concat([callback]);
}
/*
* Calls the appropriate callback(s) for the given event
* for the subscribers to notice.
* event: string. Event name to dispatch.
* args: array. List of arguments to call the callback function with.
publish(event, ...args){
if (this.subscribers && this.subscribers[event]){
this.subscribers[event].forEach((callback) => {
// TODO: functions should not be declared on the global scope (aka window).
// We should make a Game class and declare there the callback
// functions OR make them anonymous and declare inside subscribeGameEvents.
callback.apply(window, args);
});
}
}
/*
* This is the place to register all possible game events.
* eventSys: EventSystem. The object that keeps track of the events.
subscribeGameEvents(player) {
this.subscribe(EVENT.WAKEUP, promptContinue);
this.subscribe(EVENT.EXIT_SHIP, exitShip);
this.subscribe(EVENT.STARVATION, player.die);
}
}
*/