Skip to content

Commit

Permalink
Memoize path
Browse files Browse the repository at this point in the history
  • Loading branch information
mhluska committed Jun 12, 2016
1 parent 7dcd2fa commit 85baf80
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
4 changes: 2 additions & 2 deletions source/queue.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// TODO(maros): Implement using linked list if widely used.
class Queue {
constructor(data = [], maxSize = Infinity) {
this._data = data;
constructor(data, maxSize = Infinity) {
this._data = data || [];
this._maxSize = maxSize;
}

Expand Down
24 changes: 12 additions & 12 deletions source/snake.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,26 +135,26 @@ module.exports = class Snake {
return false;
}

this.world.enable(this.position);
// Recompute path.
if (this._path.empty() || Voxel.findOrCreate(this._path.peek()).type === 'snake') {

// Find new target.
let start = Voxel.findOrCreate(this.position);
let path = Graph.dijkstra(start, node => node.type === 'food');
this.world.enable(this.position);

this.world.disable(this.position, 'snake');
// Find new target.
const start = Voxel.findOrCreate(this.position);
this._path = new Queue(Graph.dijkstra(start, node => node.type === 'food'));

if (!path) {
return false;
}
// Remove the current position.
this._path.dequeue();

path.shift();
this.world.disable(this.position, 'snake');
}

if (path.length === 0) {
if (this._path.empty()) {
return false;
}

// TODO(maros): Memoize path.
return path[0].position;
return this._path.dequeue().position;
}

_nextPositionManual() {
Expand Down

0 comments on commit 85baf80

Please sign in to comment.