-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathqueueAction() system.js
107 lines (100 loc) · 2.51 KB
/
queueAction() system.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
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
// helam 3 January 2017 at 01:37
/**
* Used to create unique id numbers
* Author: Helam
* @returns {*|number}
*/
global.getId = function() {
if (Memory.globalId == undefined || Memory.globalId > 10000) {
Memory.globalId = 0;
}
Memory.globalId = Memory.globalId + 1;
return Memory.globalId;
};
/**
* INTERNAL USE ONLY.
* Author: Helam
* @param id
* @param action
* @param stopResult
* @param tickLimit
* @param startTime
* @constructor
*/
global.QueuedAction = function({
id,
action,
stopResult,
tickLimit,
startTime
}) {
this.id = id || getId();
this.action = id ? action : `return (${action.toString()})()`;
this.stopResult = stopResult;
this.tickLimit = tickLimit || 100;
this.startTime = startTime || Game.time;
};
/**
* INTERNAL USE ONLY.
* Run the queued action and return false if:
* 1. There is an error
* 2. The return value of the queued action is equal to the stopResult
* 3. The queued action has been run [tickLimit] number of times
* Author: Helam
* @returns {boolean}
*/
QueuedAction.prototype.run = function() {
let func = Function(this.action);
try {
let result = func();
if (result === this.stopResult) {
return false;
}
if (Game.time - this.startTime >= this.tickLimit) {
return false;
}
} catch (error) {
console.log(error.stack);
return false;
}
return true;
};
/**
* INTERNAL USE ONLY.
* Add the action to the queue.
* Author: Helam
*/
QueuedAction.prototype.add = function() {
Memory.queuedActions[this.id] = this;
};
/**
* INTERNAL USE ONLY.
* Remove the queued action from the queue.
* Author: Helam
*/
QueuedAction.prototype.clear = function() {
delete Memory.queuedActions[this.id];
};
/**
* Put somewhere in the main loop.
* Calls all of the queued actions.
* Author: Helam
*/
global.runQueuedActions = function() {
Object.keys(Memory.queuedActions || {}).forEach(id => {
let action = new QueuedAction(Memory.queuedActions[id]);
if (!action.run()) action.clear();
});
};
/**
* Call this function to add an action to the queue.
* Author: Helam
* @param action {Function} (the function you want called)
* @param stopResult (return value of the function that should signal removing the action from the queue)
* @param tickLimit (max number of ticks to call the function. default 100)
*/
global.queueAction = function(action, stopResult, tickLimit) {
if (!Memory.queuedActions) Memory.queuedActions = {};
let newAction = new QueuedAction({ action, stopResult, tickLimit });
newAction.add();
};