1
0
forked from 0ad/0ad

remove aegis bot

This was SVN commit r15756.
This commit is contained in:
mimo 2014-09-15 20:19:00 +00:00
parent 66a2fe6308
commit 3f1db1ef01
28 changed files with 0 additions and 8399 deletions

View File

@ -1,13 +0,0 @@
Aegis. AI for 0 A.D. ( http://play0ad.com/ ). An effort to improve over two bots: qBot (by Quantumstate, based on TestBot) and Marilyn (by Wraitii, itself based on qBot).
Install by placing files into the data/mods/public/simulation/ai/aegis folder.
You may want to set "debug : true" in config.js if you are developping, you will get a better understanding of what the AI does. There are also many commented debug outputs, and many commented map outputs that you may want to uncomment.
This bot has been made default as of Alpha 13. It features some technological support, early naval support, better economic management, better defense and better attack management (over qBot). It is generally much stronger than the former, and should hopefully be able to handle more situations properly. It is, however, not faultless.
Please report any error to the wildfire games forum ( http://www.wildfiregames.com/forum/index.php?act=idx ), and thanks for playing!
Requires common-api;
(note: no saved game support as of yet).

View File

@ -1 +0,0 @@
Engine.IncludeModule("common-api");

View File

@ -1,300 +0,0 @@
var AEGIS = (function() {
var m = {};
// "local" global variables for stuffs that will need a unique ID
// Note that since order of loading is alphabetic, this means this file must go before any other file using them.
m.playerGlobals = [];
m.AegisBot = function AegisBot(settings) {
API3.BaseAI.call(this, settings);
this.turn = 0;
this.playedTurn = 0;
this.Config = new m.Config();
this.Config.updateDifficulty(settings.difficulty);
this.Config.personality = settings.personality;
this.firstTime = true;
this.savedEvents = {};
this.defcon = 5;
this.defconChangeTime = -10000000;
};
m.AegisBot.prototype = new API3.BaseAI();
m.AegisBot.prototype.CustomInit = function(gameState, sharedScript) {
this.initPersonality(this.gameState);
this.priorities = this.Config.priorities;
// this.queues can only be modified by the queue manager or things will go awry.
this.queues = {};
for (var i in this.priorities)
this.queues[i] = new m.Queue();
this.queueManager = new m.QueueManager(this.Config, this.queues, this.priorities);
this.HQ = new m.HQ(this.Config);
gameState.Config = this.Config;
m.playerGlobals[PlayerID] = {};
m.playerGlobals[PlayerID].uniqueIDBOPlans = 0; // training/building/research plans
m.playerGlobals[PlayerID].uniqueIDBases = 1; // base manager ID. Starts at one because "0" means "no base" on the map
m.playerGlobals[PlayerID].uniqueIDTPlans = 1; // transport plans. starts at 1 because 0 might be used as none.
m.playerGlobals[PlayerID].uniqueIDArmy = 0;
this.HQ.init(gameState,this.queues);
m.debug ("Initialized with the difficulty " + this.Config.difficulty);
var ents = gameState.getEntities().filter(API3.Filters.byOwner(this.player));
var myKeyEntities = ents.filter(function(ent) {
return ent.hasClass("CivCentre");
});
if (myKeyEntities.length == 0){
myKeyEntities = gameState.getEntities().filter(API3.Filters.byOwner(this.player));
}
var filter = API3.Filters.byClass("CivCentre");
var enemyKeyEntities = gameState.getEntities().filter(API3.Filters.not(API3.Filters.byOwner(this.player))).filter(filter);
if (enemyKeyEntities.length == 0){
enemyKeyEntities = gameState.getEntities().filter(API3.Filters.not(API3.Filters.byOwner(this.player)));
}
this.myIndex = this.accessibility.getAccessValue(myKeyEntities.toEntityArray()[0].position());
this.pathFinder = new API3.aStarPath(gameState, false, true);
this.pathsToMe = [];
this.pathInfo = { "angle" : 0, "needboat" : true, "mkeyPos" : myKeyEntities.toEntityArray()[0].position(), "ekeyPos" : enemyKeyEntities.toEntityArray()[0].position() };
// First path has a sampling of 3, which ensures we'll get at least one path even on Acropolis. The others are 6 so might fail.
var pos = [this.pathInfo.mkeyPos[0] + 150*Math.cos(this.pathInfo.angle),this.pathInfo.mkeyPos[1] + 150*Math.sin(this.pathInfo.angle)];
var path = this.pathFinder.getPath(this.pathInfo.ekeyPos, pos, 2, 2);// uncomment for debug:*/, 300000, gameState);
//Engine.DumpImage("initialPath" + this.player + ".png", this.pathFinder.TotorMap.map, this.pathFinder.TotorMap.width,this.pathFinder.TotorMap.height,255);
if (path !== undefined && path[1] !== undefined && path[1] == false) {
// path is viable and doesn't require boating.
// blackzone the last two waypoints.
this.pathFinder.markImpassableArea(path[0][0][0],path[0][0][1],20);
this.pathsToMe.push(path[0][0][0]);
this.pathInfo.needboat = false;
}
this.pathInfo.angle += Math.PI/3.0;
}
m.AegisBot.prototype.OnUpdate = function(sharedScript) {
if (this.gameFinished){
return;
}
for (var i in this.events)
{
if(this.savedEvents[i] !== undefined)
this.savedEvents[i] = this.savedEvents[i].concat(this.events[i]);
else
this.savedEvents[i] = this.events[i];
}
// Run the update every n turns, offset depending on player ID to balance the load
if ((this.turn + this.player) % 8 == 5) {
Engine.ProfileStart("Aegis bot (player " + this.player +")");
this.playedTurn++;
if (this.gameState.getOwnEntities().length === 0){
Engine.ProfileStop();
return; // With no entities to control the AI cannot do anything
}
if (this.pathInfo !== undefined)
{
var pos = [this.pathInfo.mkeyPos[0] + 150*Math.cos(this.pathInfo.angle),this.pathInfo.mkeyPos[1] + 150*Math.sin(this.pathInfo.angle)];
var path = this.pathFinder.getPath(this.pathInfo.ekeyPos, pos, 6, 5);// uncomment for debug:*/, 300000, this.gameState);
if (path !== undefined && path[1] !== undefined && path[1] == false) {
// path is viable and doesn't require boating.
// blackzone the last two waypoints.
this.pathFinder.markImpassableArea(path[0][0][0],path[0][0][1],20);
this.pathsToMe.push(path[0][0][0]);
this.pathInfo.needboat = false;
}
this.pathInfo.angle += Math.PI/3.0;
if (this.pathInfo.angle > Math.PI*2.0)
{
if (this.pathInfo.needboat)
{
m.debug ("Assuming this is a water map");
this.HQ.waterMap = true;
}
delete this.pathFinder;
delete this.pathInfo;
}
}
var townPhase = this.gameState.townPhase();
var cityPhase = this.gameState.cityPhase();
// try going up phases.
// TODO: softcode this more
if (this.gameState.canResearch(townPhase,true) && this.gameState.getPopulation() >= this.Config.Economy.villagePopCap - 10
&& this.gameState.findResearchers(townPhase,true).length != 0 && this.queues.majorTech.length() === 0)
{
var plan = new m.ResearchPlan(this.gameState, townPhase, true);
plan.lastIsGo = false;
plan.onStart = function (gameState) { gameState.ai.HQ.econState = "growth"; gameState.ai.HQ.OnTownPhase(gameState) };
plan.isGo = function (gameState) {
var ret = gameState.getPopulation() >= gameState.Config.Economy.villagePopCap
if (ret && !this.lastIsGo)
this.onGo(gameState);
else if (!ret && this.lastIsGo)
this.onNotGo(gameState);
this.lastIsGo = ret;
return ret;
};
plan.onGo = function (gameState) { gameState.ai.HQ.econState = "townPhasing"; m.debug ("Trying to reach TownPhase"); };
plan.onNotGo = function (gameState) { gameState.ai.HQ.econState = "growth"; };
this.queues.majorTech.addItem(plan);
m.debug ("Planning Town Phase");
} else if (this.gameState.canResearch(cityPhase,true) && this.gameState.getTimeElapsed() > (this.Config.Economy.cityPhase*1000)
&& this.gameState.getOwnEntitiesByRole("worker", true).length > 85
&& this.gameState.findResearchers(cityPhase, true).length != 0 && this.queues.majorTech.length() === 0
&& this.queues.civilCentre.length() === 0) {
m.debug ("Trying to reach city phase");
this.queues.majorTech.addItem(new m.ResearchPlan(this.gameState, cityPhase));
}
// defcon cooldown
if (this.defcon < 5 && this.gameState.timeSinceDefconChange() > 20000)
{
this.defcon++;
m.debug ("updefconing to " +this.defcon);
if (this.defcon >= 4 && this.HQ.hasGarrisonedFemales)
this.HQ.ungarrisonAll(this.gameState);
}
this.HQ.update(this.gameState, this.queues, this.savedEvents);
this.queueManager.update(this.gameState);
/*
// Use this to debug informations about the metadata.
if (this.playedTurn % 10 === 0)
{
// some debug informations about units.
var units = this.gameState.getOwnEntities();
for (var i in units._entities)
{
var ent = units._entities[i];
if (!ent.isIdle())
continue;
warn ("Unit " + ent.id() + " is a " + ent._templateName);
if (sharedScript._entityMetadata[PlayerID][ent.id()])
{
var metadata = sharedScript._entityMetadata[PlayerID][ent.id()];
for (var j in metadata)
{
warn ("Metadata " + j);
if (typeof(metadata[j]) == "object")
warn ("Object");
else if (typeof(metadata[j]) == undefined)
warn ("Undefined");
else
warn(uneval(metadata[j]));
}
}
}
}*/
//if (this.playedTurn % 5 === 0)
// this.queueManager.printQueues(this.gameState);
// Generate some entropy in the random numbers (against humans) until the engine gets random initialised numbers
// TODO: remove this when the engine gives a random seed
var n = this.savedEvents["Create"].length % 29;
for (var i = 0; i < n; i++){
Math.random();
}
for (var i in this.savedEvents)
this.savedEvents[i] = [];
Engine.ProfileStop();
}
this.turn++;
};
// defines our core components strategy-wise.
// TODO: the sky's the limit here.
m.AegisBot.prototype.initPersonality = function(gameState)
{
this.aggressiveness = 0.5; // I'll try to keep this as a percent but it's basically arbitrary.
if (this.Config.difficulty >= 2)
this.aggressiveness = Math.random();
var agrThrsh = 0.8; // treshold for aggressiveness.
if (gameState.civ() == "athen")
agrThrsh = 0.6; // works very well with athens
if (this.aggressiveness > agrThrsh)
{
m.debug("Going the Rush route");
this.aggressiveness = 1.0;
// we'll try to pull in an attack at village phase.
this.Config.Military.defenceBuildingTime = 900;
this.Config.Military.popForBarracks1 = 0;
this.Config.Economy.villagePopCap = 75;
this.Config.Economy.cityPhase = 900;
this.Config.Economy.popForMarket = 80;
this.Config.Economy.popForFarmstead = 50;
this.Config.Economy.targetNumBuilders = 2;
this.Config.Economy.femaleRatio = 0.6;
this.Config.Defence.prudence = 0.5;
} else if (this.aggressiveness < 0.15) {
m.debug("Going the Boom route");
// Now and then Superboom
this.Config.Military.defenceBuildingTime = 600;
this.Config.Economy.cityPhase = 1000;
this.Config.Military.attackPlansStartTime = 1000;
this.Config.Military.popForBarracks1 = 39;
this.Config.Economy.villagePopCap = 50;
this.Config.Economy.femaleRatio = 1.0;
this.Config.Economy.popForMarket = 55;
this.Config.Economy.popForFarmstead = 55;
}
};
/*m.AegisBot.prototype.Deserialize = function(data, sharedScript)
{
};
// Override the default serializer
AegisBot.prototype.Serialize = function()
{
return {};
};*/
// For the moment we just use the debugging flag and the debugging function from the API.
// Maybe it will make sense in the future to separate them.
m.DebugEnabled = function()
{
return API3.DebugEnabled;
}
m.debug = function(output)
{
API3.debug(output);
}
return m;
}());

View File

@ -1,382 +0,0 @@
var AEGIS = function(m)
{
/* Defines an army
* An army is a collection of own entities and enemy entities.
* This doesn't use entity collections are they aren't really useful
* and it would probably slow the rest of the system down too much.
* All entities are therefore lists of ID
* Inherited by the defense manager and several of the attack manager's attack plan.
*/
m.Army = function(gameState, owner, ownEntities, foeEntities)
{
this.ID = m.playerGlobals[PlayerID].uniqueIDArmy++;
this.Config = owner.Config;
this.defenceRatio = this.Config.Defence.defenceRatio;
this.compactSize = this.Config.Defence.armyCompactSize;
this.breakawaySize = this.Config.Defence.armyBreakawaySize;
// average
this.foePosition = [0,0];
this.ownPosition = [0,0];
this.positionLastUpdate = gameState.getTimeElapsed();
// Some caching
// A list of our defenders that were tasked with attacking a particular unit
// This doesn't mean that they actually are since they could move on to something else on their own.
this.assignedAgainst = {};
// who we assigned against, for quick removal.
this.assignedTo = {};
// For substrengths, format is "name": [classes]
this.foeEntities = [];
this.foeStrength = 0;
this.foeSubStrength = {};
this.ownEntities = [];
this.ownStrength = 0;
this.ownSubStrength = {};
// actually add units
for (var i in foeEntities)
this.addFoe(gameState,foeEntities[i], true);
for (var i in ownEntities)
this.addOwn(gameState,ownEntities[i]);
this.recalculatePosition(gameState, true);
return true;
}
// if not forced, will only recalculate if on a different turn.
m.Army.prototype.recalculatePosition = function(gameState, force)
{
if (!force && this.positionLastUpdate === gameState.getTimeElapsed())
return;
var pos = [0,0];
if (this.foeEntities.length !== 0)
{
for each (var id in this.foeEntities)
{
var ent = gameState.getEntityById(id);
var epos = ent.position();
pos[0] += epos[0];
pos[1] += epos[1];
}
this.foePosition[0] = pos[0]/this.foeEntities.length;
this.foePosition[1] = pos[1]/this.foeEntities.length;
} else
this.foePosition = [0,0];
pos = [0,0];
if (this.ownEntities.length !== 0)
{
for each (var id in this.ownEntities)
{
var ent = gameState.getEntityById(id);
var epos = ent.position();
pos[0] += epos[0];
pos[1] += epos[1];
}
this.ownPosition[0] = pos[0]/this.ownEntities.length;
this.ownPosition[1] = pos[1]/this.ownEntities.length;
} else
this.ownPosition = [0,0];
this.positionLastUpdate = gameState.getTimeElapsed();
}
// helper
m.Army.prototype.recalculateStrengths = function (gameState)
{
this.ownStrength = 0;
this.foeStrength = 0;
// todo: deal with specifics.
for each (var id in this.foeEntities)
this.evaluateStrength(gameState.getEntityById(id));
for each (var id in this.ownEntities)
this.evaluateStrength(gameState.getEntityById(id), true);
}
// adds or remove the strength of the entity either to the enemy or to our units.
m.Army.prototype.evaluateStrength = function (ent, isOwn, remove)
{
var entStrength = m.getMaxStrength(ent);
if (remove)
entStrength *= -1;
if (isOwn)
this.ownStrength += entStrength;
else
this.foeStrength += entStrength;
// todo: deal with specifics.
}
// add an entity to the enemy army
// Will return true if the entity was added and false otherwise.
// won't recalculate our position but will dirty it.
m.Army.prototype.addFoe = function (gameState, enemyID, force)
{
if (this.foeEntities.indexOf(enemyID) !== -1)
return false;
var ent = gameState.getEntityById(enemyID);
if (ent === undefined || ent.position() === undefined)
return false;
// check distance
if (!force && API3.SquareVectorDistance(ent.position(), this.foePosition) > this.compactSize)
return false;
this.foeEntities.push(enemyID);
this.assignedAgainst[enemyID] = [];
this.positionLastUpdate = 0;
this.evaluateStrength(ent);
ent.setMetadata(PlayerID, "PartOfArmy", this.ID);
return true;
}
// returns true if the entity was removed and false otherwise.
// TODO: when there is a technology update, we should probably recompute the strengths, or weird stuffs will happen.
m.Army.prototype.removeFoe = function (gameState, enemyID, enemyEntity)
{
var idx = this.foeEntities.indexOf(enemyID);
if (idx === -1)
return false;
var ent = enemyEntity === undefined ? gameState.getEntityById(enemyID) : enemyEntity;
if (ent === undefined)
{
warn("Trying to remove a non-existing enemy entity, crashing for stacktrace");
xgzrg();
}
this.foeEntities.splice(idx, 1);
this.evaluateStrength(ent, false, true);
ent.setMetadata(PlayerID, "PartOfArmy", undefined);
this.assignedAgainst[enemyID] = undefined;
return true;
}
// adds a defender but doesn't assign him yet.
m.Army.prototype.addOwn = function (gameState, ID)
{
if (this.ownEntities.indexOf(ID) !== -1)
return false;
var ent = gameState.getEntityById(ID);
if (ent === undefined || ent.position() === undefined)
return false;
this.ownEntities.push(ID);
this.evaluateStrength(ent, true);
ent.setMetadata(PlayerID, "PartOfArmy", this.ID);
this.assignedTo[ID] = 0;
var formerRole = ent.getMetadata(PlayerID, "role");
var formerSubRole = ent.getMetadata(PlayerID, "subrole");
if (formerRole !== undefined)
ent.setMetadata(PlayerID,"formerRole", formerRole);
if (formerSubRole !== undefined)
ent.setMetadata(PlayerID,"formerSubRole", formerSubRole);
ent.setMetadata(PlayerID, "role", "defense");
ent.setMetadata(PlayerID, "subrole", "defending");
return true;
}
m.Army.prototype.removeOwn = function (gameState, ID, Entity)
{
var idx = this.ownEntities.indexOf(ID);
if (idx === -1)
return false;
var ent = Entity === undefined ? gameState.getEntityById(ID) : Entity;
if (ent === undefined)
{
warn( ID);
warn("Trying to remove a non-existing entity, crashing for stacktrace");
xgzrg();
}
this.ownEntities.splice(idx, 1);
this.evaluateStrength(ent, true, true);
ent.setMetadata(PlayerID, "PartOfArmy", undefined);
if (this.assignedTo[ID] !== 0)
{
var temp = this.assignedAgainst[this.assignedTo[ID]];
if (temp)
temp.splice(temp.indexOf(ID), 1);
}
this.assignedTo[ID] = undefined;
var formerRole = ent.getMetadata(PlayerID, "formerRole");
var formerSubRole = ent.getMetadata(PlayerID, "formerSubRole");
if (formerRole !== undefined)
ent.setMetadata(PlayerID,"role", formerRole);
else
ent.setMetadata(PlayerID,"role", undefined);
if (formerSubRole !== undefined)
ent.setMetadata(PlayerID,"subrole", formerSubRole);
else
ent.setMetadata(PlayerID,"subrole", undefined);
return true;
}
// this one is "undefined entity" proof because it's called at odd times.
// Orders a unit to attack an enemy.
// overridden by specific army classes.
m.Army.prototype.assignUnit = function (gameState, entID)
{
}
// resets the army properly.
// assumes we already cleared dead units.
m.Army.prototype.clear = function (gameState, events)
{
while(this.foeEntities.length > 0)
this.removeFoe(gameState,this.foeEntities[0]);
while(this.ownEntities.length > 0)
this.removeOwn(gameState,this.ownEntities[0]);
this.assignedAgainst = {};
this.assignedTo = {};
this.recalculateStrengths(gameState);
this.recalculatePosition(gameState);
}
// merge this army with another properly.
// assumes units are in only one army.
// also assumes that all have been properly cleaned up (no dead units).
m.Army.prototype.merge = function (gameState, otherArmy)
{
// copy over all parameters.
for (var i in otherArmy.assignedAgainst)
{
if (this.assignedAgainst[i] === undefined)
this.assignedAgainst[i] = otherArmy.assignedAgainst[i];
else
this.assignedAgainst[i] = this.assignedAgainst[i].concat(otherArmy.assignedAgainst[i]);
}
for (var i in otherArmy.assignedTo)
this.assignedTo[i] = otherArmy.assignedTo[i];
for each (var id in otherArmy.foeEntities)
this.addFoe(gameState, id);
// TODO: reassign those ?
for each (var id in otherArmy.ownEntities)
this.addOwn(gameState, id);
this.recalculatePosition(gameState, true);
this.recalculateStrengths(gameState);
return true;
}
// TODO: when there is a technology update, we should probably recompute the strengths, or weird stuffs might happen.
m.Army.prototype.checkEvents = function (gameState, events)
{
var renameEvents = events["EntityRenamed"]; // take care of promoted and packed units
var destroyEvents = events["Destroy"];
var convEvents = events["OwnershipChanged"];
var garriEvents = events["Garrison"];
// Warning the metadata is already cloned in shared.js. Futhermore, changes should be done before destroyEvents
// otherwise it would remove the old entity from this army list
// TODO we should may-be reevaluate the strength
for each (var msg in renameEvents)
{
if (this.foeEntities.indexOf(msg.entity) !== -1)
{
var idx = this.foeEntities.indexOf(msg.entity);
this.foeEntities[idx] = msg.newentity;
this.assignedAgainst[msg.newentity] = this.assignedAgainst[msg.entity];
this.assignedAgainst[msg.entity] = undefined;
for (var to in this.assignedTo)
if (this.assignedTo[to] == msg.entity)
this.assignedTo[to] = msg.newentity;
}
else if (this.ownEntities.indexOf(msg.entity) !== -1)
{
var idx = this.ownEntities.indexOf(msg.entity);
this.ownEntities[idx] = msg.newentity;
this.assignedTo[msg.newentity] = this.assignedTo[msg.entity];
this.assignedTo[msg.entity] = undefined;
for (var against in this.assignedAgainst)
{
if (!this.assignedAgainst[against])
continue;
if (this.assignedAgainst[against].indexOf(msg.entity) !== -1)
this.assignedAgainst[against][this.assignedAgainst[against].indexOf(msg.entity)] = msg.newentity;
}
}
}
for each (var msg in destroyEvents)
{
if (msg.entityObj === undefined)
continue;
if (msg.entityObj._entity.owner === PlayerID)
this.removeOwn(gameState, msg.entity, msg.entityObj);
else
this.removeFoe(gameState, msg.entity, msg.entityObj);
}
for each (var msg in garriEvents)
this.removeFoe(gameState, msg.entity);
for each (var msg in convEvents)
{
if (msg.to === PlayerID)
{
// we have converted an enemy, let's assign it as a defender
if (this.removeFoe(gameState, msg.entity))
this.addOwn(gameState, msg.entity);
} else if (msg.from === PlayerID)
this.removeOwn(gameState, msg.entity); // TODO: add allies
}
}
// assumes cleaned army.
// this only checks for breakaways.
m.Army.prototype.onUpdate = function (gameState)
{
var breakaways = [];
// TODO: assign unassigned defenders, cleanup of a few things.
// perhaps occasional strength recomputation
// occasional update or breakaways, positions…
if (gameState.getTimeElapsed() - this.positionLastUpdate > 5000)
{
this.recalculatePosition(gameState);
this.positionLastUpdate = gameState.getTimeElapsed();
// Check for breakaways.
for (var i = 0; i < this.foeEntities.length; ++i)
{
var id = this.foeEntities[i];
var ent = gameState.getEntityById(id);
if (API3.SquareVectorDistance(ent.position(), this.foePosition) > this.breakawaySize)
{
breakaways.push(id);
if(this.removeFoe(gameState, id))
i--;
}
}
this.recalculatePosition(gameState);
}
return breakaways;
}
return m;
}(AEGIS);

View File

@ -1,156 +0,0 @@
var AEGIS = function(m)
{
// Specialization of Armies used by the defense manager.
m.DefenseArmy = function(gameState, defManager, ownEntities, foeEntities)
{
if (!m.Army.call(this, gameState, defManager, ownEntities, foeEntities))
return false;
this.watchTSMultiplicator = this.Config.Defence.armyStrengthWariness;
this.watchDecrement = this.Config.Defence.prudence;
this.foeSubStrength = {
"spear" : ["Infantry", "Spear"], //also pikemen
"sword" : ["Infantry", "Sword"],
"ranged" : ["Infantry", "Ranged"],
"meleeCav" : ["Cavalry", "Melee"],
"rangedCav" : ["Cavalry", "Ranged"],
"Elephant" : ["Elephant"],
"meleeSiege" : ["Siege", "Melee"],
"rangedSiege" : ["Siege", "Ranged"]
};
this.ownSubStrength = {
"spear" : ["Infantry", "Spear"], //also pikemen
"sword" : ["Infantry", "Sword"],
"ranged" : ["Infantry", "Ranged"],
"meleeCav" : ["Cavalry", "Melee"],
"rangedCav" : ["Cavalry", "Ranged"],
"Elephant" : ["Elephant"],
"meleeSiege" : ["Siege", "Melee"],
"rangedSiege" : ["Siege", "Ranged"]
};
this.checkDangerosity(gameState); // might push us to 1.
this.watchLevel = this.foeStrength * this.watchTSMultiplicator;
return true;
}
m.DefenseArmy.prototype = Object.create(m.Army.prototype);
m.DefenseArmy.prototype.assignUnit = function (gameState, entID)
{
// we'll assume this defender is ours already.
// we'll also override any previous assignment
var ent = gameState.getEntityById(entID);
if (!ent)
return false;
// TODO: improve the logic in there.
var maxVal = 1000000;
var maxEnt = -1;
for each (var id in this.foeEntities)
{
var eEnt = gameState.getEntityById(id);
if (!eEnt) // probably can't happen.
continue;
if (maxVal > this.assignedAgainst[id].length)
{
maxVal = this.assignedAgainst[id].length;
maxEnt = id;
}
}
if (maxEnt === -1)
return false;
// let's attack id
this.assignedAgainst[maxEnt].push(entID);
this.assignedTo[entID] = maxEnt;
ent.attack(maxEnt);
return true;
}
// TODO: this should return cleverer results ("needs anti-elephant"…)
m.DefenseArmy.prototype.needsDefenders = function (gameState, events)
{
// some preliminary checks because we don't update for tech
if (this.foeStrength < 0 || this.ownStrength < 0)
this.recalculateStrengths(gameState);
if (this.foeStrength * this.defenceRatio < this.ownStrength)
return false;
return this.foeStrength * this.defenceRatio - this.ownStrength;
}
m.DefenseArmy.prototype.getState = function (gameState)
{
if (this.foeEntities.length === 0)
return 0;
if (this.state === 2)
return 2;
if (this.watchLevel > 0)
return 1;
return 0;
}
// check if we should remain at state 2 or drift away
m.DefenseArmy.prototype.checkDangerosity = function (gameState)
{
this.territoryMap = m.createTerritoryMap(gameState);
// right now we'll check if our position is "enemy" or not.
if (this.territoryMap.getOwner(this.ownPosition) !== PlayerID)
this.state = 1;
else if (this.state === 1)
this.state = 2;
}
m.DefenseArmy.prototype.update = function (gameState)
{
var breakaways = this.onUpdate(gameState);
this.checkDangerosity(gameState);
var normalWatch = this.foeStrength * this.watchTSMultiplicator;
if (this.state === 2)
this.watchLevel = normalWatch;
else if (this.watchLevel > normalWatch)
this.watchLevel = normalWatch;
else
this.watchLevel -= this.watchDecrement;
// TODO: deal with watchLevel?
return breakaways;
}
m.DefenseArmy.prototype.debug = function (gameState)
{
m.debug(" ");
m.debug ("Army " + this.ID)
// m.debug ("state " + this.state);
// m.debug ("WatchLevel " + this.watchLevel);
// m.debug ("Entities " + this.foeEntities.length);
// m.debug ("Strength " + this.foeStrength);
// debug (gameState.getEntityById(ent)._templateName + ", ID " + ent);
//debug ("Defenders " + this.ownEntities.length);
for each (ent in this.foeEntities)
{
if (gameState.getEntityById(ent) !== undefined)
{
m.debug (gameState.getEntityById(ent)._templateName + ", ID " + ent);
Engine.PostCommand(PlayerID,{"type": "set-shading-color", "entities": [ent], "rgb": [0.5,0,0]});
} else
m.debug("ent " + ent);
}
//debug ("Strength " + this.ownStrength);
m.debug ("");
}
return m;
}(AEGIS);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,121 +0,0 @@
var AEGIS = function(m)
{
// this defines the medium difficulty
m.Config = function() {
this.difficulty = 2; // 0 is sandbox, 1 is easy, 2 is medium, 3 is hard, 4 is very hard.
this.Military = {
"fortressLapseTime" : 540, // Time to wait between building 2 fortresses
"defenceBuildingTime" : 900, // Time to wait before building towers or fortresses
"attackPlansStartTime" : 0, // time to wait before attacking. Start as soon as possible.
"techStartTime" : 120, // time to wait before teching. Will only start after town phase so it's irrelevant.
"popForBarracks1" : 25,
"popForBarracks2" : 95,
"timeForBlacksmith" : 900,
};
this.Economy = {
"villagePopCap" : 40, // How many units we want before aging to town.
"cityPhase" : 840, // time to start trying to reach city phase
"popForMarket" : 50,
"popForFarmstead" : 35,
"dockStartTime" : 240, // Time to wait before building the dock
"techStartTime" : 0, // time to wait before teching.
"targetNumBuilders" : 1.5, // Base number of builders per foundation.
"femaleRatio" : 0.5, // percent of females among the workforce.
"initialFields" : 5
};
// Note: attack settings are set directly in attack_plan.js
// defence
this.Defence =
{
"defenceRatio" : 2, // see defence.js for more info.
"armyCompactSize" : 2000, // squared. Half-diameter of an army.
"armyBreakawaySize" : 3500, // squared.
"armyMergeSize" : 1400, // squared.
"armyStrengthWariness" : 2, // Representation of how important army strength is for its "watch level" (see defense-helper.js).
"prudence" : 1 // Representation of how quickly we'll forget about a dangerous army.
};
// military
this.buildings =
{
"moderate" : {
"default" : [ "structures/{civ}_barracks" ]
},
"advanced" : {
"default" : [],
"hele" : [ "structures/{civ}_gymnasion" ],
"athen" : [ "structures/{civ}_gymnasion" ],
"spart" : [ "structures/{civ}_syssiton" ],
"cart" : [ "structures/{civ}_embassy_celtic",
"structures/{civ}_embassy_iberian", "structures/{civ}_embassy_italiote" ],
"celt" : [ "structures/{civ}_kennel" ],
"pers" : [ "structures/{civ}_fortress", "structures/{civ}_stables", "structures/{civ}_apadana" ],
"rome" : [ "structures/{civ}_army_camp" ],
"maur" : [ "structures/{civ}_elephant_stables"]
},
"fort" : {
"default" : [ "structures/{civ}_fortress" ],
"celt" : [ "structures/{civ}_fortress_b", "structures/{civ}_fortress_g" ]
}
};
this.priorities =
{
"villager" : 30, // should be slightly lower than the citizen soldier one because otherwise they get all the food
"citizenSoldier" : 60,
"ships" : 70,
"house" : 350,
"dropsites" : 120,
"field" : 500,
"economicBuilding" : 90,
"militaryBuilding" : 240, // set to something lower after the first barracks.
"defenceBuilding" : 70,
"civilCentre" : 950,
"majorTech" : 700,
"minorTech" : 40
};
};
//Config.prototype = new BaseConfig();
m.Config.prototype.updateDifficulty = function(difficulty)
{
this.difficulty = difficulty;
// changing settings based on difficulty.
if (this.difficulty === 1)
{
this.Military.defenceBuildingTime = 1200;
this.Military.attackPlansStartTime = 960;
this.Military.popForBarracks1 = 35;
this.Military.popForBarracks2 = 150; // shouldn't reach it
this.Military.popForBlacksmith = 150; // shouldn't reach it
this.Economy.cityPhase = 1800;
this.Economy.popForMarket = 80;
this.Economy.techStartTime = 600;
this.Economy.femaleRatio = 0.6;
this.Economy.initialFields = 1;
// Config.Economy.targetNumWorkers will be set by AI scripts.
}
else if (this.difficulty === 0)
{
this.Military.defenceBuildingTime = 450;
this.Military.attackPlansStartTime = 9600000; // never
this.Military.popForBarracks1 = 60;
this.Military.popForBarracks2 = 150; // shouldn't reach it
this.Military.popForBlacksmith = 150; // shouldn't reach it
this.Economy.cityPhase = 240000;
this.Economy.popForMarket = 200;
this.Economy.techStartTime = 1800;
this.Economy.femaleRatio = 0.2;
this.Economy.initialFields = 1;
// Config.Economy.targetNumWorkers will be set by AI scripts.
}
};
return m;
}(AEGIS);

View File

@ -1,7 +0,0 @@
{
"name": "Aegis Bot",
"description": "[color=\"255 0 0 255\"]NO LONGER SUPPORTED[/color] \n Aegis is an improvement of earlier bots by Wratii. Note that it doesn't support saved games or naval maps.",
"moduleName" : "AEGIS",
"constructor": "AegisBot",
"useShared": true
}

View File

@ -1,348 +0,0 @@
var AEGIS = function(m)
{
m.Defence = function(Config)
{
this.armies = []; // array of "army" Objects. See defence-helper.js
this.Config = Config;
}
m.Defence.prototype.init = function(gameState)
{
this.armyMergeSize = this.Config.Defence.armyMergeSize;
this.dangerMap = new API3.Map(gameState.sharedScript);
}
m.Defence.prototype.update = function(gameState, events)
{
Engine.ProfileStart("Defence Manager");
this.territoryMap = m.createTerritoryMap(gameState);
this.releasedDefenders = []; // array of defenders released by armies this turn.
this.checkEnemyArmies(gameState,events);
this.checkEnemyUnits(gameState);
this.assignDefenders(gameState);
// debug
/*debug ("");
debug ("");
debug ("Armies: " +this.armies.length);
for (var i in this.armies)
this.armies[i].debug(gameState);
*/
this.MessageProcess(gameState,events);
Engine.ProfileStop();
};
m.Defence.prototype.makeIntoArmy = function(gameState, entityID)
{
// Try to add it to an existing army.
for (var o in this.armies)
{
if (this.armies[o].addFoe(gameState,entityID))
return; // over
}
// Create a new army for it.
var army = new m.DefenseArmy(gameState, this, [], [entityID]);
this.armies.push(army);
}
// TODO: this algorithm needs to be improved, sorta.
m.Defence.prototype.isDangerous = function(gameState, entity)
{
if (!entity.position())
return false;
if (this.territoryMap.getOwner(entity.position()) === entity.owner() || entity.attackTypes() === undefined)
return false;
var myBuildings = gameState.getOwnStructures();
for (var i in myBuildings._entities)
if (API3.SquareVectorDistance(myBuildings._entities[i].position(), entity.position()) < 6000)
return true;
return false;
}
m.Defence.prototype.checkEnemyUnits = function(gameState)
{
var self = this;
// loop through enemy units
var nbPlayers = gameState.sharedScript.playersData.length - 1;
var i = 1 + gameState.ai.playedTurn % nbPlayers;
if (i === PlayerID && i !== nbPlayers)
i++;
else if (i === PlayerID)
i = 1;
if (gameState.isPlayerAlly(i))
return;
var filter = API3.Filters.and(API3.Filters.byClass("Unit"), API3.Filters.byOwner(i));
var enemyUnits = gameState.updatingGlobalCollection("player-" +i + "-units", filter);
enemyUnits.forEach( function (ent) {
// first check: is this unit already part of an army.
if (ent.getMetadata(PlayerID, "PartOfArmy") !== undefined)
return;
if (ent.attackTypes() === undefined || ent.hasClass("Support") || ent.hasClass("Ship"))
return;
// check if unit is dangerous "a priori"
if (self.isDangerous(gameState,ent))
self.makeIntoArmy(gameState,ent.id());
});
}
m.Defence.prototype.checkEnemyArmies = function(gameState, events)
{
var self = this;
for (var o = 0; o < this.armies.length; ++o)
{
var army = this.armies[o];
army.checkEvents(gameState, events); // must be called every turn for all armies
// this returns a list of IDs: the units that broke away from the army for being too far.
var breakaways = army.update(gameState);
for (var u in breakaways)
{
// assume dangerosity
this.makeIntoArmy(gameState,breakaways[u]);
}
if (army.getState(gameState) === 0)
{
army.clear(gameState);
this.armies.splice(o--,1);
continue;
}
}
// Check if we can't merge it with another.
for (var o = 0; o < this.armies.length; ++o)
{
var army = this.armies[o];
for (var p = o+1; p < this.armies.length; ++p)
{
var otherArmy = this.armies[p];
if (otherArmy.state !== army.state)
continue;
if (API3.SquareVectorDistance(army.foePosition, otherArmy.foePosition) < this.armyMergeSize)
{
// no need to clear here.
army.merge(gameState, otherArmy);
this.armies.splice(p--,1);
}
}
}
}
m.Defence.prototype.assignDefenders = function(gameState, events)
{
if (this.armies.length === 0)
return;
var armiesNeeding = [];
// Okay, let's add defenders
// TODO: this is dumb.
for (var i in this.armies)
{
var army = this.armies[i];
var needsDef = army.needsDefenders(gameState);
if (needsDef === false)
continue;
// Okay for now needsDef is the total needed strength.
// we're dumb so we don't choose if we have a defender shortage.
armiesNeeding.push([army, needsDef]);
}
if (armiesNeeding.length === 0)
return;
// let's get our potential units
// TODO: this should rather be a HQ function that returns viable plans.
var filter = API3.Filters.and(API3.Filters.and(API3.Filters.byHasMetadata(PlayerID,"plan"),
API3.Filters.not(API3.Filters.byHasMetadata(PlayerID, "PartOfArmy"))),
API3.Filters.and(API3.Filters.not(API3.Filters.byMetadata(PlayerID,"subrole","walking")),
API3.Filters.not(API3.Filters.byMetadata(PlayerID,"subrole","attacking"))));
var potentialDefendersOne = gameState.getOwnUnits().filter(filter).toIdArray();
filter = API3.Filters.and(API3.Filters.and(API3.Filters.not(API3.Filters.byHasMetadata(PlayerID,"plan")),
API3.Filters.not(API3.Filters.byHasMetadata(PlayerID, "PartOfArmy"))),
API3.Filters.byClassesOr(["Infantry","Cavalry"]));
var potentialDefendersTwo = gameState.getOwnUnits().filter(filter).toIdArray();
var potDefs = this.releasedDefenders.concat(potentialDefendersOne).concat(potentialDefendersTwo);
for (var i in armiesNeeding)
{
var army = armiesNeeding[i][0];
var need = armiesNeeding[i][1];
// TODO: this is what I'll want to improve, along with the choice above.
while (need > 0)
{
if (potDefs.length === 0)
return; // won't do anything anymore.
var ent = gameState.getEntityById(potDefs[0]);
if (ent.getMetadata(PlayerID, "PartOfArmy") !== undefined)
{
potDefs.splice(0,1);
continue;
}
var str = m.getMaxStrength(ent);
need -= str;
army.addOwn(gameState,potDefs[0]);
army.assignUnit(gameState, potDefs[0]);
potDefs.splice(0,1);
}
}
}
// this processes the attackmessages
// So that a unit that gets attacked will not be completely dumb.
// warning: big levels of indentation coming.
m.Defence.prototype.MessageProcess = function(gameState,events) {
/* var self = this;
var attackedEvents = events["Attacked"];
for (var key in attackedEvents){
var e = attackedEvents[key];
if (gameState.isEntityOwn(gameState.getEntityById(e.target))) {
var attacker = gameState.getEntityById(e.attacker);
var ourUnit = gameState.getEntityById(e.target);
// the attacker must not be already dead, and it must not be me (think catapults that miss).
if (attacker === undefined || attacker.owner() === PlayerID || attacker.position() === undefined)
continue;
var mapPos = this.dangerMap.gamePosToMapPos(attacker.position());
this.dangerMap.addInfluence(mapPos[0], mapPos[1], 4, 1, 'constant');
// disregard units from attack plans and defence.
if (ourUnit.getMetadata(PlayerID, "role") == "defence" || ourUnit.getMetadata(PlayerID, "role") == "attack")
continue;
var territory = this.territoryMap.getOwner(attacker.position());
if (attacker.owner() == 0)
{
if (ourUnit !== undefined && ourUnit.hasClass("Unit") && !ourUnit.hasClass("Support"))
ourUnit.attack(e.attacker);
else
{
ourUnit.flee(attacker);
ourUnit.setMetadata(PlayerID,"fleeing", gameState.getTimeElapsed());
}
if (territory === PlayerID)
{
// anyway we'll register the animal as dangerous, and attack it (note: only on our territory. Don't care otherwise).
this.listOfWantedUnits[attacker.id()] = new EntityCollection(gameState.sharedScript);
this.listOfWantedUnits[attacker.id()].addEnt(attacker);
this.listOfWantedUnits[attacker.id()].freeze();
this.listOfWantedUnits[attacker.id()].registerUpdates();
var filter = Filters.byTargetedEntity(attacker.id());
this.WantedUnitsAttacker[attacker.id()] = this.myUnits.filter(filter);
this.WantedUnitsAttacker[attacker.id()].registerUpdates();
}
} // Disregard military units except in our territory. Disregard all calls in enemy territory.
else if (territory == PlayerID || (territory != attacker.owner() && ourUnit.hasClass("Support")))
{
// TODO: this does not differentiate with buildings...
// These ought to be treated differently.
// units in attack plans will react independently, but we still list the attacks here.
if (attacker.hasClass("Structure")) {
// todo: we ultimately have to check wether it's a danger point or an isolated area, and if it's a danger point, mark it as so.
// Right now, to make the AI less gameable, we'll mark any surrounding resource as inaccessible.
// usual tower range is 80. Be on the safe side.
var close = gameState.getResourceSupplies("wood").filter(Filters.byDistance(attacker.position(), 90));
close.forEach(function (supply) { //}){
supply.setMetadata(PlayerID, "inaccessible", true);
});
} else {
// TODO: right now a soldier always retaliate... Perhaps it should be set in "Defence" mode.
// TODO: handle the ship case
if (attacker.hasClass("Ship"))
continue;
// This unit is dangerous. if it's in an army, it's being dealt with.
// if it's not in an army, it means it's either a lone raider, or it has got friends.
// In which case we must check for other dangerous units around, and perhaps armify them.
// TODO: perhaps someday army detection will have improved and this will require change.
var armyID = attacker.getMetadata(PlayerID, "inArmy");
if (armyID == undefined || !this.enemyArmy[attacker.owner()] || !this.enemyArmy[attacker.owner()][armyID]) {
if (this.reevaluateEntity(gameState, attacker))
{
var position = attacker.position();
var close = HQ.enemyWatchers[attacker.owner()].enemySoldiers.filter(Filters.byDistance(position, self.armyCompactSize));
if (close.length > 2 || ourUnit.hasClass("Support") || attacker.hasClass("Siege"))
{
// armify it, then armify units close to him.
this.armify(gameState,attacker);
armyID = attacker.getMetadata(PlayerID, "inArmy");
close.forEach(function (ent) { //}){
if (API3.SquareVectorDistance(position, ent.position()) < self.armyCompactSize)
{
ent.setMetadata(PlayerID, "inArmy", armyID);
self.enemyArmy[ent.owner()][armyID].addEnt(ent);
}
});
return; // don't use too much processing power. If there are other cases, they'll be processed soon enough.
}
}
// Defencemanager will deal with them in the next turn.
}
if (ourUnit !== undefined && ourUnit.hasClass("Unit")) {
if (ourUnit.hasClass("Support")) {
// let's try to garrison this support unit.
if (ourUnit.position())
{
var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).filterNearest(ourUnit.position(),4).toEntityArray();
var garrisoned = false;
for (var i in buildings)
{
var struct = buildings[i];
if (struct.garrisoned() && struct.garrisonMax() - struct.garrisoned().length > 0)
{
garrisoned = true;
ourUnit.garrison(struct);
break;
}
}
if (!garrisoned) {
ourUnit.flee(attacker);
ourUnit.setMetadata(PlayerID,"fleeing", gameState.getTimeElapsed());
}
}
} else {
// It's a soldier. Right now we'll retaliate
// TODO: check for stronger units against this type, check for fleeing options, etc.
// Check also for neighboring towers and garrison there perhaps?
ourUnit.attack(e.attacker);
}
}
}
}
}
}
*/
}; // nice sets of closing brackets, isn't it?
return m;
}(AEGIS);

View File

@ -1,69 +0,0 @@
var AEGIS = function(m)
{
// returns some sort of DPS * health factor. If you specify a class, it'll use the modifiers against that class too.
m.getMaxStrength = function(ent, againstClass)
{
var strength = 0.0;
var attackTypes = ent.attackTypes();
var armourStrength = ent.armourStrengths();
var hp = ent.maxHitpoints() / 100.0; // some normalization
for (var typeKey in attackTypes) {
var type = attackTypes[typeKey];
if (type == "Slaughter" || type == "Charged")
continue;
var attackStrength = ent.attackStrengths(type);
var attackRange = ent.attackRange(type);
var attackTimes = ent.attackTimes(type);
for (var str in attackStrength) {
var val = parseFloat(attackStrength[str]);
if (againstClass)
val *= ent.getMultiplierAgainst(type, againstClass);
switch (str) {
case "crush":
strength += (val * 0.085) / 3;
break;
case "hack":
strength += (val * 0.075) / 3;
break;
case "pierce":
strength += (val * 0.065) / 3;
break;
}
}
if (attackRange){
strength += (attackRange.max * 0.0125) ;
}
for (var str in attackTimes) {
var val = parseFloat(attackTimes[str]);
switch (str){
case "repeat":
strength += (val / 100000);
break;
case "prepare":
strength -= (val / 100000);
break;
}
}
}
for (var str in armourStrength) {
var val = parseFloat(armourStrength[str]);
switch (str) {
case "crush":
strength += (val * 0.085) / 3;
break;
case "hack":
strength += (val * 0.075) / 3;
break;
case "pierce":
strength += (val * 0.065) / 3;
break;
}
}
return strength * hp;
};
return m;
}(AEGIS);

View File

@ -1,16 +0,0 @@
var AEGIS = function(m)
{
m.EntityCollectionFromIds = function(gameState, idList){
var ents = {};
for (var i in idList){
var id = idList[i];
if (gameState.entities._entities[id]) {
ents[id] = gameState.entities._entities[id];
}
}
return new API3.EntityCollection(gameState.sharedScript, ents);
}
return m;
}(AEGIS);

View File

@ -1,57 +0,0 @@
var AEGIS = function(m)
{
// Some functions that could be part of the gamestate but are Aegis specific.
// The next three are to register that we assigned a gatherer to a resource this turn.
// expects an entity
m.IsSupplyFull = function(gamestate, supply)
{
if (supply.isFull(PlayerID) === true)
return true;
var count = supply.resourceSupplyGatherers().length;
if (gamestate.turnCache["ressourceGatherer"] && gamestate.turnCache["ressourceGatherer"][supply.id()])
count += gamestate.turnCache["ressourceGatherer"][supply.id()];
if (count >= supply.maxGatherers())
return true;
return false;
}
// add a gatherer to the turn cache for this supply.
m.AddTCGatherer = function(gamestate, supplyID)
{
if (gamestate.turnCache["ressourceGatherer"] && gamestate.turnCache["ressourceGatherer"][supplyID])
++gamestate.turnCache["ressourceGatherer"][supplyID];
else if (gamestate.turnCache["ressourceGatherer"])
gamestate.turnCache["ressourceGatherer"][supplyID] = 1;
else
gamestate.turnCache["ressourceGatherer"] = { "supplyID" : 1 };
}
m.GetTCGatherer = function(gamestate, supplyID)
{
if (gamestate.turnCache["ressourceGatherer"] && gamestate.turnCache["ressourceGatherer"][supplyID])
return gamestate.turnCache["ressourceGatherer"][supplyID];
else
return 0;
}
// The next two are to register that we assigned a gatherer to a resource this turn.
m.AddTCRessGatherer = function(gamestate, resource)
{
if (gamestate.turnCache["ressourceGatherer-" + resource])
++gamestate.turnCache["ressourceGatherer-" + resource];
else
gamestate.turnCache["ressourceGatherer-" + resource] = 1;
}
m.GetTCRessGatherer = function(gamestate, resource)
{
if (gamestate.turnCache["ressourceGatherer-" + resource])
return gamestate.turnCache["ressourceGatherer-" + resource];
else
return 0;
}
return m;
}(AEGIS);

File diff suppressed because it is too large Load Diff

View File

@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -1,149 +0,0 @@
var AEGIS = function(m)
{
// other map functions
m.TERRITORY_PLAYER_MASK = 0x3F;
m.createObstructionMap = function(gameState, accessIndex, template){
var passabilityMap = gameState.getMap();
var territoryMap = gameState.ai.territoryMap;
// default values
var placementType = "land";
var buildOwn = true;
var buildAlly = true;
var buildNeutral = true;
var buildEnemy = false;
// If there is a template then replace the defaults
if (template){
placementType = template.buildPlacementType();
buildOwn = template.hasBuildTerritory("own");
buildAlly = template.hasBuildTerritory("ally");
buildNeutral = template.hasBuildTerritory("neutral");
buildEnemy = template.hasBuildTerritory("enemy");
}
var obstructionMask = gameState.getPassabilityClassMask("foundationObstruction") | gameState.getPassabilityClassMask("building-land");
if (placementType == "shore")
{
// TODO: this won't change much, should be cached, it's slow.
var obstructionTiles = new Uint8Array(passabilityMap.data.length);
var okay = false;
for (var x = 0; x < passabilityMap.width; ++x)
{
for (var y = 0; y < passabilityMap.height; ++y)
{
var i = x + y*passabilityMap.width;
var tilePlayer = (territoryMap.data[i] & m.TERRITORY_PLAYER_MASK);
if (gameState.ai.myIndex !== gameState.ai.accessibility.landPassMap[i])
{
obstructionTiles[i] = 0;
continue;
}
if (gameState.isPlayerEnemy(tilePlayer) && tilePlayer !== 0)
{
obstructionTiles[i] = 0;
continue;
}
if ((passabilityMap.data[i] & (gameState.getPassabilityClassMask("building-shore") | gameState.getPassabilityClassMask("default"))))
{
obstructionTiles[i] = 0;
continue;
}
okay = false;
var positions = [[0,1], [1,1], [1,0], [1,-1], [0,-1], [-1,-1], [-1,0], [-1,1]];
var available = 0;
for each (var stuff in positions)
{
var index = x + stuff[0] + (y+stuff[1])*passabilityMap.width;
var index2 = x + stuff[0]*2 + (y+stuff[1]*2)*passabilityMap.width;
var index3 = x + stuff[0]*3 + (y+stuff[1]*3)*passabilityMap.width;
var index4 = x + stuff[0]*4 + (y+stuff[1]*4)*passabilityMap.width;
if ((passabilityMap.data[index] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index,true) > 500)
if ((passabilityMap.data[index2] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index2,true) > 500)
if ((passabilityMap.data[index3] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index3,true) > 500)
if ((passabilityMap.data[index4] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index4,true) > 500) {
if (available < 2)
available++;
else
okay = true;
}
}
// checking for accessibility: if a neighbor is inaccessible, this is too. If it's not on the same "accessible map" as us, we crash-i~u.
var radius = 3;
for (var xx = -radius;xx <= radius; xx++)
for (var yy = -radius;yy <= radius; yy++)
{
var id = x + xx + (y+yy)*passabilityMap.width;
if (id > 0 && id < passabilityMap.data.length)
if (gameState.ai.terrainAnalyzer.map[id] === 0 || gameState.ai.terrainAnalyzer.map[id] == 30 || gameState.ai.terrainAnalyzer.map[id] == 40)
okay = false;
}
obstructionTiles[i] = okay ? 255 : 0;
}
}
} else {
var playerID = PlayerID;
var obstructionTiles = new Uint8Array(passabilityMap.data.length);
for (var i = 0; i < passabilityMap.data.length; ++i)
{
var tilePlayer = (territoryMap.data[i] & m.TERRITORY_PLAYER_MASK);
var invalidTerritory = (
(!buildOwn && tilePlayer == playerID) ||
(!buildAlly && gameState.isPlayerAlly(tilePlayer) && tilePlayer != playerID) ||
(!buildNeutral && tilePlayer == 0) ||
(!buildEnemy && gameState.isPlayerEnemy(tilePlayer) && tilePlayer != 0)
);
if (accessIndex)
var tileAccessible = (accessIndex === gameState.ai.accessibility.landPassMap[i]);
else
var tileAccessible = true;
if (placementType === "shore")
tileAccessible = true;
obstructionTiles[i] = (!tileAccessible || invalidTerritory || (passabilityMap.data[i] & obstructionMask)) ? 0 : 255;
}
}
var map = new API3.Map(gameState.sharedScript, obstructionTiles);
map.setMaxVal(255);
if (template && template.buildDistance()) {
var minDist = template.buildDistance().MinDistance;
var category = template.buildDistance().FromCategory;
if (minDist !== undefined && category !== undefined){
gameState.getOwnStructures().forEach(function(ent) {
if (ent.buildCategory() === category && ent.position()){
var pos = ent.position();
var x = Math.round(pos[0] / gameState.cellSize);
var z = Math.round(pos[1] / gameState.cellSize);
map.addInfluence(x, z, minDist/gameState.cellSize, -255, 'constant');
}
});
}
}
return map;
};
m.createTerritoryMap = function(gameState) {
var map = gameState.ai.territoryMap;
var ret = new API3.Map(gameState.sharedScript, map.data);
ret.getOwner = function(p) {
return this.point(p) & m.TERRITORY_PLAYER_MASK;
}
ret.getOwnerIndex = function(p) {
return this.map[p] & m.TERRITORY_PLAYER_MASK;
}
return ret;
};
return m;
}(AEGIS);

View File

@ -1,290 +0,0 @@
var AEGIS = function(m)
{
/* Naval Manager
Will deal with anything ships.
-Basically trade over water (with fleets and goals commissioned by the economy manager)
-Defence over water (commissioned by the defense manager)
-subtask being patrols, escort, naval superiority.
-Transport of units over water (a few units).
-Scouting, ultimately.
Also deals with handling docks, making sure we have access and stuffs like that.
Does not build them though, that's for the base manager to handle.
*/
m.NavalManager = function() {
// accessibility zones for which we have a dock.
// Connexion is described as [landindex] = [seaIndexes];
// technically they also exist for sea zones but I don't care.
this.landZoneDocked = [];
// list of seas I have a dock on.
this.accessibleSeas = [];
// ship subCollections. Also exist for land zones, idem, not caring.
this.seaShips = [];
this.seaTpShips = [];
this.seaWarships = [];
// wanted NB per zone.
this.wantedTpShips = [];
this.wantedWarships = [];
this.transportPlans = [];
this.askedPlans = [];
};
// More initialisation for stuff that needs the gameState
m.NavalManager.prototype.init = function(gameState, queues) {
// finished docks
this.docks = gameState.getOwnStructures().filter(API3.Filters.and(API3.Filters.byClass("Dock"), API3.Filters.not(API3.Filters.isFoundation())));
this.docks.allowQuickIter();
this.docks.registerUpdates();
this.ships = gameState.getOwnEntities().filter(API3.Filters.byClass("Ship"));
// note: those two can overlap (some transport ships are warships too and vice-versa).
this.tpShips = this.ships.filter(API3.Filters.byCanGarrison());
this.warships = this.ships.filter(API3.Filters.byClass("Warship"));
this.ships.registerUpdates();
this.tpShips.registerUpdates();
this.warships.registerUpdates();
for (var i = 0; i < gameState.ai.accessibility.regionSize.length; ++i)
{
if (gameState.ai.accessibility.regionType[i] !== "water")
{
// push dummies
this.seaShips.push(new API3.EntityCollection(gameState.sharedScript));
this.seaTpShips.push(new API3.EntityCollection(gameState.sharedScript));
this.seaWarships.push(new API3.EntityCollection(gameState.sharedScript));
this.wantedTpShips.push(0);
this.wantedWarships.push(0);
} else {
var collec = this.ships.filter(API3.Filters.byStaticMetadata(PlayerID, "sea", i));
collec.registerUpdates();
this.seaShips.push(collec);
collec = this.tpShips.filter(API3.Filters.byStaticMetadata(PlayerID, "sea", i));
collec.registerUpdates();
this.seaTpShips.push(collec);
var collec = this.warships.filter(API3.Filters.byStaticMetadata(PlayerID, "sea", i));
collec.registerUpdates();
this.seaWarships.push(collec);
this.wantedTpShips.push(1);
this.wantedWarships.push(1);
}
this.landZoneDocked.push([]);
}
};
m.NavalManager.prototype.getUnconnectedSeas = function (gameState, region) {
var seas = gameState.ai.accessibility.regionLinks[region]
if (seas.length === 0)
return [];
for (var i = 0; i < seas.length; ++i)
{
if (this.landZoneDocked[region].indexOf(seas[i]) !== -1)
seas.splice(i--,1);
}
return seas;
};
// returns true if there is a path from A to B and we have docks.
m.NavalManager.prototype.canReach = function (gameState, regionA, regionB) {
var path = gameState.ai.accessibility.getTrajectToIndex(regionA, regionB);
if (!path)
{
return false;
}
for (var i = 0; i < path.length - 1; ++i)
{
if (gameState.ai.accessibility.regionType[path[i]] == "land")
if (this.accessibleSeas.indexOf(path[i+1]) === -1)
{
m.debug ("cannot reach because of " + path[i+1]);
return false; // we wn't be able to board on that sea
}
}
return true;
};
m.NavalManager.prototype.checkEvents = function (gameState, queues, events) {
var evts = events["ConstructionFinished"];
// TODO: probably check stuffs like a base destruction.
for (var i in evts)
{
var evt = evts[i];
if (evt && evt.newentity)
{
var entity = gameState.getEntityById(evt.newentity);
if (entity && entity.hasClass("Dock") && entity.isOwn(PlayerID))
{
// okay we have a dock whose construction is finished.
// let's assign it to us.
var pos = entity.position();
var li = gameState.ai.accessibility.getAccessValue(pos);
var ni = entity.getMetadata(PlayerID, "sea");
if (this.landZoneDocked[li].indexOf(ni) === -1)
this.landZoneDocked[li].push(ni);
if (this.accessibleSeas.indexOf(ni) === -1)
this.accessibleSeas.push(ni);
}
}
}
};
m.NavalManager.prototype.addPlan = function(plan) {
this.transportPlans.push(plan);
};
// will create a plan at the end of the turn.
// many units can call this separately and end up in the same plan
// which can be useful.
m.NavalManager.prototype.askForTransport = function(entity, startPos, endPos) {
this.askedPlans.push([entity, startPos, endPos]);
};
// creates aforementionned plans
m.NavalManager.prototype.createPlans = function(gameState) {
var startID = {};
for (var i in this.askedPlans)
{
var plan = this.askedPlans[i];
var startIndex = gameState.ai.accessibility.getAccessValue(plan[1]);
var endIndex = gameState.ai.accessibility.getAccessValue(plan[2]);
if (startIndex === 1 || endIndex === -1)
continue;
if (!startID[startIndex])
{
startID[startIndex] = {};
startID[startIndex][endIndex] = { "dest" : plan[2], "units": [plan[0]]};
}
else if (!startID[startIndex][endIndex])
startID[startIndex][endIndex] = { "dest" : plan[2], "units": [plan[0]]};
else
startID[startIndex][endIndex].units.push(plan[0]);
}
for (var i in startID)
for (var k in startID[i])
{
var tpPlan = new m.TransportPlan(gameState, startID[i][k].units, startID[i][k].dest, false)
this.transportPlans.push (tpPlan);
}
};
// TODO: work on this.
m.NavalManager.prototype.maintainFleet = function(gameState, queues, events) {
// check if we have enough transport ships.
// check per region.
for (var i = 0; i < this.seaShips.length; ++i)
{
var tpNb = gameState.countOwnQueuedEntitiesWithMetadata("sea", i);
if (this.accessibleSeas.indexOf(i) !== -1 && this.seaTpShips[i].length < this.wantedTpShips[i]
&& tpNb + queues.ships.length() === 0 && gameState.getTemplate(gameState.applyCiv("units/{civ}_ship_bireme")).available(gameState))
{
// TODO: check our dock can build the wanted ship types, for Carthage.
queues.ships.addItem(new m.TrainingPlan(gameState, "units/{civ}_ship_bireme", { "sea" : i }, 1, 1 ));
}
}
};
// bumps up the number of ships we want if we need more.
m.NavalManager.prototype.checkLevels = function(gameState, queues) {
if (queues.ships.length() !== 0)
return;
for (var i = 0; i < this.transportPlans.length; ++i)
{
var plan = this.transportPlans[i];
if (plan.needTpShips())
{
var zone = plan.neededShipsZone();
if (zone && gameState.countOwnQueuedEntitiesWithMetadata("sea", zone) > 0)
continue;
if (zone && this.wantedTpShips[i] === 0)
this.wantedTpShips[i]++;
else if (zone && plan.allAtOnce)
this.wantedTpShips[i]++;
}
}
};
// assigns free ships to plans that need some
m.NavalManager.prototype.assignToPlans = function(gameState, queues, events) {
for (var i = 0; i < this.transportPlans.length; ++i)
{
var plan = this.transportPlans[i];
if (plan.needTpShips())
{
// assign one per go.
var zone = plan.neededShipsZone();
if (zone)
{
for each (var ship in this.seaTpShips[zone]._entities)
{
if (!ship.getMetadata(PlayerID, "tpplan"))
{
m.debug ("Assigning ship " + ship.id() + " to plan" + plan.ID);
plan.assignShip(gameState, ship);
return true;
}
}
}
}
}
return false;
};
m.NavalManager.prototype.checkActivePlan = function(ID) {
for (var i = 0; i < this.transportPlans.length; ++i)
if (this.transportPlans[i].ID === ID)
return true;
return false;
};
// Some functions are run every turn
// Others once in a while
m.NavalManager.prototype.update = function(gameState, queues, events) {
Engine.ProfileStart("Naval Manager update");
this.checkEvents(gameState, queues, events);
if (gameState.ai.playedTurn % 10 === 0)
{
this.maintainFleet(gameState, queues, events);
this.checkLevels(gameState, queues);
}
for (var i = 0; i < this.transportPlans.length; ++i)
if (!this.transportPlans[i].carryOn(gameState, this))
{
// whatever the reason, this plan needs to be ended
// it could be that it's finished though.
var seaZone = this.transportPlans[i].neededShipsZone();
var rallyPos = [];
this.docks.forEach(function (dock) {
if (dock.getMetadata(PlayerID,"sea") == seaZone)
rallyPos = dock.position();
});
this.transportPlans[i].ships.move(rallyPos[0], rallyPos[1]);
this.transportPlans[i].releaseAll(gameState);
this.transportPlans.splice(i,1);
--i;
}
this.assignToPlans(gameState, queues, events);
if (gameState.ai.playedTurn % 10 === 2)
{
this.createPlans(gameState);
this.askedPlans = [];
}
Engine.ProfileStop();
};
return m;
}(AEGIS);

View File

@ -1,479 +0,0 @@
var AEGIS = function(m)
{
/*
Describes a transport plan
Constructor assign units (units is an ID array, or an ID), a destionation (position, ingame), and a wanted escort size.
If "onlyIfOk" is true, then the plan will only start if the wanted escort size is met.
The naval manager will try to deal with it accordingly.
By this I mean that the naval manager will find how to go from access point 1 to access point 2 (relying on in-game pathfinder for mvt)
And then carry units from there.
If units are over multiple accessibility indexes (ie different islands) it will first group them
Note: only assign it units currently over land, or it won't work.
Also: destination should probably be land, otherwise the units will be lost at sea.
*/
// TODO: finish the support of multiple accessibility indexes.
// TODO: this doesn't check we can actually reach in the init, which we might want?
m.TransportPlan = function(gameState, units, destination, allAtOnce, escortSize, onlyIfOK) {
var self = this;
this.ID = m.playerGlobals[PlayerID].uniqueIDTPlans++;
var unitsID = [];
if (units.length !== undefined)
unitsID = units;
else
unitsID = [units];
this.units = m.EntityCollectionFromIds(gameState, unitsID);
this.units.forEach(function (ent) { //}){
ent.setMetadata(PlayerID, "tpplan", self.ID);
ent.setMetadata(PlayerID, "formerRole", ent.getMetadata(PlayerID, "role"));
ent.setMetadata(PlayerID, "role", "transport");
});
this.units.freeze();
this.units.registerUpdates();
m.debug ("Starting a new plan with ID " + this.ID + " to " + destination);
m.debug ("units are " + uneval (units));
this.destination = destination;
this.destinationIndex = gameState.ai.accessibility.getAccessValue(destination);
if (allAtOnce)
this.allAtOnce = allAtOnce;
else
this.allAtOnce = false;
if (escortSize)
this.escortSize = escortSize;
else
this.escortSize = 0;
if (onlyIfOK)
this.onlyIfOK = onlyIfOK;
else
this.onlyIfOK = false;
this.state = "unstarted";
this.ships = gameState.ai.HQ.navalManager.ships.filter(Filters.byMetadata(PlayerID, "tpplan", this.ID));
// note: those two can overlap (some transport ships are warships too and vice-versa).
this.transportShips = gameState.ai.HQ.navalManager.tpShips.filter(Filters.byMetadata(PlayerID, "tpplan", this.ID));
this.escortShips = gameState.ai.HQ.navalManager.warships.filter(Filters.byMetadata(PlayerID, "tpplan", this.ID));
this.ships.registerUpdates();
this.transportShips.registerUpdates();
this.escortShips.registerUpdates();
};
// count available slots
m.TransportPlan.prototype.countFreeSlots = function(onlyTrulyFree)
{
var slots = 0;
this.transportShips.forEach(function (ent) { //}){
slots += ent.garrisonMax();
if (onlyTrulyFree)
slots -= ent.garrisoned().length;
});
return slots;
};
m.TransportPlan.prototype.assignShip = function(gameState, ship)
{
ship.setMetadata(PlayerID,"tpplan", this.ID);
}
m.TransportPlan.prototype.releaseAll = function(gameState)
{
this.ships.forEach(function (ent) { ent.setMetadata(PlayerID,"tpplan", undefined) });
this.units.forEach(function (ent) {
var fRole = ent.getMetadata(PlayerID, "formerRole");
if (fRole)
ent.setMetadata(PlayerID,"role", fRole);
ent.setMetadata(PlayerID,"tpplan", undefined)
});
}
m.TransportPlan.prototype.releaseAllShips = function(gameState)
{
this.ships.forEach(function (ent) { ent.setMetadata(PlayerID,"tpplan", undefined) });
}
m.TransportPlan.prototype.needTpShips = function()
{
if ((this.allAtOnce && this.countFreeSlots() >= this.units.length) || this.transportShips.length > 0)
return false;
return true;
}
m.TransportPlan.prototype.needEscortShips = function()
{
return !((this.onlyIfOK && this.escortShips.length < this.escortSize) || !this.onlyIfOK);
}
// returns the zone for which we are needing our ships
m.TransportPlan.prototype.neededShipsZone = function()
{
if (!this.seaZone)
return false;
return this.seaZone;
}
// try to move on.
/* several states:
"unstarted" is the initial state, and will determine wether we follow basic or grouping path
Basic path:
- "waitingForBoarding" means we wait 'till we have enough transport ships and escort ships to move stuffs.
- "Boarding" means we're trying to board units onto our ships
- "Moving" means we're moving ships
- "Unboarding" means we're unbording
- Once we're unboarded, we either return to boarding point (if we still have units to board) or we clear.
> there is the possibility that we'll be moving units on land, but that's basically a restart too, with more clearing.
Grouping Path is basically the same with "grouping" and we never unboard (unless there is a need to)
*/
m.TransportPlan.prototype.carryOn = function(gameState, navalManager)
{
if (this.state === "unstarted")
{
// Okay so we can start the plan.
// So what we'll do is check what accessibility indexes our units are.
var unitIndexes = [];
this.units.forEach( function (ent) { //}){
var idx = gameState.ai.accessibility.getAccessValue(ent.position());
if (unitIndexes.indexOf(idx) === -1 && idx !== 1)
unitIndexes.push(idx);
});
// we have indexes. If there is more than 1, we'll try and regroup them.
if (unitIndexes.length > 1)
{
warn("Transport Plan path is too complicated, aborting");
return false;
/*
this.state = "waitingForGrouping";
// get the best index for grouping, ie start by the one farthest away in terms of movement.
var idxLength = {};
for (var i = 0; i < unitIndexes.length; ++i)
idxLength[unitIndexes[i]] = gameState.ai.accessibility.getTrajectToIndex(unitIndexes[i], this.destinationIndex).length;
var sortedArray = unitIndexes.sort(function (a,b) { //}){
return idxLength[b] - idxLength[a];
});
this.startIndex = sortedArray[0];
// okay so we'll board units from this index and we'll try to join them with units of the next index.
// this might not be terribly efficient but it won't be efficient anyhow.
return true;*/
}
this.state = "waitingForBoarding";
// let's get our index this turn.
this.startIndex = unitIndexes[0];
m.debug ("plan " + this.ID + " from " + this.startIndex);
return true;
}
if (this.state === "waitingForBoarding")
{
if (!this.path)
{
this.path = gameState.ai.accessibility.getTrajectToIndex(this.startIndex, this.destinationIndex);
if (!this.path || this.path.length === 0 || this.path.length % 2 === 0)
return false; // TODO: improve error handling
if (this.path[0] !== this.startIndex)
{
warn ("Start point of the path is not the start index, aborting transport plan");
return false;
}
// we have a path, register the first sea zone.
this.seaZone = this.path[1];
m.debug ("Plan " + this.ID + " over seazone " + this.seaZone);
}
// if we currently have no baoarding spot, try and find one.
if (!this.boardingSpot)
{
// TODO: improve on this whenever we have danger maps.
// okay so we have units over an accessibility index.
// we'll get a map going on.
var Xibility = gameState.ai.accessibility;
// custom obstruction map that uses the shore as the obstruction map
// but doesn't really check like for a building.
// created realtime with the other map.
var passabilityMap = gameState.getMap();
var territoryMap = gameState.ai.territoryMap;
var obstructionMask = gameState.getPassabilityClassMask("foundationObstruction") | gameState.getPassabilityClassMask("building-shore");
var obstructions = new API3.Map(gameState.sharedScript);
// wanted map.
var friendlyTiles = new API3.Map(gameState.sharedScript);
for (var j = 0; j < friendlyTiles.length; ++j)
{
// only on the wanted island
if (Xibility.landPassMap[j] !== this.startIndex)
continue;
// setting obstructions
var tilePlayer = (territoryMap.data[j] & TERRITORY_PLAYER_MASK);
// invalid is enemy-controlled or not on the right sea/land (we need a shore for this, we might want to check neighbhs instead).
var invalidTerritory = (gameState.isPlayerEnemy(tilePlayer) && tilePlayer != 0)
|| (Xibility.navalPassMap[j] !== this.path[1]);
obstructions.map[j] = (invalidTerritory || (passabilityMap.data[j] & obstructionMask)) ? 0 : 255;
// currently we'll just like better on our territory
if (tilePlayer == PlayerID)
friendlyTiles.map[j] = 100;
}
obstructions.expandInfluences();
var best = friendlyTiles.findBestTile(4, obstructions);
var bestIdx = best[0];
// not good enough.
if (best[1] <= 0)
{
best = friendlyTiles.findBestTile(1, obstructions);
bestIdx = best[0];
if (best[1] <= 0)
return false; // apparently we won't be able to board.
}
var x = ((bestIdx % friendlyTiles.width) + 0.5) * gameState.cellSize;
var z = (Math.floor(bestIdx / friendlyTiles.width) + 0.5) * gameState.cellSize;
// we have the spot we want to board at.
this.boardingSpot = [x,z];
m.debug ("Plan " + this.ID + " new boarding spot is " + this.boardingSpot);
}
// if all at once we need to be full, else we just need enough escort ships.
if (!this.needTpShips() && !this.needEscortShips())
{
// preparing variables
// TODO: destroy former entity collection.
this.garrisoningUnits = this.units.filter(Filters.not(Filters.isGarrisoned()));
this.garrisoningUnits.registerUpdates();
this.garrisoningUnits.freeze();
this.garrisonShipID = -1;
m.debug ("Boarding");
this.state = "boarding";
}
return true;
} else if (this.state === "waitingForGrouping")
{
// TODO: this.
return true;
}
if (this.state === "boarding" && gameState.ai.playedTurn % 5 === 0)
{
// TODO: improve error recognition.
if (this.units.length === 0)
return false;
if (!this.boardingSpot)
return false;
if (this.needTpShips())
{
this.state = "waitingForBoarding";
return true;
}
if (this.needEscortShips())
{
this.state = "waitingForBoarding";
return true;
}
// check if we aren't actually finished.
if (this.units.getCentrePosition() == undefined || this.countFreeSlots(true) === 0)
{
delete this.boardingSpot;
this.garrisoningUnits.unregister();
this.state = "moving";
return true;
}
// check if we need to move our units and ships closer together
var stillMoving = false;
if (API3.SquareVectorDistance(this.ships.getCentrePosition(),this.boardingSpot) > 1600)
{
this.ships.move(this.boardingSpot[0],this.boardingSpot[1]);
stillMoving = true; // wait till ships are in position
}
if (API3.SquareVectorDistance(this.units.getCentrePosition(),this.boardingSpot) > 1600)
{
this.units.move(this.boardingSpot[0],this.boardingSpot[1]);
stillMoving = true; // wait till units are in position
}
if (stillMoving)
{
return true; // wait.
}
// check if we need to try and board units.
var garrisonShip = gameState.getEntityById(this.garrisonShipID);
var self = this;
// check if ship we're currently garrisoning in is full
if (garrisonShip && garrisonShip.canGarrisonInside())
{
// okay garrison units
var nbStill = garrisonShip.garrisonMax() - garrisonShip.garrisoned().length;
if (this.garrisoningUnits.length < nbStill)
{
Engine.PostCommand({"type": "garrison", "entities": this.garrisoningUnits.toIdArray(), "target": garrisonShip.id(),"queued": false});
}
return true;
} else if (garrisonShip)
{
// full ship, abort
this.garrisonShipID = -1;
garrisonShip = false; // will enter next if.
}
if (!garrisonShip)
{
// could have died or could have be full
// we'll pick a new one, one that isn't full
for (var i in this.transportShips._entities)
{
if (this.transportShips._entities[i].canGarrisonInside())
{
this.garrisonShipID = this.transportShips._entities[i].id();
break;
}
}
return true; // wait.
}
// could I actually get here?
return true;
}
if (this.state === "moving")
{
if (!this.unboardingSpot)
{
// TODO: improve on this whenever we have danger maps.
// okay so we have units over an accessibility index.
// we'll get a map going on.
var Xibility = gameState.ai.accessibility;
// custom obstruction map that uses the shore as the obstruction map
// but doesn't really check like for a building.
// created realtime with the other map.
var passabilityMap = gameState.getMap();
var territoryMap = gameState.ai.territoryMap;
var obstructionMask = gameState.getPassabilityClassMask("foundationObstruction") | gameState.getPassabilityClassMask("building-shore");
var obstructions = new API3.Map(gameState.sharedScript);
// wanted map.
var friendlyTiles = new API3.Map(gameState.sharedScript);
var wantedIndex = -1;
if (this.path.length >= 3)
{
this.path.splice(0,2);
wantedIndex = this.path[0];
} else {
m.debug ("too short at " +uneval(this.path));
return false; // Incomputable
}
for (var j = 0; j < friendlyTiles.length; ++j)
{
// only on the wanted island
if (Xibility.landPassMap[j] !== wantedIndex)
continue;
// setting obstructions
var tilePlayer = (territoryMap.data[j] & TERRITORY_PLAYER_MASK);
// invalid is not on the right land (we need a shore for this, we might want to check neighbhs instead).
var invalidTerritory = (Xibility.landPassMap[j] !== wantedIndex);
obstructions.map[j] = (invalidTerritory || (passabilityMap.data[j] & obstructionMask)) ? 0 : 255;
// currently we'll just like better on our territory
if (tilePlayer == PlayerID)
friendlyTiles.map[j] = 100;
else if (gameState.isPlayerEnemy(tilePlayer) && tilePlayer != 0)
friendlyTiles.map[j] = 4;
else
friendlyTiles.map[j] = 50;
}
obstructions.expandInfluences();
var best = friendlyTiles.findBestTile(4, obstructions);
var bestIdx = best[0];
// not good enough.
if (best[1] <= 0)
{
best = friendlyTiles.findBestTile(1, obstructions);
bestIdx = best[0];
if (best[1] <= 0)
return false; // apparently we won't be able to unboard.
}
var x = ((bestIdx % friendlyTiles.width) + 0.5) * gameState.cellSize;
var z = (Math.floor(bestIdx / friendlyTiles.width) + 0.5) * gameState.cellSize;
// we have the spot we want to board at.
this.unboardingSpot = [x,z];
return true;
}
// TODO: improve error recognition.
if (this.units.length === 0)
return false;
if (!this.unboardingSpot)
return false;
// check if we need to move ships
if (API3.SquareVectorDistance(this.ships.getCentrePosition(),this.unboardingSpot) > 400)
{
this.ships.move(this.unboardingSpot[0],this.unboardingSpot[1]);
} else {
this.state = "unboarding";
return true;
}
return true;
}
if (this.state === "unboarding")
{
// TODO: improve error recognition.
if (this.units.length === 0)
return false;
// check if we need to move ships
if (API3.SquareVectorDistance(this.ships.getCentrePosition(),this.unboardingSpot) > 400)
{
this.ships.move(this.unboardingSpot[0],this.unboardingSpot[1]);
} else {
this.transportShips.forEach( function (ent) { ent.unloadAll() });
// TODO: improve on this.
if (this.path.length > 1)
{
m.debug ("plan " + this.ID + " going back for more");
// basically reset.
delete this.boardingSpot;
delete this.unboardingSpot;
this.state = "unstarted";
this.releaseAllShips();
return true;
}
m.debug ("plan " + this.ID + " is finished");
return false;
}
}
return true;
}
return m;
}(AEGIS);

View File

@ -1,560 +0,0 @@
var AEGIS = function(m)
{
// This takes the input queues and picks which items to fund with resources until no more resources are left to distribute.
//
// Currently this manager keeps accounts for each queue, split between the 4 main resources
//
// Each time resources are available (ie not in any account), it is split between the different queues
// Mostly based on priority of the queue, and existing needs.
// Each turn, the queue Manager checks if a queue can afford its next item, then it does.
//
// A consequence of the system it's not really revertible. Once a queue has an account of 500 food, it'll keep it
// If for some reason the AI stops getting new food, and this queue lacks, say, wood, no other queues will
// be able to benefit form the 500 food (even if they only needed food).
// This is not to annoying as long as all goes well. If the AI loses many workers, it starts being problematic.
//
// It also has the effect of making the AI more or less always sit on a few hundreds resources since most queues
// get some part of the total, and if all queues have 70% of their needs, nothing gets done
// Particularly noticeable when phasing: the AI often overshoots by a good 200/300 resources before starting.
//
// This system should be improved. It's probably not flexible enough.
m.QueueManager = function(Config, queues, priorities) {
this.Config = Config;
this.queues = queues;
this.priorities = priorities;
this.accounts = {};
// the sorting is updated on priority change.
var self = this;
this.queueArrays = [];
for (var p in this.queues) {
this.accounts[p] = new API3.Resources();
this.queueArrays.push([p,this.queues[p]]);
}
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
this.curItemQueue = [];
};
m.QueueManager.prototype.getAvailableResources = function(gameState, noAccounts) {
var resources = gameState.getResources();
if (noAccounts)
return resources;
for (var key in this.queues) {
resources.subtract(this.accounts[key]);
}
return resources;
};
m.QueueManager.prototype.getTotalAccountedResources = function(gameState) {
var resources = new API3.Resources();
for (var key in this.queues) {
resources.add(this.accounts[key]);
}
return resources;
};
m.QueueManager.prototype.currentNeeds = function(gameState) {
var needed = new API3.Resources();
//queueArrays because it's faster.
for (var i in this.queueArrays)
{
var name = this.queueArrays[i][0];
var queue = this.queueArrays[i][1];
if (queue.length() == 0 || !queue.queue[0].isGo(gameState))
continue;
// we need resource if the account is smaller than the cost
var costs = queue.queue[0].getCost();
for each (var ress in costs.types)
costs[ress] = Math.max(0, costs[ress] - this.accounts[name][ress]);
needed.add(costs);
}
return needed;
};
m.QueueManager.prototype.futureNeeds = function(gameState) {
var needs = new API3.Resources();
// get out current resources, not removing accounts.
var current = this.getAvailableResources(gameState, true);
//queueArrays because it's faster.
for (var i in this.queueArrays)
{
var name = this.queueArrays[i][0];
var queue = this.queueArrays[i][1];
for (var j = 0; j < queue.length(); ++j)
{
var costs = queue.queue[j].getCost();
if (!queue.queue[j].isGo(gameState))
costs.multiply(0.5);
needs.add(costs);
}
}
return {
"food" : Math.max(25 + needs.food - current.food, 10),
"wood" : Math.max(needs.wood - current.wood, 10),
"stone" : Math.max(needs.stone - current.stone, 0),
"metal" : Math.max(needs.metal - current.metal, 0)
};
};
// calculate the gather rates we'd want to be able to start all elements in our queues
// TODO: many things.
m.QueueManager.prototype.wantedGatherRates = function(gameState, shortTerm) {
// global rates
var rates = { "food" : 0, "wood" : 0, "stone" : 0, "metal" : 0 };
// per-queue.
var qTime = gameState.getTimeElapsed();
var time = gameState.getTimeElapsed();
var qCosts = { "food" : 0, "wood" : 0, "stone" : 0, "metal" : 0 };
var currentRess = this.getAvailableResources(gameState);
//queueArrays because it's faster.
for (var i in this.queueArrays)
{
qCosts = { "food" : 0, "wood" : 0, "stone" : 0, "metal" : 0 };
qTime = gameState.getTimeElapsed();
var name = this.queueArrays[i][0];
var queue = this.queueArrays[i][1];
// we'll move temporally along the queue.
for (var j = 0; j < queue.length(); ++j)
{
var elem = queue.queue[j];
var cost = elem.getCost();
var timeMultiplier = Math.max(1,(qTime-time)/25000);
if (shortTerm)
timeMultiplier += 0.8;
if (!elem.isGo(gameState))
{
// assume we'll be wanted in four minutes.
// TODO: work on this.
for (var type in qCosts)
qCosts[type] += cost[type] / timeMultiplier;
qTime += 240000;
break; // disregard other stuffs.
}
// Assume we want it in 30 seconds from current time.
// Costs are made higher based on priority and lower based on current time.
// TODO: work on this.
for (var type in qCosts)
{
if (cost[type] === 0)
continue;
qCosts[type] += (cost[type] + Math.min(cost[type],this.priorities[name])) / timeMultiplier;
}
qTime += 30000; // TODO: this needs a lot more work.
}
for (var j in qCosts)
{
qCosts[j] -= this.accounts[name][j];
var diff = Math.min(qCosts[j], currentRess[j]);
qCosts[j] -= diff;
currentRess[j] -= diff;
rates[j] += qCosts[j]/(qTime/1000);
}
}
return rates;
};
/*m.QueueManager.prototype.logNeeds = function(gameState) {
if (!this.totor)
{
this.totor = [];
this.currentGathR = [];
this.currentGathRWanted = [];
this.ressLev = [];
}
if (gameState.ai.playedTurn % 10 !== 0)
return;
var array = this.wantedGatherRates(gameState);
this.totor.push( array );
var currentRates = {};
for (var type in array)
currentRates[type] = 0;
for (var i in gameState.ai.HQ.baseManagers)
{
var base = gameState.ai.HQ.baseManagers[i];
for (var type in array)
{
base.gatherersByType(gameState,type).forEach (function (ent) { //}){
var worker = ent.getMetadata(PlayerID, "worker-object");
if (worker)
currentRates[type] += worker.getGatherRate(gameState);
});
}
}
this.currentGathR.push( currentRates );
var types = Object.keys(array);
types.sort(function(a, b) {
var va = (Math.max(0,array[a] - currentRates[a]))/ (currentRates[a]+1);
var vb = (Math.max(0,array[b] - currentRates[b]))/ (currentRates[b]+1);
if (va === vb)
return (array[b]/(currentRates[b]+1)) - (array[a]/(currentRates[a]+1));
return vb-va;
});
this.currentGathRWanted.push( types );
var rss = gameState.getResources();
this.ressLev.push( {"food" : rss["food"],"stone" : rss["stone"],"wood" : rss["wood"],"metal" : rss["metal"]} );
if (gameState.getTimeElapsed() > 20*60*1000 && !this.once)
{
this.once = true;
for (var j in array)
{
log (j + ";");
for (var i = 0; i < this.totor.length; ++i)
{
log (this.totor[i][j] + ";");
}
}
log();
for (var j in array)
{
log (j + ";");
for (var i = 0; i < this.totor.length; ++i)
{
log (this.currentGathR[i][j] + ";");
}
}
log();
for (var j in array)
{
log (j + ";");
for (var i = 0; i < this.totor.length; ++i)
{
log (this.currentGathRWanted[i].indexOf(j) + ";");
}
}
log();
for (var j in array)
{
log (j + ";");
for (var i = 0; i < this.totor.length; ++i)
{
log (this.ressLev[i][j] + ";");
}
}
}
};
*/
m.QueueManager.prototype.printQueues = function(gameState){
m.debug("QUEUES");
for (var i in this.queues){
var qStr = "";
var q = this.queues[i];
if (q.queue.length > 0)
m.debug((i + ":"));
for (var j in q.queue){
qStr = " " + q.queue[j].type + " ";
if (q.queue[j].number)
qStr += "x" + q.queue[j].number;
m.debug (qStr);
}
}
m.debug ("Accounts");
for (var p in this.accounts)
{
m.debug(p + ": " + uneval(this.accounts[p]));
}
m.debug("Needed Resources:" + uneval(this.futureNeeds(gameState,false)));
m.debug ("Wanted Gather Rates:" + uneval(this.wantedGatherRates(gameState)));
m.debug ("Current Resources:" + uneval(gameState.getResources()));
m.debug ("Available Resources:" + uneval(this.getAvailableResources(gameState)));
};
// nice readable HTML version.
m.QueueManager.prototype.HTMLprintQueues = function(gameState){
if (!m.DebugEnabled())
return;
var strToSend = [];
strToSend.push("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"> <html> <head> <title>Aegis Queue Manager</title> <link rel=\"stylesheet\" href=\"table.css\"> </head> <body> <table> <caption>Aegis Build Order</caption> ");
for (var i in this.queues){
strToSend.push("<tr>");
var q = this.queues[i];
var str = "<th>" + i + " (" + this.priorities[i] + ")<br><span class=\"ressLevel\">";
for each (var k in this.accounts[i].types)
if(k != "population")
{
str += this.accounts[i][k] + k.substr(0,1).toUpperCase() ;
if (k != "metal") str += " / ";
}
strToSend.push(str + "</span></th>");
for (var j in q.queue) {
if (q.queue[j].isGo(gameState))
strToSend.push("<td>");
else
strToSend.push("<td class=\"NotGo\">");
var qStr = "";
if (q.queue[j].number)
qStr += q.queue[j].number + " ";
qStr += q.queue[j].type;
qStr += "<br><span class=\"ressLevel\">";
var costs = q.queue[j].getCost();
for each (var k in costs.types) {
qStr += costs[k] + k.substr(0,1).toUpperCase() ;
if (k != "metal") qStr += " / ";
}
qStr += "</span></td>";
strToSend.push(qStr);
}
strToSend.push("</tr>");
}
strToSend.push("</table>");
/*strToSend.push("<h3>Accounts</h3>");
for (var p in this.accounts)
{
strToSend.push("<p>" + p + ": " + uneval(this.accounts[p]) + " </p>");
}*/
strToSend.push("<p>Wanted Gather Rate:" + uneval(this.wantedGatherRates(gameState)) + "</p>");
strToSend.push("<p>Current Resources:" + uneval(gameState.getResources()) + "</p>");
strToSend.push("<p>Available Resources:" + uneval(this.getAvailableResources(gameState)) + "</p>");
strToSend.push("</body></html>");
for each (var logged in strToSend)
log(logged);
};
m.QueueManager.prototype.clear = function(){
this.curItemQueue = [];
for (var i in this.queues)
this.queues[i].empty();
};
m.QueueManager.prototype.update = function(gameState) {
var self = this;
for (var i in this.priorities){
if (!(this.priorities[i] > 0)){
this.priorities[i] = 1; // TODO: make the Queue Manager not die when priorities are zero.
warn("QueueManager received bad priorities, please report this error: " + uneval(this.priorities));
}
}
Engine.ProfileStart("Queue Manager");
// Let's assign resources to plans that need'em
var availableRes = this.getAvailableResources(gameState);
for (var ress in availableRes)
{
if (ress === "population")
continue;
if (availableRes[ress] > 0)
{
var totalPriority = 0;
var tempPrio = {};
var maxNeed = {};
// Okay so this is where it gets complicated.
// If a queue requires "ress" for the next elements (in the queue)
// And the account is not high enough for it.
// Then we add it to the total priority.
// To try and be clever, we don't want a long queue to hog all resources. So two things:
// -if a queue has enough of resource X for the 1st element, its priority is decreased (/2).
// -queues accounts are capped at "resources for the first + 80% of the next"
// This avoids getting a high priority queue with many elements hogging all of one resource
// uselessly while it awaits for other resources.
for (var j in this.queues) {
// returns exactly the correct amount, ie 0 if we're not go.
var queueCost = this.queues[j].maxAccountWanted(gameState);
if (this.queues[j].length() > 0 && this.accounts[j][ress] < queueCost[ress] && !this.queues[j].paused)
{
// check that we're not too forward in this resource compared to others.
/*var maxp = this.accounts[j][ress] / (queueCost[ress]+1);
var tooFull = false;
for (var tempRess in availableRes)
if (tempRess !== ress && queueCost[tempRess] > 0 && (this.accounts[j][tempRess] / (queueCost[tempRess]+1)) - maxp < -0.2)
tooFull = true;
if (tooFull)
continue;*/
// adding us to the list of queues that need an update.
tempPrio[j] = this.priorities[j];
maxNeed[j] = queueCost[ress] - this.accounts[j][ress];
// if we have enough of that resource for our first item in the queue, diminish our priority.
if (this.accounts[j][ress] >= this.queues[j].getNext().getCost()[ress])
tempPrio[j] /= 2;
if (tempPrio[j])
totalPriority += tempPrio[j];
}
else if (this.accounts[j][ress] > queueCost[ress])
{
this.accounts[j][ress] = queueCost[ress];
}
}
// Now we allow resources to the accounts. We can at most allow "TempPriority/totalpriority*available"
// But we'll sometimes allow less if that would overflow.
for (var j in tempPrio) {
// we'll add at much what can be allowed to this queue.
var toAdd = tempPrio[j]/totalPriority * availableRes[ress];
var maxAdd = Math.floor(Math.min(maxNeed[j], toAdd));
this.accounts[j][ress] += maxAdd;
}
} else {
// We have no available resources, see if we can't "compact" them in one queue.
// compare queues 2 by 2, and if one with a higher priority could be completed by our amount, give it.
// TODO: this isn't perfect compression.
for (var j in this.queues)
{
var queue = this.queues[j];
var queueCost = queue.maxAccountWanted(gameState);
if (this.queues[j].length() === 0 || this.queues[j].paused)
continue;
for (var i in this.queues)
{
if (i === j)
continue;
var otherQueue = this.queues[i];
if (this.priorities[i] >= this.priorities[j] || otherQueue.switched !== 0)
continue;
for (var ress in queueCost)
{
if (this.accounts[j][ress] >= queueCost[ress])
continue;
if (this.accounts[j][ress] + this.accounts[i][ress] >= queueCost[ress])
{
// we would be helped by it. Check if it's worth it.
for (var otherRess in queueCost)
if (otherRess !== ress && queueCost[otherRess] + 100 >= queueCost[ress])
continue;
var diff = Math.min(queueCost[ress] - this.accounts[j][ress],this.accounts[i][ress]);
this.accounts[j][ress] += diff;
this.accounts[i][ress] -= diff;
++otherQueue.switched;
//warn ("switching " + ress + " from " + i + " to " + j + " in amount " + diff);
}
}
}
}
}
}
Engine.ProfileStart("Pick items from queues");
//m.debug ("start");
//m.debug (uneval(this.accounts));
// Start the next item in the queue if we can afford it.
for (var i in this.queueArrays)
{
var name = this.queueArrays[i][0];
var queue = this.queueArrays[i][1];
if (queue.length() > 0 && !queue.paused)
{
var item = queue.getNext();
var total = new API3.Resources();
total.add(this.accounts[name]);
if (total.canAfford(item.getCost()))
{
if (item.canStart(gameState))
{
this.accounts[name].subtract(item.getCost());
queue.startNext(gameState);
queue.switched = 0;
}
}
} else if (queue.length() === 0) {
this.accounts[name].reset();
queue.switched = 0;
}
}
//m.debug (uneval(this.accounts));
Engine.ProfileStop();
if (gameState.ai.playedTurn % 15 === 2)
this.HTMLprintQueues(gameState);
Engine.ProfileStop();
};
m.QueueManager.prototype.pauseQueue = function(queue, scrapAccounts) {
if (this.queues[queue])
{
this.queues[queue].paused = true;
if (scrapAccounts)
this.accounts[queue].reset();
}
}
m.QueueManager.prototype.unpauseQueue = function(queue) {
if (this.queues[queue])
this.queues[queue].paused = false;
}
m.QueueManager.prototype.pauseAll = function(scrapAccounts, but) {
for (var p in this.queues)
if (p != but)
{
if (scrapAccounts)
this.accounts[p].reset();
this.queues[p].paused = true;
}
}
m.QueueManager.prototype.unpauseAll = function(but) {
for (var p in this.queues)
if (p != but)
this.queues[p].paused = false;
}
m.QueueManager.prototype.addQueue = function(queueName, priority) {
if (this.queues[queueName] == undefined) {
this.queues[queueName] = new m.Queue();
this.priorities[queueName] = priority;
this.accounts[queueName] = new API3.Resources();
var self = this;
this.queueArrays = [];
for (var p in this.queues)
this.queueArrays.push([p,this.queues[p]]);
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
}
}
m.QueueManager.prototype.removeQueue = function(queueName) {
if (this.queues[queueName] !== undefined) {
if ( this.curItemQueue.indexOf(queueName) !== -1) {
this.curItemQueue.splice(this.curItemQueue.indexOf(queueName),1);
}
delete this.queues[queueName];
delete this.priorities[queueName];
delete this.accounts[queueName];
var self = this;
this.queueArrays = [];
for (var p in this.queues)
this.queueArrays.push([p,this.queues[p]]);
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
}
}
m.QueueManager.prototype.changePriority = function(queueName, newPriority) {
var self = this;
if (this.queues[queueName] !== undefined)
this.priorities[queueName] = newPriority;
this.queueArrays = [];
for (var p in this.queues)
this.queueArrays.push([p,this.queues[p]]);
this.queueArrays.sort(function (a,b) { return (self.priorities[b[0]] - self.priorities[a[0]]) });
}
return m;
}(AEGIS);

View File

@ -1,111 +0,0 @@
var AEGIS = function(m)
{
/*
* Holds a list of wanted items to train or construct
*/
m.Queue = function() {
this.queue = [];
this.paused = false;
this.switched = 0;
};
m.Queue.prototype.empty = function() {
this.queue = [];
};
m.Queue.prototype.addItem = function(plan) {
for (var i in this.queue)
{
if (plan.category === "unit" && this.queue[i].type == plan.type && this.queue[i].number + plan.number <= this.queue[i].maxMerge)
{
this.queue[i].addItem(plan.number)
return;
}
}
this.queue.push(plan);
};
m.Queue.prototype.getNext = function() {
if (this.queue.length > 0) {
return this.queue[0];
} else {
return null;
}
};
m.Queue.prototype.startNext = function(gameState) {
if (this.queue.length > 0) {
this.queue.shift().start(gameState);
return true;
} else {
return false;
}
};
// returns the maximal account we'll accept for this queue.
// Currently 100% of the cost of the first element and 80% of that of the second
m.Queue.prototype.maxAccountWanted = function(gameState) {
var cost = new API3.Resources();
if (this.queue.length > 0 && this.queue[0].isGo(gameState))
cost.add(this.queue[0].getCost());
if (this.queue.length > 1 && this.queue[1].isGo(gameState))
{
var costs = this.queue[1].getCost();
costs.multiply(0.4);
cost.add(costs);
}
return cost;
};
m.Queue.prototype.queueCost = function(){
var cost = new API3.Resources();
for (var key in this.queue){
cost.add(this.queue[key].getCost());
}
return cost;
};
m.Queue.prototype.length = function() {
return this.queue.length;
};
m.Queue.prototype.countQueuedUnits = function(){
var count = 0;
for (var i in this.queue){
count += this.queue[i].number;
}
return count;
};
m.Queue.prototype.countQueuedUnitsWithClass = function(classe){
var count = 0;
for (var i in this.queue){
if (this.queue[i].template && this.queue[i].template.hasClass(classe))
count += this.queue[i].number;
}
return count;
};
m.Queue.prototype.countQueuedUnitsWithMetadata = function(data,value){
var count = 0;
for (var i in this.queue){
if (this.queue[i].metadata[data] && this.queue[i].metadata[data] == value)
count += this.queue[i].number;
}
return count;
};
m.Queue.prototype.countAllByType = function(t){
var count = 0;
for (var i = 0; i < this.queue.length; i++){
if (this.queue[i].type === t){
count += this.queue[i].number;
}
}
return count;
};
return m;
}(AEGIS);

View File

@ -1,71 +0,0 @@
var AEGIS = function(m)
{
/*
* Common functions and variables to all queue plans.
* has a "--" suffix because it needs to be loaded before the other queueplan files.
*/
m.QueuePlan = function(gameState, type, metadata) {
this.type = gameState.applyCiv(type);
this.metadata = metadata;
this.template = gameState.getTemplate(this.type);
if (!this.template)
{
warn ("Tried to add the inexisting tempalte " + this.type + " to Aegis. Please report thison the forums")
return false;
}
this.ID = m.playerGlobals[PlayerID].uniqueIDBOPlans++;
this.cost = new API3.Resources(this.template.cost());
this.number = 1;
this.category = "";
this.lastIsGo = undefined;
return true;
};
// if true, the queue manager will begin increasing this plan's account.
m.QueuePlan.prototype.isGo = function(gameState) {
return true;
};
// can we start this plan immediately?
m.QueuePlan.prototype.canStart = function(gameState) {
return false;
};
// needs to be updated if you want this to do something
m.QueuePlan.prototype.onStart = function(gameState) {
}
// process the plan.
m.QueuePlan.prototype.start = function(gameState) {
// should call onStart.
};
m.QueuePlan.prototype.getCost = function() {
var costs = new API3.Resources();
costs.add(this.cost);
if (this.number !== 1)
costs.multiply(this.number);
return costs;
};
// On Event functions.
// Can be used to do some specific stuffs
// Need to be updated to actually do something if you want them to.
// this is called by "Start" if it succeeds.
m.QueuePlan.prototype.onStart = function(gameState) {
}
// This is called by "isGo()" if it becomes true while it was false.
m.QueuePlan.prototype.onGo = function(gameState) {
}
// This is called by "isGo()" if it becomes false while it was true.
m.QueuePlan.prototype.onNotGo = function(gameState) {
}
return m;
}(AEGIS);

View File

@ -1,223 +0,0 @@
var AEGIS = function(m)
{
// Defines a construction plan, ie a building.
// We'll try to fing a good position if non has been provided
m.ConstructionPlan = function(gameState, type, metadata, position) {
if (!m.QueuePlan.call(this, gameState, type, metadata))
return false;
this.position = position ? position : 0;
this.category = "building";
return true;
};
m.ConstructionPlan.prototype = Object.create(m.QueuePlan.prototype);
// checks other than resource ones.
// TODO: change this.
// TODO: if there are specific requirements here, maybe try to do them?
m.ConstructionPlan.prototype.canStart = function(gameState) {
if (gameState.buildingsBuilt > 0)
return false;
if (!this.isGo(gameState))
return false;
// TODO: verify numeric limits etc
if (this.template.requiredTech() && !gameState.isResearched(this.template.requiredTech()))
{
return false;
}
var builders = gameState.findBuilders(this.type);
return (builders.length != 0);
};
m.ConstructionPlan.prototype.start = function(gameState) {
var builders = gameState.findBuilders(this.type).toEntityArray();
// We don't care which builder we assign, since they won't actually
// do the building themselves - all we care about is that there is
// some unit that can start the foundation
var pos = this.findGoodPosition(gameState);
if (!pos){
if (this.template.hasClass("Naval"))
gameState.ai.HQ.dockFailed = true;
m.debug("No room to place " + this.type);
return;
}
if (this.template.hasClass("Naval"))
m.debug (pos);
gameState.buildingsBuilt++;
if (gameState.getTemplate(this.type).buildCategory() === "Dock")
{
for (var angle = 0; angle < Math.PI * 2; angle += Math.PI/4)
{
builders[0].construct(this.type, pos.x, pos.z, angle, this.metadata);
}
} else {
// try with the lowest, move towards us unless we're same
if (pos.x == pos.xx && pos.z == pos.zz)
builders[0].construct(this.type, pos.x, pos.z, pos.angle, this.metadata);
else
{
for (var step = 0; step <= 1; step += 0.2)
{
builders[0].construct(this.type, (step*pos.x + (1-step)*pos.xx), (step*pos.z + (1-step)*pos.zz), pos.angle, this.metadata);
}
}
}
this.onStart(gameState);
};
m.ConstructionPlan.prototype.findGoodPosition = function(gameState) {
var template = gameState.getTemplate(this.type);
var cellSize = gameState.cellSize; // size of each tile
// First, find all tiles that are far enough away from obstructions:
var obstructionMap = m.createObstructionMap(gameState,0, template);
//obstructionMap.dumpIm(template.buildCategory() + "_obstructions_pre.png");
if (template.buildCategory() !== "Dock")
obstructionMap.expandInfluences();
//obstructionMap.dumpIm(template.buildCategory() + "_obstructions.png");
// Compute each tile's closeness to friendly structures:
var friendlyTiles = new API3.Map(gameState.sharedScript);
var alreadyHasHouses = false;
// If a position was specified then place the building as close to it as possible
if (this.position) {
var x = Math.floor(this.position[0] / cellSize);
var z = Math.floor(this.position[1] / cellSize);
friendlyTiles.addInfluence(x, z, 255);
} else {
// No position was specified so try and find a sensible place to build
if (this.metadata && this.metadata.base !== undefined)
for each (var px in gameState.ai.HQ.baseManagers[this.metadata.base].territoryIndices)
friendlyTiles.map[px] = 20;
gameState.getOwnStructures().forEach(function(ent) {
var pos = ent.position();
var x = Math.round(pos[0] / cellSize);
var z = Math.round(pos[1] / cellSize);
if (template.hasClass("Field")) {
if (ent.resourceDropsiteTypes() && ent.resourceDropsiteTypes().indexOf("food") !== -1)
friendlyTiles.addInfluence(x, z, 20, 50);
} else if (template.hasClass("House")) {
if (ent.hasClass("House"))
{
friendlyTiles.addInfluence(x, z, 15,40); // houses are close to other houses
alreadyHasHouses = true;
} else {
friendlyTiles.addInfluence(x, z, 15, -40); // and further away from other stuffs
}
} else if (template.hasClass("Farmstead")) {
// move farmsteads away to make room.
friendlyTiles.addInfluence(x, z, 25, -25);
} else {
if (template.hasClass("GarrisonFortress") && ent.genericName() == "House")
friendlyTiles.addInfluence(x, z, 30, -50);
else if (template.hasClass("Military"))
friendlyTiles.addInfluence(x, z, 10, -40);
// If this is not a field add a negative influence near the CivCentre because we want to leave this
// area for fields.
if (ent.hasClass("CivCentre"))
friendlyTiles.addInfluence(x, z, 20, -20);
}
});
if (template.hasClass("Farmstead"))
{
for (var j = 0; j < gameState.sharedScript.resourceMaps["wood"].map.length; ++j)
{
var value = friendlyTiles.map[j] - (gameState.sharedScript.resourceMaps["wood"].map[j])/3;
friendlyTiles.map[j] = value >= 0 ? value : 0;
}
}
if (this.metadata && this.metadata.base !== undefined)
for (var base in gameState.ai.HQ.baseManagers)
if (base != this.metadata.base)
for (var j in gameState.ai.HQ.baseManagers[base].territoryIndices)
friendlyTiles.map[gameState.ai.HQ.baseManagers[base].territoryIndices[j]] = 0;
}
//friendlyTiles.dumpIm(template.buildCategory() + "_" +gameState.getTimeElapsed() + ".png", 200);
// Find target building's approximate obstruction radius, and expand by a bit to make sure we're not too close, this
// allows room for units to walk between buildings.
// note: not for houses and dropsites who ought to be closer to either each other or a resource.
// also not for fields who can be stacked quite a bit
var radius = 0;
if (template.hasClass("GarrisonFortress"))
radius = Math.floor(template.obstructionRadius() / cellSize) + 2;
else if (template.buildCategory() === "Dock")
radius = 1;
else if (template.resourceDropsiteTypes() === undefined)
radius = Math.ceil(template.obstructionRadius() / cellSize) + 1;
else
radius = Math.ceil(template.obstructionRadius() / cellSize);
// further contract cause walls
// Note: I'm currently destroying them so that doesn't matter.
//if (gameState.playerData.civ == "iber")
// radius *= 0.95;
// Find the best non-obstructed
if (template.hasClass("House") && !alreadyHasHouses) {
// try to get some space first
var bestTile = friendlyTiles.findBestTile(10, obstructionMap);
var bestIdx = bestTile[0];
var bestVal = bestTile[1];
}
if (bestVal === undefined || bestVal === -1) {
var bestTile = friendlyTiles.findBestTile(radius, obstructionMap);
var bestIdx = bestTile[0];
var bestVal = bestTile[1];
}
if (bestVal === -1) {
return false;
}
//friendlyTiles.setInfluence((bestIdx % friendlyTiles.width), Math.floor(bestIdx / friendlyTiles.width), 1, 200);
//friendlyTiles.dumpIm(template.buildCategory() + "_" +gameState.getTimeElapsed() + ".png", 200);
var x = ((bestIdx % friendlyTiles.width) + 0.5) * cellSize;
var z = (Math.floor(bestIdx / friendlyTiles.width) + 0.5) * cellSize;
if (template.hasClass("House") || template.hasClass("Field") || template.resourceDropsiteTypes() !== undefined)
var secondBest = obstructionMap.findLowestNeighbor(x,z);
else
var secondBest = [x,z];
// default angle
var angle = 3*Math.PI/4;
return {
"x" : x,
"z" : z,
"angle" : angle,
"xx" : secondBest[0],
"zz" : secondBest[1]
};
};
return m;
}(AEGIS);

View File

@ -1,50 +0,0 @@
var AEGIS = function(m)
{
m.ResearchPlan = function(gameState, type, rush) {
if (!m.QueuePlan.call(this, gameState, type, {}))
return false;
if (this.template.researchTime === undefined)
return false;
this.category = "technology";
this.rush = rush ? true : false;
return true;
};
m.ResearchPlan.prototype = Object.create(m.QueuePlan.prototype);
m.ResearchPlan.prototype.canStart = function(gameState) {
// also checks canResearch
return (gameState.findResearchers(this.type).length !== 0);
};
m.ResearchPlan.prototype.start = function(gameState) {
var self = this;
//m.debug ("Starting the research plan for " + this.type);
var trainers = gameState.findResearchers(this.type).toEntityArray();
//for (var i in trainers)
// warn (this.type + " - " +trainers[i].genericName());
// Prefer training buildings with short queues
// (TODO: this should also account for units added to the queue by
// plans that have already been executed this turn)
if (trainers.length > 0){
trainers.sort(function(a, b) {
return (a.trainingQueueTime() - b.trainingQueueTime());
});
// drop anything in the queue if we rush it.
if (this.rush)
trainers[0].stopAllProduction(0.45);
trainers[0].research(this.type);
}
this.onStart(gameState);
};
return m;
}(AEGIS);

View File

@ -1,62 +0,0 @@
var AEGIS = function(m)
{
m.TrainingPlan = function(gameState, type, metadata, number, maxMerge) {
if (!m.QueuePlan.call(this, gameState, type, metadata))
return false;
this.category = "unit";
this.cost = new API3.Resources(this.template.cost(), this.template._template.Cost.Population);
this.number = number !== undefined ? number : 1;
this.maxMerge = maxMerge !== undefined ? maxMerge : 5;
return true;
};
m.TrainingPlan.prototype = Object.create(m.QueuePlan.prototype);
m.TrainingPlan.prototype.canStart = function(gameState) {
if (this.invalidTemplate)
return false;
// TODO: we should probably check pop caps
var trainers = gameState.findTrainers(this.type);
return (trainers.length != 0);
};
m.TrainingPlan.prototype.start = function(gameState) {
//warn("Executing TrainingPlan " + uneval(this));
var self = this;
var trainers = gameState.findTrainers(this.type).toEntityArray();
// Prefer training buildings with short queues
// (TODO: this should also account for units added to the queue by
// plans that have already been executed this turn)
if (trainers.length > 0){
trainers.sort(function(a, b) {
var aa = a.trainingQueueTime();
var bb = b.trainingQueueTime();
if (a.hasClass("Civic") && !self.template.hasClass("Support"))
aa += 10;
if (b.hasClass("Civic") && !self.template.hasClass("Support"))
bb += 10;
return (aa - bb);
});
if (this.metadata && this.metadata.base !== undefined && this.metadata.base === 0)
this.metadata.base = trainers[0].getMetadata(PlayerID,"base");
trainers[0].train(this.type, this.number, this.metadata);
}
this.onStart(gameState);
};
m.TrainingPlan.prototype.addItem = function(amount) {
if (amount === undefined)
amount = 1;
this.number += amount;
};
return m;
}(AEGIS);

View File

@ -1,122 +0,0 @@
var AEGIS = function(m)
{
/*
* Used to know which templates I have, which templates I know I can train, things like that.
* Mostly unused.
*/
m.TemplateManager = function(gameState) {
var self = this;
this.knownTemplatesList = [];
this.buildingTemplates = [];
this.unitTemplates = [];
this.templateCounters = {};
this.templateCounteredBy = {};
// this will store templates that exist
this.AcknowledgeTemplates(gameState);
this.getBuildableSubtemplates(gameState);
this.getTrainableSubtemplates(gameState);
this.getBuildableSubtemplates(gameState);
this.getTrainableSubtemplates(gameState);
// should be enough in 100% of the cases.
this.getTemplateCounters(gameState);
};
m.TemplateManager.prototype.AcknowledgeTemplates = function(gameState)
{
var self = this;
var myEntities = gameState.getOwnEntities();
myEntities.forEach(function(ent) { // }){
var template = ent._templateName;
if (self.knownTemplatesList.indexOf(template) === -1) {
self.knownTemplatesList.push(template);
if (ent.hasClass("Unit") && self.unitTemplates.indexOf(template) === -1)
self.unitTemplates.push(template);
else if (self.buildingTemplates.indexOf(template) === -1)
self.buildingTemplates.push(template);
}
});
}
m.TemplateManager.prototype.getBuildableSubtemplates = function(gameState)
{
for each (var templateName in this.knownTemplatesList) {
var template = gameState.getTemplate(templateName);
if (template !== null) {
var buildable = template.buildableEntities();
if (buildable !== undefined)
for each (var subtpname in buildable) {
if (this.knownTemplatesList.indexOf(subtpname) === -1) {
this.knownTemplatesList.push(subtpname);
var subtemplate = gameState.getTemplate(subtpname);
if (subtemplate.hasClass("Unit") && this.unitTemplates.indexOf(subtpname) === -1)
this.unitTemplates.push(subtpname);
else if (this.buildingTemplates.indexOf(subtpname) === -1)
this.buildingTemplates.push(subtpname);
}
}
}
}
}
m.TemplateManager.prototype.getTrainableSubtemplates = function(gameState)
{
for each (var templateName in this.knownTemplatesList) {
var template = gameState.getTemplate(templateName);
if (template !== null) {
var trainables = template.trainableEntities();
if (trainables !== undefined)
for each (var subtpname in trainables) {
if (this.knownTemplatesList.indexOf(subtpname) === -1) {
this.knownTemplatesList.push(subtpname);
var subtemplate = gameState.getTemplate(subtpname);
if (subtemplate.hasClass("Unit") && this.unitTemplates.indexOf(subtpname) === -1)
this.unitTemplates.push(subtpname);
else if (this.buildingTemplates.indexOf(subtpname) === -1)
this.buildingTemplates.push(subtpname);
}
}
}
}
}
m.TemplateManager.prototype.getTemplateCounters = function(gameState)
{
for (var i in this.unitTemplates)
{
var tp = gameState.getTemplate(this.unitTemplates[i]);
var tpname = this.unitTemplates[i];
this.templateCounters[tpname] = tp.getCounteredClasses();
}
}
// features auto-caching
m.TemplateManager.prototype.getCountersToClasses = function(gameState,classes,templateName)
{
if (templateName !== undefined && this.templateCounteredBy[templateName])
return this.templateCounteredBy[templateName];
var templates = [];
for (var i in this.templateCounters) {
var okay = false;
for each (var ticket in this.templateCounters[i]) {
var okaya = true;
for (var a in ticket[0]) {
if (classes.indexOf(ticket[0][a]) === -1)
okaya = false;
}
if (okaya && templates.indexOf(i) === -1)
templates.push([i, ticket[1]]);
}
}
templates.sort (function (a,b) { return -a[1] + b[1]; });
if (templateName !== undefined)
this.templateCounteredBy[templateName] = templates;
return templates;
}
return m;
}(AEGIS);

View File

@ -1,112 +0,0 @@
var AEGIS = function(m)
{
//The Timer class // The instance of this class is created in the qBot object under the name 'timer'
//The methods that are available to call from this instance are:
//timer.setTimer : Creates a new timer with the given interval (miliseconds).
// Optionally set dalay or a limited repeat value.
//timer.checkTimer : Gives true if called at the time of the interval.
//timer.clearTimer : Deletes the timer permanently. No way to get the same timer back.
//timer.activateTimer : Sets the status of a deactivated timer to active.
//timer.deactivateTimer : Deactivates a timer. Deactivated timers will never give true.
// Currently totally unused, iirc.
//-EmjeR-// Timer class //
m.Timer = function() {
///Private array.
var alarmList = [];
///Private methods
function num_alarms() {
return alarmList.length;
};
function get_alarm(id) {
return alarmList[id];
};
function add_alarm(index, alarm) {
alarmList[index] = alarm;
};
function delete_alarm(id) {
// Set the array element to undefined
delete alarmList[id];
};
///Privileged methods
// Add an new alarm to the list
this.setTimer = function(gameState, interval, delay, repeat) {
delay = delay || 0;
repeat = repeat || -1;
var index = num_alarms();
//Add a new alarm to the list
add_alarm(index, new alarm(gameState, index, interval, delay, repeat));
return index;
};
// Check if a alarm has reached its interval.
this.checkTimer = function(gameState,id) {
var alarm = get_alarm(id);
if (alarm === undefined)
return false;
if (!alarm.active)
return false;
var time = gameState.getTimeElapsed();
var alarmState = false;
// If repeat forever (repeat is -1). Or if the alarm has rung less times than repeat.
if (alarm.repeat < 0 || alarm.counter < alarm.repeat) {
var time_diffrence = time - alarm.start_time - alarm.delay - alarm.interval * alarm.counter;
if (time_diffrence > alarm.interval) {
alarmState = true;
alarm.counter++;
}
}
// Check if the alarm has rung 'alarm.repeat' times if so, delete the alarm.
if (alarm.counter >= alarm.repeat && alarm.repeat != -1) {
this.clearTimer(id);
}
return alarmState;
};
// Remove an alarm from the list.
this.clearTimer = function(id) {
delete_alarm(id);
};
// Activate a deactivated alarm.
this.activateTimer = function(id) {
var alarm = get_alarm(id);
alarm.active = true;
};
// Deactivate an active alarm but don't delete it.
this.deactivateTimer = function(id) {
var alarm = get_alarm(id);
alarm.active = false;
};
};
//-EmjeR-// Alarm class //
m.alarm = function(gameState, id, interval, delay, repeat) {
this.id = id;
this.interval = interval;
this.delay = delay;
this.repeat = repeat;
this.start_time = gameState.getTimeElapsed();
this.active = true;
this.counter = 0;
};
return m;
}(AEGIS);

View File

@ -1,32 +0,0 @@
var AEGIS = function(m)
{
m.AssocArraytoArray = function(assocArray) {
var endArray = [];
for (var i in assocArray)
endArray.push(assocArray[i]);
return endArray;
};
// A is the reference, B must be in "range" of A
// this supposes the range is already squared
m.inRange = function(a, b, range)// checks for X distance
{
// will avoid unnecessary checking for position in some rare cases... I'm lazy
if (a === undefined || b === undefined || range === undefined)
return undefined;
var dx = a[0] - b[0];
var dz = a[1] - b[1];
return ((dx*dx + dz*dz ) < range);
}
// slower than SquareVectorDistance, faster than VectorDistance but not exactly accurate.
m.ManhattanDistance = function(a, b)
{
var dx = a[0] - b[0];
var dz = a[1] - b[1];
return Math.abs(dx) + Math.abs(dz);
}
return m;
}(AEGIS);

View File

@ -1,643 +0,0 @@
var AEGIS = function(m)
{
/**
* This class makes a worker do as instructed by the economy manager
*/
m.Worker = function(ent) {
this.ent = ent;
this.maxApproachTime = 45000;
this.unsatisfactoryResource = false; // if true we'll reguarly check if we can't have better now.
this.baseID = 0;
};
m.Worker.prototype.update = function(baseManager, gameState) {
this.baseID = baseManager.ID;
var subrole = this.ent.getMetadata(PlayerID, "subrole");
if (!this.ent.position() || (this.ent.getMetadata(PlayerID,"fleeing") && gameState.getTimeElapsed() - this.ent.getMetadata(PlayerID,"fleeing") < 8000)){
// If the worker has no position then no work can be done
return;
}
if (this.ent.getMetadata(PlayerID,"fleeing"))
this.ent.setMetadata(PlayerID,"fleeing", undefined);
// Okay so we have a few tasks.
// If we're gathering, we'll check that we haven't run idle.
// ANd we'll also check that we're gathering a resource we want to gather.
// If we're fighting, let's not start gathering, heh?
// TODO: remove this when we're hunting?
if (this.ent.unitAIState().split(".")[1] === "COMBAT" || this.ent.getMetadata(PlayerID, "role") === "transport")
{
return;
}
if (subrole === "gatherer") {
if (this.ent.isIdle()) {
// if we aren't storing resources or it's the same type as what we're about to gather,
// let's just pick a new resource.
if (!this.ent.resourceCarrying() || this.ent.resourceCarrying().length === 0 ||
this.ent.resourceCarrying()[0].type === this.ent.getMetadata(PlayerID, "gather-type")){
Engine.ProfileStart("Start Gathering");
this.unsatisfactoryResource = false;
this.startGathering(baseManager,gameState);
Engine.ProfileStop();
this.startApproachingResourceTime = gameState.getTimeElapsed();
} else {
// Should deposit resources
Engine.ProfileStart("Return Resources");
if (!this.returnResources(gameState))
{
// no dropsite, abandon cargo.
// if we were ordered to gather something else, try that.
if (this.ent.resourceCarrying()[0].type !== this.ent.getMetadata(PlayerID, "gather-type"))
this.startGathering(baseManager,gameState);
else {
// okay so we haven't found a proper dropsite for the resource we're supposed to gather
// so let's get idle and the base manager will reassign us, hopefully well.
this.ent.setMetadata(PlayerID, "gather-type",undefined);
this.ent.setMetadata(PlayerID, "subrole", "idle");
this.ent.stopMoving();
}
}
Engine.ProfileStop();
}
// debug: show the resource we're gathering from
//Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [10,0,0]});
} else if (this.ent.unitAIState().split(".")[1] === "GATHER") {
// check for transport.
if (gameState.ai.playedTurn % 5 === 0)
{
if (this.ent.unitAIOrderData().length && this.ent.unitAIState().split(".")[2] === "APPROACHING" && this.ent.unitAIOrderData()[0]["target"])
{
var ress = gameState.getEntityById(this.ent.unitAIOrderData()[0]["target"]);
if (ress !== undefined)
{
var index = gameState.ai.accessibility.getAccessValue(ress.position());
var mIndex = gameState.ai.accessibility.getAccessValue(this.ent.position());
if (index !== mIndex && index !== 1)
{
//gameState.ai.HQ.navalManager.askForTransport(this.ent.id(), this.ent.position(), ress.position());
}
}
}
}
/*
if (gameState.getTimeElapsed() - this.startApproachingResourceTime > this.maxApproachTime)
{
if (this.ent.unitAIOrderData().length && this.ent.unitAIState().split(".")[1] === "GATHER"
&& this.ent.unitAIOrderData()[0]["target"])
{
var ent = gameState.getEntityById(this.ent.unitAIOrderData()[0]["target"]);
m.debug ("here " + this.startApproachingResourceAmount + "," + ent.resourceSupplyAmount());
if (ent && this.startApproachingResourceAmount == ent.resourceSupplyAmount() && this.startEnt == ent.id()) {
m.debug (ent.toString() + " is inaccessible");
ent.setMetadata(PlayerID, "inaccessible", true);
this.ent.flee(ent);
this.ent.setMetadata(PlayerID, "subrole", "idle");
}
}
}*/
// we're gathering. Let's check that it's not a resource we'd rather not gather from.
if ((this.ent.id() + gameState.ai.playedTurn) % 6 === 0 && this.checkUnsatisfactoryResource(gameState))
{
Engine.ProfileStart("Start Gathering");
this.startGathering(baseManager,gameState);
Engine.ProfileStop();
}
// TODO: reimplement the "reaching time" check.
/*if (gameState.getTimeElapsed() - this.startApproachingResourceTime > this.maxApproachTime) {
if (this.gatheringFrom) {
var ent = gameState.getEntityById(this.gatheringFrom);
if ((ent && ent.resourceSupplyAmount() == ent.resourceSupplyMax())) {
// if someone gathers from it, it's only that the pathfinder sucks.
m.debug (ent.toString() + " is inaccessible");
ent.setMetadata(PlayerID, "inaccessible", true);
this.ent.flee(ent);
this.ent.setMetadata(PlayerID, "subrole", "idle");
this.gatheringFrom = undefined;
}
}
}*/
} else if (this.ent.unitAIState().split(".")[1] === "COMBAT") {
/*if (gameState.getTimeElapsed() - this.startApproachingResourceTime > this.maxApproachTime) {
var ent = gameState.getEntityById(this.ent.unitAIOrderData()[0].target);
if (ent && !ent.isHurt()) {
// if someone gathers from it, it's only that the pathfinder sucks.
m.debug (ent.toString() + " is inaccessible from Combat");
ent.setMetadata(PlayerID, "inaccessible", true);
this.ent.flee(ent);
this.ent.setMetadata(PlayerID, "subrole", "idle");
this.gatheringFrom = undefined;
}
}*/
}
} else if(subrole === "builder") {
// check for transport.
/*if (gameState.ai.playedTurn % 5 === 0)
{
if (this.ent.unitAIOrderData().length && this.ent.unitAIState().split(".")[2] && this.ent.unitAIState().split(".")[2] === "APPROACHING" && this.ent.unitAIOrderData()[0]["target"])
{
var ress = gameState.getEntityById(this.ent.unitAIOrderData()[0]["target"]);
if (ress !== undefined)
{
var index = gameState.ai.accessibility.getAccessValue(ress.position());
var mIndex = gameState.ai.accessibility.getAccessValue(this.ent.position());
if (index !== mIndex && index !== 1)
{
gameState.ai.HQ.navalManager.askForTransport(this.ent.id(), this.ent.position(), ress.position());
}
}
}
}*/
if (this.ent.unitAIState().split(".")[1] !== "REPAIR") {
var target = gameState.getEntityById(this.ent.getMetadata(PlayerID, "target-foundation"));
// okay so apparently we aren't working.
// Unless we've been explicitely told to keep our role, make us idle.
if (!target || target.foundationProgress() === undefined && target.needsRepair() == false)
{
if (!this.ent.getMetadata(PlayerID, "keepSubrole"))
this.ent.setMetadata(PlayerID, "subrole", "idle");
} else
this.ent.repair(target);
}
this.startApproachingResourceTime = gameState.getTimeElapsed();
//Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [0,10,0]});
// TODO: we should maybe decide on our own to build other buildings, not rely on the assigntofoundation stuff.
} else if(subrole === "hunter") {
if (this.ent.isIdle()){
Engine.ProfileStart("Start Hunting");
this.startHunting(gameState, baseManager);
Engine.ProfileStop();
}
}
};
// check if our current resource is unsatisfactory
// this can happen in two ways:
// -either we were on an unsatisfactory resource last time we started gathering (this.unsatisfactoryResource)
// -Or we auto-moved to a bad resource thanks to the great UnitAI.
m.Worker.prototype.checkUnsatisfactoryResource = function(gameState) {
if (this.unsatisfactoryResource)
return true;
if (this.ent.unitAIOrderData().length && this.ent.unitAIState().split(".")[1] === "GATHER" && this.ent.unitAIState().split(".")[2] === "GATHERING" && this.ent.unitAIOrderData()[0]["target"])
{
var ress = gameState.getEntityById(this.ent.unitAIOrderData()[0]["target"]);
if (!ress || !ress.getMetadata(PlayerID,"linked-dropsite") || !ress.getMetadata(PlayerID,"linked-dropsite-nearby") || gameState.ai.accessibility.getAccessValue(ress.position()) === -1)
return true;
}
return false;
};
m.Worker.prototype.startGathering = function(baseManager, gameState) {
var resource = this.ent.getMetadata(PlayerID, "gather-type");
var ent = this.ent;
var self = this;
if (!ent.position()) {
// TODO: work out what to do when entity has no position
return;
}
/* Procedure for gathering resources
* Basically the AI focuses a lot on dropsites, and we will too
* So what we want is trying to find the best dropsites
* Traits: it needs to have a lot of resources available
* -it needs to have room available for me
* -it needs to be as close as possible (meaning base)
* Once we've found the best dropsite, we'll just pick a random close resource.
* TODO: we probably could pick something better.
*/
var wantedDropsite = 0;
var wantedDropsiteCoeff = 0;
var forceFaraway = false;
// So for now what I'll do is that I'll check dropsites in my base, then in other bases.
for (var id in baseManager.dropsites)
{
var dropsiteInfo = baseManager.dropsites[id][resource];
var capacity = baseManager.getDpWorkerCapacity(gameState, id, resource);
if (capacity === undefined) // presumably we're not ready
continue;
if (dropsiteInfo)
{
var coeff = dropsiteInfo[3] + (capacity-dropsiteInfo[5].length)*1000;
if (gameState.getEntityById(id).hasClass("CivilCentre"))
coeff += 20000;
if (coeff > wantedDropsiteCoeff)
{
wantedDropsiteCoeff = coeff;
wantedDropsite = id;
}
}
}
if (wantedDropsite === 0)
{
for (var id in baseManager.dropsites)
{
var dropsiteInfo = baseManager.dropsites[id][resource];
var capacity = baseManager.getDpWorkerCapacity(gameState, id, resource, true);
if (capacity === undefined) // presumably we're not ready
continue;
if (dropsiteInfo)
{
var coeff = dropsiteInfo[4] + (capacity-dropsiteInfo[5].length)*100;
if (coeff > wantedDropsiteCoeff)
{
wantedDropsiteCoeff = coeff;
wantedDropsite = id;
forceFaraway = true;
}
}
}
}
// so if we're here we have checked our whole base for a proper dropsite.
// for food, try to build fields if there are any.
if (wantedDropsiteCoeff < 200 && resource === "food" && this.buildAnyField(gameState))
return;
// haven't found any, check in other bases
// TODO: we should pick closest/most accessible bases first.
if (wantedDropsiteCoeff < 200)
{
for each (var base in gameState.ai.HQ.baseManagers)
{
// TODO: check we can access that base, and/or pick the best base.
if (base.ID === this.baseID || wantedDropsite !== 0)
continue;
for (var id in base.dropsites)
{
// if we have at least 1000 resources (including faraway) on this d
var dropsiteInfo = base.dropsites[id][resource];
var capacity = base.getDpWorkerCapacity(gameState, id, resource);
if (capacity === undefined) // presumably we're not ready
continue;
if (dropsiteInfo && dropsiteInfo[3] > 600 && dropsiteInfo[5].length < capacity)
{
// we want to change bases.
this.ent.setMetadata(PlayerID,"base",base.ID);
wantedDropsite = id;
break;
}
}
}
}
// I know, this is horrible code repetition.
// TODO: avoid horrible code repetition
// haven't found any, check in other bases
// TODO: we should pick closest/most accessible bases first.
if (wantedDropsiteCoeff < 200)
{
for each (var base in gameState.ai.HQ.baseManagers)
{
if (base.ID === this.baseID || wantedDropsite !== 0)
continue;
for (var id in base.dropsites)
{
// if we have at least 1000 resources (including faraway) on this d
var dropsiteInfo = base.dropsites[id][resource];
var capacity = baseManager.getDpWorkerCapacity(gameState, id, resource, true);
if (capacity === undefined) // presumably we're not ready
continue;
if (dropsiteInfo && dropsiteInfo[4] > 600 && dropsiteInfo[5].length < capacity)
{
this.ent.setMetadata(PlayerID,"base",base.ID);
wantedDropsite = id;
break; // here I'll break, TODO.
}
}
}
}
if (wantedDropsite === 0)
{
//TODO: something.
// Okay so we haven't found any appropriate dropsite anywhere.
m.debug("No proper dropsite found for " + resource + ", waiting.");
return;
} else
this.pickResourceNearDropsite(gameState, resource, wantedDropsite, forceFaraway);
};
m.Worker.prototype.pickResourceNearDropsite = function(gameState, resource, dropsiteID, forceFaraway)
{
// get the entity.
var dropsite = gameState.getEntityById(dropsiteID);
if (!dropsite)
return false;
// get the dropsite info
var baseManager = this.ent.getMetadata(PlayerID,"base");
baseManager = gameState.ai.HQ.baseManagers[baseManager];
var dropsiteInfo = baseManager.dropsites[dropsiteID][resource];
if (!dropsiteInfo)
return false;
var faraway = (forceFaraway === true) ? true : false;
var capacity = baseManager.getDpWorkerCapacity(gameState, dropsiteID, resource, faraway);
if (dropsiteInfo[5].length >= capacity || dropsiteInfo[3] < 200)
faraway = true;
var resources = (faraway === true) ? dropsiteInfo[1] : dropsiteInfo[0];
var wantedSupply = 0;
var wantedSupplyCoeff = Math.min();
// Pick the best resource
resources.forEach(function(supply) {
if (!supply.position())
return;
if (supply.getMetadata(PlayerID, "inaccessible") === true)
return;
if (m.IsSupplyFull(gameState, supply) === true)
return;
// TODO: make a quick accessibility check for sanity
/* if (!gameState.ai.accessibility.pathAvailable(gameState, ent.position(), supply.position())) {
//m.debug ("nopath");
return;
}*/
// some simple check for chickens: if they're in a square that's inaccessible, we won't gather from them.
// TODO: make sure this works with rounding.
if (supply.footprintRadius() < 1)
{
var fakeMap = new API3.Map(gameState.sharedScript,gameState.getMap().data);
var id = fakeMap.gamePosToMapPos(supply.position())[0] + fakeMap.width*fakeMap.gamePosToMapPos(supply.position())[1];
if ( (gameState.sharedScript.passabilityClasses["pathfinderObstruction"] & gameState.getMap().data[id]) )
{
supply.setMetadata(PlayerID, "inaccessible", true)
return;
}
}
// Factor in distance to the dropsite.
var dist = API3.SquareVectorDistance(supply.position(), dropsite.position());
var territoryOwner = m.createTerritoryMap(gameState).getOwner(supply.position());
if (territoryOwner != PlayerID && territoryOwner != 0) {
dist *= 5.0;
} else if (dist < 40000 && supply.resourceSupplyType().generic == "treasure"){
// go for treasures if they're not in enemy territory
dist /= 1000;
}
if (dist < wantedSupplyCoeff) {
wantedSupplyCoeff = dist;
wantedSupply = supply;
}
});
if (!wantedSupply)
{
if (resource === "food" && this.buildAnyField(gameState))
return true;
//m.debug("Found a proper dropsite for " + resource + " but apparently no resources are available.");
return false;
}
var pos = wantedSupply.position();
// add the worker to the turn cache
m.AddTCGatherer(gameState,wantedSupply.id());
// helper to check if it's accessible.
this.maxApproachTime = Math.max(30000, API3.VectorDistance(pos,this.ent.position()) * 5000);
this.startApproachingResourceAmount = wantedSupply.resourceSupplyAmount();
// helper for unsatisfactory resource.
this.startEnt = wantedSupply.id();
this.ent.gather(wantedSupply);
// sanity.
this.ent.setMetadata(PlayerID, "linked-to-dropsite", dropsiteID);
this.ent.setMetadata(PlayerID, "target-foundation", undefined);
return true;
};
// Makes the worker deposit the currently carried resources at the closest dropsite
m.Worker.prototype.returnResources = function(gameState){
if (!this.ent.resourceCarrying() || this.ent.resourceCarrying().length === 0){
return true; // assume we're OK.
}
var resource = this.ent.resourceCarrying()[0].type;
var self = this;
if (!this.ent.position()){
// TODO: work out what to do when entity has no position
return true;
}
var closestDropsite = undefined;
var dist = Math.min();
gameState.getOwnDropsites(resource).forEach(function(dropsite){
if (dropsite.position()){
var d = API3.SquareVectorDistance(self.ent.position(), dropsite.position());
if (d < dist){
dist = d;
closestDropsite = dropsite;
}
}
});
if (!closestDropsite){
m.debug("No dropsite found to deposit " + resource);
return false;
}
this.ent.returnResources(closestDropsite);
return true;
};
m.Worker.prototype.startHunting = function(gameState, baseManager){
var ent = this.ent;
if (!ent.position() || !baseManager.isHunting)
return;
// So here we're doing it basic. We check what we can hunt, we hunt it. No fancies.
var resources = gameState.getResourceSupplies("food");
if (resources.length === 0){
m.debug("No food found to hunt!");
return;
}
var supplies = [];
var nearestSupplyDist = Math.min();
var nearestSupply = undefined;
resources.forEach(function(supply) { //}){
if (!supply.position())
return;
if (supply.getMetadata(PlayerID, "inaccessible") === true)
return;
if (supply.isFull() === true)
return;
if (!supply.hasClass("Animal"))
return;
// measure the distance to the resource
var dist = API3.SquareVectorDistance(supply.position(), ent.position());
var territoryOwner = m.createTerritoryMap(gameState).getOwner(supply.position());
if (territoryOwner != PlayerID && territoryOwner != 0) {
dist *= 3.0;
}
// quickscope accessbility check
if (!gameState.ai.accessibility.pathAvailable(gameState, ent.position(), supply.position(),false, true))
return;
if (dist < nearestSupplyDist) {
nearestSupplyDist = dist;
nearestSupply = supply;
}
});
if (nearestSupply) {
var pos = nearestSupply.position();
var nearestDropsite = 0;
var minDropsiteDist = 1000000;
// find a fitting dropsites in case we haven't already.
gameState.getOwnDropsites("food").forEach(function (dropsite){ //}){
if (dropsite.position()){
var dist = API3.SquareVectorDistance(pos, dropsite.position());
if (dist < minDropsiteDist){
minDropsiteDist = dist;
nearestDropsite = dropsite;
}
}
});
if (!nearestDropsite)
{
baseManager.isHunting = false;
ent.setMetadata(PlayerID, "role", undefined);
m.debug ("No dropsite for hunting food");
return;
}
if (minDropsiteDist > 35000) {
baseManager.isHunting = false;
ent.setMetadata(PlayerID, "role", undefined);
} else {
ent.gather(nearestSupply);
ent.setMetadata(PlayerID, "target-foundation", undefined);
}
} else {
baseManager.isHunting = false;
ent.setMetadata(PlayerID, "role", undefined);
m.debug("No food found for hunting! (2)");
}
};
m.Worker.prototype.getResourceType = function(type){
if (!type || !type.generic){
return undefined;
}
if (type.generic === "treasure"){
return type.specific;
}else{
return type.generic;
}
};
m.Worker.prototype.getGatherRate = function(gameState) {
if (this.ent.getMetadata(PlayerID,"subrole") !== "gatherer")
return 0;
var rates = this.ent.resourceGatherRates();
if (this.ent.unitAIOrderData().length && this.ent.unitAIState().split(".")[1] === "GATHER" && this.ent.unitAIOrderData()[0]["target"])
{
var ress = gameState.getEntityById(this.ent.unitAIOrderData()[0]["target"]);
if (!ress)
return 0;
var type = ress.resourceSupplyType();
if (type.generic == "treasure")
return 1000;
var tstring = type.generic + "." + type.specific;
//m.debug (+rates[tstring] + " for " + tstring + " for " + this.ent._templateName);
if (rates[tstring])
return rates[tstring];
return 0;
}
return 0;
};
m.Worker.prototype.buildAnyField = function(gameState){
var self = this;
var foundations = gameState.getOwnFoundations();
var baseFoundations = foundations.filter(API3.Filters.byMetadata(PlayerID,"base",this.baseID));
var maxGatherers = gameState.getTemplate(gameState.applyCiv("structures/{civ}_field")).maxGatherers();
var bestFarmEnt = undefined;
var bestFarmCoeff = 10000000;
baseFoundations.forEach(function (found) {
if (found.hasClass("Field")) {
var coeff = API3.SquareVectorDistance(found.position(), self.ent.position());
if (found.getBuildersNb() && found.getBuildersNb() >= maxGatherers)
return;
if (coeff <= bestFarmCoeff)
{
bestFarmEnt = found;
bestFarmCoeff = coeff;
}
}
});
if (bestFarmEnt !== undefined)
{
self.ent.repair(bestFarmEnt);
return true;
}
foundations.forEach(function (found) {
if (found.hasClass("Field")) {
var coeff = API3.SquareVectorDistance(found.position(), self.ent.position());
if (found.getBuildersNb() && found.getBuildersNb() >= found.maxGatherers())
return;
if (coeff <= bestFarmCoeff)
{
bestFarmEnt = found;
bestFarmCoeff = coeff;
}
}
});
if (bestFarmEnt !== undefined)
{
self.ent.repair(bestFarmEnt);
self.ent.setMetadata(PlayerID,"base", bestFarmEnt.getMetadata(PlayerID,"base"));
this.startEnt = bestFarmEnt.id();
self.ent.gather(bestFarmEnt,true);
self.ent.setMetadata(PlayerID, "target-foundation", undefined);
return true;
}
return false;
};
return m;
}(AEGIS);