Compare commits

...

2 Commits

Author SHA1 Message Date
126f2d6bfc
[behavio-tree] add ParallelNode.tick() 2023-11-02 09:18:23 +08:00
dd9851674c
[utils] add class PriorityQueue 2023-11-02 09:17:34 +08:00
3 changed files with 58 additions and 4 deletions

View File

@ -31,9 +31,7 @@ export class ControlNode extends Node {
};
export class SequenceNode extends ControlNode {
constructor() {
super();
}
constructor() { super(); }
async tick(blackboard) {
for (let child of this.children) {
@ -47,6 +45,7 @@ export class FallbackNode extends ControlNode {
async tick(blackboard) {
for (let i = 0; i < this.children.length; i += 1) {
let child = this.children[i];
try {
await child.tick(blackboard);
break;
@ -60,5 +59,7 @@ export class FallbackNode extends ControlNode {
export class ParallelNode extends ControlNode {
constructor() { super(); }
async tick(blackboard) {}
tick(blackboard) {
return Promise.all(this.children.map(child => child(blackboard)));
}
}

View File

@ -4,3 +4,4 @@ export { readJsonFile, writeJsonFile, parseLogin, waitEvent,
export { Queue, QueueEmptyError } from './queue.mjs';
export { AsyncLock } from './async-lock.mjs';
export { Task, TaskInteruptedError } from './task.mjs';
export { PriorityQueue } from './priority-queue.mjs';

52
utils/priority-queue.mjs Normal file
View File

@ -0,0 +1,52 @@
export class PriorityQueue {
constructor() {
this.val = [null];
}
push(value, priority) {
if (priority == null) {
priority = value;
}
this.val.push([value, priority]);
let id = this.val.length - 1;
while (id > 1 && this.val[id][1] > this.val[id >>> 1][1]) {
const kid = id >>> 1;
[this.val[id], this.val[kid]] = [this.val[kid], this.val[id]];
id = kid;
}
return this;
}
pop() {
let lv = this.val.pop();
if (this.val.length == 1) { return lv; }
let res = this.val[1];
this.val[1] = lv;
let id = 1;
while (id * 2 < this.val.length) {
if (this.val[id][1] > this.val[id * 2][1] && (id * 2 + 1 >= this.val.length || this.val[id][1] > this.val[id * 2 + 1][1])) {
break;
}
let kid = (id * 2 + 1 >= this.val.length || this.val[id * 2][1] > this.val[id * 2 + 1][1]) ? id * 2 : id * 2 + 1;
[this.val[id], this.val[kid]] = [this.val[kid], this.val[id]];
id = kid;
}
return res;
}
top() {
return this.val[1];
}
size() {
return this.val.length - 1;
}
empty() {
return this.size() == 0;
}
};