-
Notifications
You must be signed in to change notification settings - Fork 12
/
Task.ts
294 lines (259 loc) · 8.94 KB
/
Task.ts
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
/**
* Creep tasks setup instructions
*
* Javascript:
* 1. In main.js: require("creep-tasks");
* 2. As needed: var Tasks = require("<path to creep-tasks.js>");
*
* Typescript:
* 1. In main.ts: import "<path to index.ts>";
* 2. As needed: import {Tasks} from "<path to Tasks.ts>"
*
* If you use Traveler, change all occurrences of creep.moveTo() to creep.travelTo()
*/
import {initializeTask} from './utilities/initializer';
import {deref, derefRoomPosition} from './utilities/helpers';
export type targetType = { ref: string, pos: RoomPosition }; // overwrite this variable in derived classes to specify more precise typing
/* An abstract class for encapsulating creep actions. This generalizes the concept of "do action X to thing Y until
* condition Z is met" and saves a lot of convoluted and duplicated code in creep logic. A Task object contains
* the necessary logic for traveling to a target, performing a task, and realizing when a task is no longer sensible
* to continue.*/
export abstract class Task implements ITask {
static taskName: string;
name: string; // Name of the task type, e.g. 'upgrade'
_creep: { // Data for the creep the task is assigned to"
name: string; // Name of the creep
};
_target: { // Data for the target the task is directed to:
ref: string; // Target id or name
_pos: protoPos; // Target position's coordinates in case vision is lost
};
_parent: protoTask | null; // The parent of this task, if any. Task is changed to parent upon completion
tick: number;
settings: TaskSettings; // Settings for a given type of task; shouldn't be modified on an instance-basis
options: TaskOptions; // Options for a specific instance of a task
data: TaskData; // Data pertaining to a given instance of a task
constructor(taskName: string, target: targetType, options = {} as TaskOptions) {
// Parameters for the task
this.name = taskName;
this._creep = {
name: '',
};
if (target) { // Handles edge cases like when you're done building something and target disappears
this._target = {
ref : target.ref,
_pos: target.pos,
};
} else {
this._target = {
ref : '',
_pos: {
x : -1,
y : -1,
roomName: '',
}
};
}
this._parent = null;
this.settings = {
targetRange: 1, // range at which you can perform action
workOffRoad: false, // whether work() should be performed off road
oneShot : false, // remove this task once work() returns OK, regardless of validity
};
_.defaults(options, {
blind : false,
moveOptions: {},
});
this.tick = Game.time;
this.options = options;
this.data = {
quiet: true,
};
}
get proto(): protoTask {
return {
name : this.name,
_creep : this._creep,
_target: this._target,
_parent: this._parent,
options: this.options,
data : this.data,
tick : this.tick,
};
}
set proto(protoTask: protoTask) {
// Don't write to this.name; used in task switcher
this._creep = protoTask._creep;
this._target = protoTask._target;
this._parent = protoTask._parent;
this.options = protoTask.options;
this.data = protoTask.data;
this.tick = protoTask.tick;
}
// Getter/setter for task.creep
get creep(): Creep { // Get task's own creep by its name
return Game.creeps[this._creep.name];
}
set creep(creep: Creep) {
this._creep.name = creep.name;
}
// Dereferences the target
get target(): RoomObject | null {
return deref(this._target.ref);
}
// Dereferences the saved target position; useful for situations where you might lose vision
get targetPos(): RoomPosition {
// refresh if you have visibility of the target
if (this.target) {
this._target._pos = this.target.pos;
}
return derefRoomPosition(this._target._pos);
}
// Getter/setter for task parent
get parent(): Task | null {
return (this._parent ? initializeTask(this._parent) : null);
}
set parent(parentTask: Task | null) {
this._parent = parentTask ? parentTask.proto : null;
// If the task is already assigned to a creep, update their memory
if (this.creep) {
this.creep.task = this;
}
}
// Return a list of [this, this.parent, this.parent.parent, ...] as tasks
get manifest(): Task[] {
let manifest: Task[] = [this];
let parent = this.parent;
while (parent) {
manifest.push(parent);
parent = parent.parent;
}
return manifest;
}
// Return a list of [this.target, this.parent.target, ...] without fully instantiating the list of tasks
get targetManifest(): (RoomObject | null)[] {
let targetRefs: string[] = [this._target.ref];
let parent = this._parent;
while (parent) {
targetRefs.push(parent._target.ref);
parent = parent._parent;
}
return _.map(targetRefs, ref => deref(ref));
}
// Return a list of [this.target, this.parent.target, ...] without fully instantiating the list of tasks
get targetPosManifest(): RoomPosition[] {
let targetPositions: protoPos[] = [this._target._pos];
let parent = this._parent;
while (parent) {
targetPositions.push(parent._target._pos);
parent = parent._parent;
}
return _.map(targetPositions, protoPos => derefRoomPosition(protoPos));
}
// Fork the task, assigning a new task to the creep with this task as its parent
fork(newTask: Task): Task {
newTask.parent = this;
if (this.creep) {
this.creep.task = newTask;
}
return newTask;
}
// Test every tick to see if task is still valid
abstract isValidTask(): boolean;
// Test every tick to see if target is still valid
abstract isValidTarget(): boolean;
isValid(): boolean {
let validTask = false;
if (this.creep) {
validTask = this.isValidTask();
}
let validTarget = false;
if (this.target) {
validTarget = this.isValidTarget();
} else if (this.options.blind && !Game.rooms[this.targetPos.roomName]) {
// If you can't see the target's room but you have blind enabled, then that's okay
validTarget = true;
}
// Return if the task is valid; if not, finalize/delete the task and return false
if (validTask && validTarget) {
return true;
} else {
// Switch to parent task if there is one
this.finish();
return this.parent ? this.parent.isValid() : false;
}
}
moveToTarget(range = this.settings.targetRange): number {
if (this.options.moveOptions && !this.options.moveOptions.range) {
this.options.moveOptions.range = range;
}
return this.creep.moveTo(this.targetPos, this.options.moveOptions);
// return this.creep.travelTo(this.targetPos, this.options.moveOptions); // <- switch if you use Traveler
}
/* Moves to the next position on the agenda if specified - call this in some tasks after work() is completed */
moveToNextPos(): number | undefined {
if (this.options.nextPos) {
let nextPos = derefRoomPosition(this.options.nextPos);
return this.creep.moveTo(nextPos);
// return this.creep.travelTo(nextPos); // <- switch if you use Traveler
}
}
// Return expected number of ticks until creep arrives at its first destination; this requires Traveler to work!
get eta(): number | undefined {
if (this.creep && (<any>this.creep.memory)._trav) {
return (<any>this.creep.memory)._trav.path.length;
}
}
// Execute this task each tick. Returns nothing unless work is done.
run(): number | undefined {
if (this.creep.pos.inRangeTo(this.targetPos, this.settings.targetRange) && !this.creep.pos.isEdge) {
if (this.settings.workOffRoad) {
// Move to somewhere nearby that isn't on a road
this.parkCreep(this.creep, this.targetPos, true);
}
let result = this.work();
if (this.settings.oneShot && result == OK) {
this.finish();
}
return result;
} else {
this.moveToTarget();
}
}
/* Bundled form of Zerg.park(); adapted from BonzAI codebase*/
protected parkCreep(creep: Creep, pos: RoomPosition = creep.pos, maintainDistance = false): number {
let road = _.find(creep.pos.lookFor(LOOK_STRUCTURES), s => s.structureType == STRUCTURE_ROAD);
if (!road) return OK;
let positions = _.sortBy(creep.pos.availableNeighbors(), (p: RoomPosition) => p.getRangeTo(pos));
if (maintainDistance) {
let currentRange = creep.pos.getRangeTo(pos);
positions = _.filter(positions, (p: RoomPosition) => p.getRangeTo(pos) <= currentRange);
}
let swampPosition;
for (let position of positions) {
if (_.find(position.lookFor(LOOK_STRUCTURES), s => s.structureType == STRUCTURE_ROAD)) continue;
let terrain = position.lookFor(LOOK_TERRAIN)[0];
if (terrain === 'swamp') {
swampPosition = position;
} else {
return creep.move(creep.pos.getDirectionTo(position));
}
}
if (swampPosition) {
return creep.move(creep.pos.getDirectionTo(swampPosition));
}
return creep.moveTo(pos);
// return creep.travelTo(pos); // <-- Switch if you use Traveler
}
// Task to perform when at the target
abstract work(): number;
// Finalize the task and switch to parent task (or null if there is none)
finish(): void {
this.moveToNextPos();
if (this.creep) {
this.creep.task = this.parent;
} else {
console.log(`No creep executing ${this.name}!`);
}
}
}