1
0
forked from 0ad/0ad

Memoize some common entity lists in AI scripts.

This was SVN commit r8963.
This commit is contained in:
Ykkrosh 2011-02-21 02:14:45 +00:00
parent 4ba59510b5
commit 0be515280b
4 changed files with 35 additions and 12 deletions

View File

@ -4,3 +4,21 @@ function VectorDistance(a, b)
var dz = a[1] - b[1];
return Math.sqrt(dx*dx + dz*dz);
}
function MemoizeInit(obj)
{
obj._memoizeCache = {};
}
function Memoize(funcname, func)
{
return function() {
var args = funcname + '|' + Array.prototype.join.call(arguments, '|');
if (args in this._memoizeCache)
return this._memoizeCache[args];
var ret = func.apply(this, arguments);
this._memoizeCache[args] = ret;
return ret;
};
}

View File

@ -82,8 +82,8 @@ var EconomyManager = Class({
for (var type in this.gatherWeights)
numGatherers[type] = 0;
gameState.getOwnEntities().forEach(function(ent) {
if (ent.getMetadata("role") === "worker" && ent.getMetadata("subrole") === "gatherer")
gameState.getOwnEntitiesWithRole("worker").forEach(function(ent) {
if (ent.getMetadata("subrole") === "gatherer")
numGatherers[ent.getMetadata("gather-type")] += 1;
});
@ -111,8 +111,8 @@ var EconomyManager = Class({
// later we could add some timer that redistributes workers based on
// resource demand.
var idleWorkers = gameState.getOwnEntities().filter(function(ent) {
return (ent.getMetadata("role") === "worker" && ent.isIdle());
var idleWorkers = gameState.getOwnEntitiesWithRole("worker").filter(function(ent) {
return ent.isIdle();
});
if (idleWorkers.length)
@ -166,9 +166,7 @@ var EconomyManager = Class({
if (!foundations.length)
return;
var workers = gameState.getOwnEntities().filter(function(ent) {
return (ent.getMetadata("role") === "worker");
});
var workers = gameState.getOwnEntitiesWithRole("worker");
var builderWorkers = workers.filter(function(ent) {
return (ent.getMetadata("subrole") === "builder");

View File

@ -6,6 +6,8 @@ var GameState = Class({
_init: function(ai)
{
MemoizeInit(this);
this.ai = ai;
this.timeElapsed = ai.timeElapsed;
this.templates = ai.templates;
@ -47,10 +49,17 @@ var GameState = Class({
return this.ai.passabilityClasses[name];
},
getOwnEntities: function()
getOwnEntities: Memoize('getOwnEntities', function()
{
return this.entities.filter(function(ent) { return ent.isOwn(); });
},
}),
getOwnEntitiesWithRole: Memoize('getOwnEntitiesWithRole', function(role)
{
return this.getOwnEntities().filter(function(ent) {
return (ent.getMetadata("role") === role);
});
}),
countEntitiesWithType: function(type)
{

View File

@ -52,9 +52,7 @@ var MilitaryAttackManager = Class({
);
// Find the units ready to join the attack
var pending = gameState.entities.filter(function(ent) {
return (ent.getMetadata("role") === "attack-pending");
});
var pending = gameState.getOwnEntitiesWithRole("attack-pending");
// If we have enough units yet, start the attack
if (pending.length >= this.targetSquadSize)