Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/enemy-watcher.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/enemy-watcher.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/enemy-watcher.js (nonexistent) @@ -1,212 +0,0 @@ -/* - * A class that keeps track of enemy buildings, units, and pretty much anything I can think of (still a LOT TODO here) - * Only watches one enemy, you'll need one per enemy. - * Note: pretty much unused in the current version. - */ - -var enemyWatcher = function(gameState, playerToWatch) { - - this.watched = playerToWatch; - - // using global entity collections, shared by any AI that knows the name of this. - - var filter = Filters.and(Filters.byClass("Structure"), Filters.byOwner(this.watched)); - this.enemyBuildings = gameState.updatingGlobalCollection("player-" +this.watched + "-structures", filter); - - filter = Filters.and(Filters.byClass("Worker"), Filters.byOwner(this.watched)); - this.enemyCivilians = gameState.updatingGlobalCollection("player-" +this.watched + "-civilians", filter); - - filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.byOwner(this.watched)); - this.enemySoldiers = gameState.updatingGlobalCollection("player-" +this.watched + "-soldiers", filter); - - filter = Filters.and(Filters.byClass("Worker"), Filters.byOwner(this.watched)); - this.enemyCivilians = gameState.getEnemyEntities().filter(filter); - this.enemyCivilians.registerUpdates(); - - filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.byOwner(this.watched)); - this.enemySoldiers = gameState.getEnemyEntities().filter(filter); - this.enemySoldiers.registerUpdates(); - - // entity collections too. - this.armies = {}; - - this.enemyBuildingClass = {}; - this.totalNBofArmies = 0; - - // this is an array of integers, refering to "this.armies[ XX ]" - this.dangerousArmies = []; - -}; -enemyWatcher.prototype.getAllEnemySoldiers = function() { - return this.enemySoldiers; -}; -enemyWatcher.prototype.getAllEnemyBuildings = function() { - return this.enemyBuildings; -}; - -enemyWatcher.prototype.getEnemyBuildings = function(gameState, specialClass, OneTime) { - var filter = Filters.byClass(specialClass); - - if (OneTime && gameState.getGEC("player-" +this.watched + "-structures-" +specialClass)) - return gameState.getGEC("player-" +this.watched + "-structures-" +specialClass); - else if (OneTime) - return this.enemyBuildings.filter(filter); - - return gameState.updatingGlobalCollection("player-" +this.watched + "-structures-" +specialClass, filter, gameState.getGEC("player-" +this.watched + "-structures")); -}; -enemyWatcher.prototype.getDangerousArmies = function() { - var toreturn = {}; - for (var i in this.dangerousArmies) - toreturn[this.dangerousArmies[i]] = this.armies[this.dangerousArmies[i]]; - return toreturn; -}; -enemyWatcher.prototype.getSafeArmies = function() { - var toreturn = {}; - for (var i in this.armies) - if (this.dangerousArmies.indexOf(i) == -1) - toreturn[i] = this.armies[i]; - return toreturn; -}; -enemyWatcher.prototype.resetDangerousArmies = function() { - this.dangerousArmies = []; -}; -enemyWatcher.prototype.setAsDangerous = function(armyID) { - if (this.dangerousArmies.indexOf(armyID) === -1) - this.dangerousArmies.push(armyID); -}; -enemyWatcher.prototype.isDangerous = function(armyID) { - if (this.dangerousArmies.indexOf(armyID) === -1) - return false; - return true; -}; -// returns [id, army] -enemyWatcher.prototype.getArmyFromMember = function(memberID) { - for (var i in this.armies) { - if (this.armies[i].toIdArray().indexOf(memberID) !== -1) - return [i,this.armies[i]]; - } - return undefined; -}; -enemyWatcher.prototype.isPartOfDangerousArmy = function(memberID) { - var armyID = this.getArmyFromMember(memberID)[0]; - if (this.isDangerous(armyID)) - return true; - return false; -}; -enemyWatcher.prototype.cleanDebug = function() { - for (var armyID in this.armies) { - var army = this.armies[armyID]; - debug ("Army " +armyID); - debug (army.length +" members, centered around " +army.getCentrePosition()); - } -} - -// this will monitor any unmonitored soldier. -enemyWatcher.prototype.detectArmies = function(gameState){ - //this.cleanDebug(); - - var self = this; - if (gameState.ai.playedTurn % 4 === 0) { - Engine.ProfileStart("Looking for new soldiers"); - // let's loop through unmonitored enemy soldiers - this.unmonitoredEnemySoldiers.forEach( function (enemy) { //}){ - if (enemy.position() === undefined) - return; - - // this was an unmonitored unit, we do not know any army associated with it. We assign it a new army (we'll merge later if needed) - enemy.setMetadata(PlayerID, "monitored","true"); - var armyID = gameState.player + "" + self.totalNBofArmies; - self.totalNBofArmies++, - enemy.setMetadata(PlayerID, "EnemyWatcherArmy",armyID); - var filter = Filters.byMetadata(PlayerID, "EnemyWatcherArmy",armyID); - var army = self.enemySoldiers.filter(filter); - self.armies[armyID] = army; - self.armies[armyID].registerUpdates(); - self.armies[armyID].length; - }); - Engine.ProfileStop(); - } else if (gameState.ai.playedTurn % 16 === 3) { - Engine.ProfileStart("Merging"); - this.mergeArmies(); // calls "scrap empty armies" - Engine.ProfileStop(); - } else if (gameState.ai.playedTurn % 16 === 7) { - Engine.ProfileStart("Splitting"); - this.splitArmies(gameState); - Engine.ProfileStop(); - } -}; -// this will merge any two army who are too close together. The distance for "army" is fairly big. -// note: this doesn't actually merge two entity collections... It simply changes the unit metadatas, and will clear the empty entity collection -enemyWatcher.prototype.mergeArmies = function(){ - for (var army in this.armies) { - var firstArmy = this.armies[army]; - if (firstArmy.length !== 0) { - var firstAPos = firstArmy.getApproximatePosition(4); - for (var otherArmy in this.armies) { - if (otherArmy !== army && this.armies[otherArmy].length !== 0) { - var secondArmy = this.armies[otherArmy]; - // we're not self merging, so we check if the two armies are close together - if (inRange(firstAPos,secondArmy.getApproximatePosition(4), 4000 ) ) { - // okay so we merge the two together - - // if the other one was dangerous and we weren't, we're now. - if (this.dangerousArmies.indexOf(otherArmy) !== -1 && this.dangerousArmies.indexOf(army) === -1) - this.dangerousArmies.push(army); - - secondArmy.forEach( function(ent) { - ent.setMetadata(PlayerID, "EnemyWatcherArmy",army); - }); - } - } - } - } - } - this.ScrapEmptyArmies(); -}; -enemyWatcher.prototype.ScrapEmptyArmies = function(){ - var removelist = []; - for (var army in this.armies) { - if (this.armies[army].length === 0) { - removelist.push(army); - // if the army was dangerous, we remove it from the list - if (this.dangerousArmies.indexOf(army) !== -1) - this.dangerousArmies.splice(this.dangerousArmies.indexOf(army),1); - } - } - for each (var toRemove in removelist) { - delete this.armies[toRemove]; - } -}; -// splits any unit too far from the centerposition -enemyWatcher.prototype.splitArmies = function(gameState){ - var self = this; - - var map = Map.createTerritoryMap(gameState); - - for (var armyID in this.armies) { - var army = this.armies[armyID]; - var centre = army.getApproximatePosition(4); - - if (map.getOwner(centre) === gameState.player) - continue; - - army.forEach( function (enemy) { - if (enemy.position() === undefined) - return; - - if (!inRange(enemy.position(),centre, 3500) ) { - var newArmyID = gameState.player + "" + self.totalNBofArmies; - if (self.dangerousArmies.indexOf(armyID) !== -1) - self.dangerousArmies.push(newArmyID); - - self.totalNBofArmies++, - enemy.setMetadata(PlayerID, "EnemyWatcherArmy",newArmyID); - var filter = Filters.byMetadata(PlayerID, "EnemyWatcherArmy",newArmyID); - var newArmy = self.enemySoldiers.filter(filter); - self.armies[newArmyID] = newArmy; - self.armies[newArmyID].registerUpdates(); - self.armies[newArmyID].length; - } - }); - } -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/enemy-watcher.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:executable ## -1 +0,0 ## -* \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/economy.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/economy.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/economy.js (nonexistent) @@ -1,1340 +0,0 @@ -/* Economy Manager - * Deals with anything economic. Worker logic is in worker.js. - */ - -var EconomyManager = function() { - this.targetNumBuilders = Config.Economy.targetNumBuilders; // number of workers we want building stuff - this.targetNumFields = 3; // initial setting only. - - // Used by the QueueManager to determine future needs. - this.baseNeed = {}; - this.baseNeed["food"] = 300; // only really early. - this.baseNeed["wood"] = 130; - this.baseNeed["stone"] = 0; - this.baseNeed["metal"] = 0; - - // see rePrioritize() for more info - this.lastStatG = { "food" : 0, "wood" : 0, "stone" : 0, "metal" : 0}; // resource collecting stats: gathered - this.lastStatU = { "food" : 0, "wood" : 0, "stone" : 0, "metal" : 0}; // resource collecting stats: used - - this.dockStartTime = Config.Economy.dockStartTime * 1000; - this.farmsteadStartTime = Config.Economy.farmsteadStartTime * 1000; - this.techStartTime = Config.Economy.techStartTime * 1000; - - this.dockFailed = false; // sanity check - - // A few notes about these maps. They're updated by checking for "create" and "destroy" events. - // They are also updated by dropsites, as resources that are seen as part of a dropsite are - // removed from the map. The AI otherwise tries to build tons of dropsites next to each other. - // It might actually be better to create when needed over a few frames. Dunno. - this.resourceMaps = {}; // Contains maps showing the density of wood, stone and metal - this.CCResourceMaps = {}; // Contains maps showing the density of wood, stone and metal, optimized for CC placement. - - this.setCount = 0; //stops villagers being reassigned to other resources too frequently, count a set number of - //turns before trying to reassign them. - - // this means we'll have about a big third of women, and thus we can maximize resource gathering rates. - this.femaleRatio = Config.Economy.femaleRatio; - - this.farmingFields = false; - - this.dropsiteNumbers = {"wood": 1, "stone": 0.5, "metal": 0.5}; -}; -// More initialisation for stuff that needs the gameState -EconomyManager.prototype.init = function(gameState, events){ - if (Config.Economy.targetNumWorkers) - this.targetNumWorkers = Config.Economy.targetNumWorkers; - else if (this.targetNumWorkers === undefined) - this.targetNumWorkers = Math.max(Math.floor(gameState.getPopulationMax()*0.45), 1); - - var availableRess = 0; - var availableRessFood = 0; - availableRess += gameState.ai.queueManager.getAvailableResources(gameState,false).toInt(); - availableRessFood += gameState.ai.queueManager.getAvailableResources(gameState,false)["food"]; - - var ents = gameState.getEntities().filter(Filters.byOwner(PlayerID)); - ents = ents.filter(Filters.byClass("CivCentre")).toEntityArray(); - if (ents.length > 0) - { - gameState.getResourceSupplies("food").forEach( function (ent) { - if (ent.resourceSupplyType().generic === "treasure" && SquareVectorDistance(ent.position(), ents[0].position()) < 5000) { - availableRess += ent.resourceSupplyMax(); - availableRessFood += ent.resourceSupplyMax(); - } - }); - gameState.getResourceSupplies("stone").forEach( function (ent) { - if (ent.resourceSupplyType().generic === "treasure" && SquareVectorDistance(ent.position(), ents[0].position()) < 5000) - availableRess += ent.resourceSupplyMax(); - }); - gameState.getResourceSupplies("metal").forEach( function (ent) { - if (ent.resourceSupplyType().generic === "treasure" && SquareVectorDistance(ent.position(), ents[0].position()) < 5000) - availableRess += ent.resourceSupplyMax(); - }); - gameState.getResourceSupplies("wood").forEach( function (ent) { - if (ent.resourceSupplyType().generic === "treasure" && SquareVectorDistance(ent.position(), ents[0].position()) < 5000) - availableRess += ent.resourceSupplyMax(); - }); - } - if (availableRess > 2000) - this.fastStart = true; - - if (availableRessFood < 500) - { - // this is going to be slow. - this.fastStart = false; - Config.Economy.townPhase += 60; // add one minute - this.baseNeed["wood"] = 150; - } - - // initialize once all the resource maps. - this.updateResourceMaps(gameState, events); - this.updateResourceConcentrations(gameState,"food"); - this.updateResourceConcentrations(gameState,"wood"); - this.updateResourceConcentrations(gameState,"stone"); - this.updateResourceConcentrations(gameState,"metal"); - - this.reassignIdleWorkers(gameState); -}; - -// okay, so here we'll create both females and male workers. -// We'll try to keep close to the "ratio" defined atop. -// Choice of citizen soldier is a bit messy. -// Before having 100 workers it focuses on speed, cost, and won't choose units that cost stone/metal -// After 100 it just picks the strongest; -// TODO: This should probably be changed to favor a more mixed approach for better defense. -// (or even to adapt based on estimated enemy strategy). -// Also deals with setting the watned numbers of dropsites and fields since it's practical, -// this function should probably be renamed. -EconomyManager.prototype.trainMoreWorkers = function(gameState, queues) { - // Count the workers in the world and in progress - var numFemales = gameState.countEntitiesAndQueuedByType(gameState.applyCiv("units/{civ}_support_female_citizen")); - numFemales += queues.villager.countTotalQueuedUnits(); - - // counting the workers that aren't part of a plan - var numWorkers = 0; - gameState.getOwnEntities().forEach (function (ent) { - if (ent.getMetadata(PlayerID, "role") == "worker" && ent.getMetadata(PlayerID, "plan") == undefined) - numWorkers++; - }); - var numInTraining = 0; - gameState.getOwnTrainingFacilities().forEach(function(ent) { - ent.trainingQueue().forEach(function(item) { - if (item.metadata && item.metadata.role == "worker" && item.metadata.plan == undefined) - numWorkers += item.count; - numInTraining += item.count; - }); - }); - var numQueued = queues.villager.countTotalQueuedUnits() + queues.citizenSoldier.countTotalQueuedUnits(); - var numTotal = numWorkers + numQueued; - - if (gameState.currentPhase() > 1 || gameState.isResearching("phase_town")) - this.targetNumFields = numWorkers/10.0; // 5 workers per field max. - else - this.targetNumFields = 1; - - // ought to refine this. - if ((gameState.ai.playedTurn+2) % 3 === 0) { - this.dropsiteNumbers = {"wood": Math.ceil(numWorkers/25)/2, "stone": Math.ceil(numWorkers/30)/2, "metal": Math.ceil(numWorkers/20)/2}; - if (numWorkers < 30) - { - this.dropsiteNumbers["wood"] -= 0.5; - this.dropsiteNumbers["metal"] -= 0.5; - this.dropsiteNumbers["stone"] -= 0.5; - } - } - - //debug (numTotal + "/" +this.targetNumWorkers + ", " +numFemales +"/" +numTotal); - - // If we have too few, train more - // should plan enough to always have females… - if (numTotal < this.targetNumWorkers && numQueued < 15 && ((queues.villager.length() < 2 && queues.citizenSoldier.length() < 2) || gameState.currentPhase() !== 1) && (numInTraining) < 15) { - var template = gameState.applyCiv("units/{civ}_support_female_citizen"); - var size = Math.min(Math.ceil(gameState.getTimeElapsed() / 20000),5); - if (numFemales/numTotal > this.femaleRatio && (gameState.getTimeElapsed() > 150*1000 || (this.fastStart && gameState.getTimeElapsed() > 60*1000))) { - if (numTotal < 100) - template = this.findBestTrainableUnit(gameState, ["CitizenSoldier", "Infantry"], [ ["cost",1], ["speed",0.5], ["costsResource", 0.5, "stone"], ["costsResource", 0.5, "metal"]]); - else - template = this.findBestTrainableUnit(gameState, ["CitizenSoldier", "Infantry"], [ ["strength",1] ]); - if (!template) - template = gameState.applyCiv("units/{civ}_support_female_citizen"); - else - size = Math.min(Math.ceil(gameState.getTimeElapsed() / 60000),5); - } - - if ((gameState.getTimeElapsed() < 60000 && gameState.ai.queueManager.getAvailableResources(gameState)["food"] > 250) || this.fastStart) - size = 5; - - if (template === gameState.applyCiv("units/{civ}_support_female_citizen")) - queues.villager.addItem(new UnitTrainingPlan(gameState, template, { "role" : "worker" }, size, size )); - else - queues.citizenSoldier.addItem(new UnitTrainingPlan(gameState, template, { "role" : "worker" }, size, size )); - } -}; - -// Tries to research any available tech -// Only one at once. Also does military tech (selection is completely random atm) -// TODO: Lots, lots, lots here. -EconomyManager.prototype.tryResearchTechs = function(gameState, queues) { - if (queues.minorTech.totalLength() === 0) - { - var possibilities = gameState.findAvailableTech(); - if (possibilities.length === 0) - return; - // randomly pick one. No worries about pairs in that case. - var p = Math.floor((Math.random()*possibilities.length)); - queues.minorTech.addItem(new ResearchPlan(gameState, possibilities[p][0])); - } -} - -// picks the best template based on parameters and classes -// Similar to the one used in the Military manager but not quite. -EconomyManager.prototype.findBestTrainableUnit = function(gameState, classes, parameters) { - var units = gameState.findTrainableUnits(classes); - - if (units.length === 0) - return undefined; - - units.sort(function(a, b) { //}) { - var aDivParam = 0, bDivParam = 0; - var aTopParam = 0, bTopParam = 0; - for (var i in parameters) { - var param = parameters[i]; - - if (param[0] == "base") { - aTopParam = param[1]; - bTopParam = param[1]; - } - if (param[0] == "strength") { - aTopParam += getMaxStrength(a[1]) * param[1]; - bTopParam += getMaxStrength(b[1]) * param[1]; - } - if (param[0] == "speed") { - aTopParam += a[1].walkSpeed() * param[1]; - bTopParam += b[1].walkSpeed() * param[1]; - } - - if (param[0] == "cost") { - aDivParam += a[1].costSum() * param[1]; - bDivParam += b[1].costSum() * param[1]; - } - // requires a third parameter which is the resource - if (param[0] == "costsResource") { - if (a[1].cost()[param[2]]) - aTopParam *= param[1]; - if (b[1].cost()[param[2]]) - bTopParam *= param[1]; - } - } - return -(aTopParam/(aDivParam+1)) + (bTopParam/(bDivParam+1)); - }); - return units[0][0]; -}; - - - -// Pick the resource which most needs another worker -EconomyManager.prototype.pickMostNeededResources = function(gameState) { - var self = this; - - // Find what resource type we're most in need of - if (!gameState.turnCache["gather-weights-calculated"]){ - this.gatherWeights = gameState.ai.queueManager.futureNeeds(gameState,this); - gameState.turnCache["gather-weights-calculated"] = true; - } - - var numGatherers = {}; - for (var type in this.gatherWeights){ - numGatherers[type] = gameState.updatingCollection("workers-gathering-" + type, - Filters.byMetadata(PlayerID, "gather-type", type)).length;//, gameState.getOwnEntitiesByRole("worker")).length; - } - //var totalWeight = numGatherers[a].length/gameState.getOwnEntitiesByRole("worker")).length; - var types = Object.keys(this.gatherWeights); - - types.sort(function(a, b) { - // Prefer fewer gatherers (divided by weight) - var va = numGatherers[a] / (self.gatherWeights[a]+1); - var vb = numGatherers[b] / (self.gatherWeights[b]+1); - if (self.gatherWeights[a] === 0) - va = 10000; - if (self.gatherWeights[b] === 0) - vb = 10000; - return va-vb; - }); - return types; -}; - -EconomyManager.prototype.reassignRolelessUnits = function(gameState) { - //TODO: Move this out of the economic section - var roleless = gameState.getOwnEntitiesByRole(undefined); - - roleless.forEach(function(ent) { - if ((ent.hasClass("Worker") || ent.hasClass("CitizenSoldier")) && !ent.getMetadata(PlayerID, "stoppedHunting")) { - ent.setMetadata(PlayerID, "role", "worker"); - } - }); -}; - -// If the numbers of workers on the resources is unbalanced then set some of workers to idle so -// they can be reassigned by reassignIdleWorkers. -EconomyManager.prototype.setWorkersIdleByPriority = function(gameState){ - this.gatherWeights = gameState.ai.queueManager.futureNeeds(gameState,this); - - var numGatherers = {}; - var totalGatherers = 0; - var totalWeight = 0; - for ( var type in this.gatherWeights){ - numGatherers[type] = 0; - totalWeight += this.gatherWeights[type]; - } - - gameState.getOwnEntitiesByRole("worker").forEach(function(ent) { - if (ent.getMetadata(PlayerID, "subrole") === "gatherer"){ - numGatherers[ent.getMetadata(PlayerID, "gather-type")] += 1; - totalGatherers += 1; - } - }); - - for ( var type in this.gatherWeights){ - var allocation = Math.floor(totalGatherers * (this.gatherWeights[type]/totalWeight)); - if (allocation < numGatherers[type]){ - var numToTake = numGatherers[type] - allocation; - gameState.getOwnEntitiesByRole("worker").forEach(function(ent) { - if (ent.getMetadata(PlayerID, "subrole") === "gatherer" && ent.getMetadata(PlayerID, "gather-type") === type && numToTake > 0){ - ent.setMetadata(PlayerID, "subrole", "idle"); - ent.stopMoving(); - numToTake -= 1; - } - }); - } - } -}; - -EconomyManager.prototype.reassignIdleWorkers = function(gameState) { - - var self = this; - - // Search for idle workers, and tell them to gather resources based on demand - var filter = Filters.isIdle(); - var idleWorkers = gameState.updatingCollection("idle-workers", filter, gameState.getOwnEntitiesByRole("worker")); - - if (idleWorkers.length) { - idleWorkers.forEach(function(ent) { - // Check that the worker isn't garrisoned - if (ent.position() === undefined){ - return; - } - if (ent.hasClass("Worker")) { - var types = self.pickMostNeededResources(gameState); - ent.setMetadata(PlayerID, "subrole", "gatherer"); - ent.setMetadata(PlayerID, "gather-type", types[0]); - } else { - ent.setMetadata(PlayerID, "subrole", "hunter"); - } - - }); - } -}; - -EconomyManager.prototype.workersBySubrole = function(gameState, subrole) { - var workers = gameState.getOwnEntitiesByRole("worker"); - return gameState.updatingCollection("subrole-" + subrole, Filters.byMetadata(PlayerID, "subrole", subrole), workers); -}; - -EconomyManager.prototype.assignToFoundations = function(gameState, noRepair) { - // If we have some foundations, and we don't have enough builder-workers, - // try reassigning some other workers who are nearby - - // AI tries to use builders sensibly, not completely stopping its econ. - - var foundations = gameState.getOwnFoundations().toEntityArray(); - var damagedBuildings = gameState.getOwnEntities().filter(function (ent) { if (ent.needsRepair() && ent.getMetadata(PlayerID, "plan") == undefined) { return true; } return false; }).toEntityArray(); - - // Check if nothing to build - if (!foundations.length && !damagedBuildings.length){ - return; - } - var workers = gameState.getOwnEntitiesByRole("worker").filter(Filters.not(Filters.byClass("Cavalry"))); - var builderWorkers = this.workersBySubrole(gameState, "builder"); - - var addedWorkers = 0; - - var maxTotalBuilders = Math.ceil(this.numWorkers * 0.15); - - for (var i in foundations) { - var target = foundations[i]; - // Removed: sometimes the AI would not notice it has empty unbuilt fields - //if (target._template.BuildRestrictions.Category === "Field") - // continue; // we do not build fields - - var assigned = gameState.getOwnEntitiesByMetadata("target-foundation", target).length; - - var targetNB = this.targetNumBuilders; - if (target.hasClass("CivCentre") || target.buildTime() > 150 || target.hasClass("House")) - targetNB *= 2; - - if (assigned < targetNB) { - if (builderWorkers.length + addedWorkers < maxTotalBuilders) { - - var addedToThis = 0; - - var idleBuilders = builderWorkers.filter(Filters.isIdle()); - idleBuilders.forEach(function(ent) { - if (ent.position() && SquareVectorDistance(ent.position(), target.position()) < 10000 && assigned + addedToThis < targetNB) - { - addedWorkers++; - addedToThis++; - ent.setMetadata(PlayerID, "target-foundation", target); - } - }); - if (assigned + addedToThis < targetNB) - { - var nonBuilderWorkers = workers.filter(function(ent) { return (ent.getMetadata(PlayerID, "subrole") !== "builder" && ent.position() !== undefined); }); - var nearestNonBuilders = nonBuilderWorkers.filterNearest(target.position(), targetNB - assigned - addedToThis); - nearestNonBuilders.forEach(function(ent) { - addedWorkers++; - addedToThis++; - ent.stopMoving(); - ent.setMetadata(PlayerID, "subrole", "builder"); - ent.setMetadata(PlayerID, "target-foundation", target); - }); - } - } - } - } - // don't repair if we're still under attack, unless it's like a vital (civcentre or wall) building that's getting destroyed. - for (var i in damagedBuildings) { - var target = damagedBuildings[i]; - if (gameState.defcon() < 5) { - if (target.healthLevel() > 0.5 || !target.hasClass("CivCentre") || !target.hasClass("StoneWall")) { - continue; - } - } else if (noRepair && !target.hasClass("CivCentre")) - continue; - - var territory = Map.createTerritoryMap(gameState); - if (territory.getOwner(target.position()) !== PlayerID || territory.getOwner([target.position()[0] + 5, target.position()[1]]) !== PlayerID) - continue; - - var assigned = gameState.getOwnEntitiesByMetadata("target-foundation", target).length; - if (assigned < this.targetNumBuilders/3) { - if (builderWorkers.length + addedWorkers < this.targetNumBuilders*2) { - - var nonBuilderWorkers = workers.filter(function(ent) { return (ent.getMetadata(PlayerID, "subrole") !== "builder" && ent.position() !== undefined); }); - if (gameState.defcon() < 5) - nonBuilderWorkers = workers.filter(function(ent) { return (ent.getMetadata(PlayerID, "subrole") !== "builder" && ent.hasClass("Female") && ent.position() !== undefined); }); - var nearestNonBuilders = nonBuilderWorkers.filterNearest(target.position(), this.targetNumBuilders/3 - assigned); - - nearestNonBuilders.forEach(function(ent) { - ent.stopMoving(); - addedWorkers++; - ent.setMetadata(PlayerID, "subrole", "builder"); - ent.setMetadata(PlayerID, "target-foundation", target); - }); - } - } - } -}; - -EconomyManager.prototype.buildMoreFields = function(gameState, queues) { - if (this.farmingFields === true) { - var farms = gameState.getOwnEntitiesByType(gameState.applyCiv("structures/{civ}_field")); - var numFarms = 0; - farms.forEach(function (field) { - if (field.resourceSupplyAmount() > 400) - numFarms++; - }); - numFarms += gameState.countEntitiesByType(gameState.applyCiv("foundation|structures/{civ}_field")) - numFarms += queues.field.countTotalQueuedUnits(); - - if (numFarms < this.targetNumFields) - queues.field.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_field")); - } else { - var foodAmount = 0; - gameState.getOwnDropsites("food").forEach( function (ent) { //}){ - if (ent.getMetadata(PlayerID, "resource-quantity-food") != undefined) { - foodAmount += ent.getMetadata(PlayerID, "resource-quantity-food"); - } else { - foodAmount = 500; // wait till we initialize - } - }); - if (foodAmount < 500) - this.farmingFields = true; - } -}; - -// If all the CC's are destroyed then build a new one -EconomyManager.prototype.buildNewCC= function(gameState, queues) { - var numCCs = gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_civil_centre")); - numCCs += queues.civilCentre.totalLength(); - - // no use trying to lay foundations that will be destroyed - if (gameState.defcon() > 2) - for ( var i = numCCs; i < 1; i++) { - gameState.ai.queueManager.clear(); - this.baseNeed["food"] = 0; - this.baseNeed["wood"] = 50; - this.baseNeed["stone"] = 50; - this.baseNeed["metal"] = 50; - queues.civilCentre.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_civil_centre")); - } - return (gameState.countEntitiesByType(gameState.applyCiv("structures/{civ}_civil_centre")) == 0 && gameState.currentPhase() > 1); -}; - -// TODO: make it regularly update stone+metal mines and their resource levels. -// creates and maintains a map of unused resource density -// this also takes dropsites into account. -// resources that are "part" of a dropsite are not counted. -EconomyManager.prototype.updateResourceMaps = function(gameState, events) { - - // By how much to divide the resource amount for plotting. - var decreaseFactor = {'wood': 50.0, 'stone': 90.0, 'metal': 90.0, 'food': 40.0}; - // This is the maximum radius of the influence - var dpRadius = 10; - var radius = {'wood':10.0, 'stone': 24.0, 'metal': 24.0, 'food': 24.0}; - - // smallRadius is the distance necessary to mark a resource as linked to a dropsite. - var smallRadius = { 'food':90*90,'wood':55*55,'stone':70*70,'metal':70*70 }; - // bigRadius is the distance for a weak link (resources are considered when building other dropsites) - // and their resource amount is divided by 3 when checking for dropsite resource level. - var bigRadius = { 'food':100*100,'wood':100*100,'stone':140*140,'metal':140*140 }; - - var self = this; - - for (var resource in radius){ - // if there is no resourceMap create one with an influence for everything with that resource - if (! this.resourceMaps[resource]){ - // We're creting them 8-bit. Things could go above 255 if there are really tons of resources - // But at that point the precision is not really important anyway. And it saves memory. - this.resourceMaps[resource] = new Map(gameState, new Uint8Array(gameState.getMap().data.length)); - this.resourceMaps[resource].setMaxVal(255); - this.CCResourceMaps[resource] = new Map(gameState, new Uint8Array(gameState.getMap().data.length)); - this.CCResourceMaps[resource].setMaxVal(255); - } - } - - var needUpdate = {}; - - // Look for destroy events and subtract the entities original influence from the resourceMap - // also look for dropsite destruction and add the associated entities (along with unmarking them) - for (var key in events) { - var e = events[key]; - if (e.type === "Destroy") { - - if (e.msg.entityObj){ - var ent = e.msg.entityObj; - if (ent && ent.position() && ent.resourceSupplyType() && ent.resourceSupplyType().generic !== "treasure") { - if (e.msg.metadata[PlayerID] && !e.msg.metadata[PlayerID]["linked-dropsite"]) { - var resource = ent.resourceSupplyType().generic; - var x = Math.round(ent.position()[0] / gameState.cellSize); - var z = Math.round(ent.position()[1] / gameState.cellSize); - var strength = Math.round(ent.resourceSupplyMax()/decreaseFactor[resource]); - - if (resource === "wood" || resource === "food") - { - this.resourceMaps[resource].addInfluence(x, z, 2, 5,'constant'); - this.resourceMaps[resource].addInfluence(x, z, 10.0, -strength,'constant'); - this.CCResourceMaps[resource].addInfluence(x, z, 15, -strength/2.0,'constant'); - } else if (resource === "stone" || resource === "metal") - { - this.resourceMaps[resource].addInfluence(x, z, 8, 50); - this.resourceMaps[resource].addInfluence(x, z, 12.0, -strength/1.5); - this.resourceMaps[resource].addInfluence(x, z, 12.0, -strength/2.0,'constant'); - this.CCResourceMaps[resource].addInfluence(x, z, 30, -strength,'constant'); - } - } - } - if (ent && ent.owner() == PlayerID && ent.resourceDropsiteTypes() !== undefined) { - var resources = ent.resourceDropsiteTypes(); - for (var i in resources) { - var resource = resources[i]; - // loop through all dropsites to see if the resources of his entity collection could - // be taken over by another dropsite - var dropsites = gameState.getOwnDropsites(resource); - var metadata = e.msg.metadata[PlayerID]; - - // can happen if it's destroyed before we've initialised it. - if (!metadata || !metadata["linked-resources-" + resource]) - break; - metadata["linked-resources-" + resource].filter( function (supply) { //}){ - var takenOver = false; - dropsites.forEach( function (otherDropsite) { //}) { - if (!otherDropsite.position() || otherDropsite.id() == ent.id()) - return; - var distance = SquareVectorDistance(supply.position(), otherDropsite.position()); - if (supply.getMetadata(PlayerID, "linked-dropsite") == undefined || supply.getMetadata(PlayerID, "linked-dropsite-dist") > distance) { - if (distance < bigRadius[resource]) { - supply.setMetadata(PlayerID, "linked-dropsite", otherDropsite.id() ); - supply.setMetadata(PlayerID, "linked-dropsite-dist", +distance); - if (distance < smallRadius[resource]) { - takenOver = true; - supply.setMetadata(PlayerID, "linked-dropsite-nearby", true ); - } else { - supply.setMetadata(PlayerID, "linked-dropsite-nearby", false ); - } - } - } - }); - if (!takenOver) { - var x = Math.round(supply.position()[0] / gameState.cellSize); - var z = Math.round(supply.position()[1] / gameState.cellSize); - var strength = Math.round(supply.resourceSupplyMax()/decreaseFactor[resource]); - if (resource === "wood" || resource === "food") - { - self.CCResourceMaps[resource].addInfluence(x, z, 15, strength/2.0,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 10.0, strength,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 2, -5,'constant'); - } else if (resource === "stone" || resource === "metal") - { - self.CCResourceMaps[resource].addInfluence(x, z, 30, strength,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 12.0, strength/1.5); - self.resourceMaps[resource].addInfluence(x, z, 12.0, strength/2.0,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 8, -50); - } - } - }); - needUpdate[resource] = true; - } - } - } - } else if (e.type === "Create") { - if (e.msg.entity){ - var ent = gameState.getEntityById(e.msg.entity); - if (ent && ent.position() && ent.resourceSupplyType() && ent.resourceSupplyType().generic !== "treasure"){ - var resource = ent.resourceSupplyType().generic; - var addToMap = true; - var dropsites = gameState.getOwnDropsites(resource); - dropsites.forEach( function (otherDropsite) { //}) { - if (!otherDropsite.position()) - return; - var distance = SquareVectorDistance(ent.position(), otherDropsite.position()); - if (ent.getMetadata(PlayerID, "linked-dropsite") == undefined || ent.getMetadata(PlayerID, "linked-dropsite-dist") > distance) { - if (distance < bigRadius[resource]) { - if (distance < smallRadius[resource]) { - if (ent.getMetadata(PlayerID, "linked-dropsite") == undefined) - addToMap = false; - ent.setMetadata(PlayerID, "linked-dropsite-nearby", true ); - } else { - ent.setMetadata(PlayerID, "linked-dropsite-nearby", false ); - } - ent.setMetadata(PlayerID, "linked-dropsite", otherDropsite.id() ); - ent.setMetadata(PlayerID, "linked-dropsite-dist", +distance); - } - } - }); - if (addToMap) { - var x = Math.round(ent.position()[0] / gameState.cellSize); - var z = Math.round(ent.position()[1] / gameState.cellSize); - var strength = Math.round(ent.resourceSupplyMax()/decreaseFactor[resource]); - if (resource === "wood" || resource === "food") - { - this.CCResourceMaps[resource].addInfluence(x, z, 15, strength/2.0,'constant'); - this.resourceMaps[resource].addInfluence(x, z, 10.0, strength,'constant'); - this.resourceMaps[resource].addInfluence(x, z, 2, -5,'constant'); - } else if (resource === "stone" || resource === "metal") - { - this.CCResourceMaps[resource].addInfluence(x, z, 30, strength,'constant'); - this.resourceMaps[resource].addInfluence(x, z, 12.0, strength/1.5); - this.resourceMaps[resource].addInfluence(x, z, 12.0, strength/2.0,'constant'); - this.resourceMaps[resource].addInfluence(x, z, 8, -50); - } - } - } else if (ent && ent.position() && ent.resourceDropsiteTypes) { - var resources = ent.resourceDropsiteTypes(); - for (var i in resources) { - var resource = resources[i]; - needUpdate[resource] = true; - } - } - } - } - } - - for (var i in needUpdate) - { - this.updateNearbyResources(gameState,i); - this.updateResourceConcentrations(gameState,i); - } - /* - if (gameState.ai.playedTurn % 20 === 1) - { - this.resourceMaps['wood'].dumpIm("s_tree_density_ " + gameState.getTimeElapsed() +".png", 255); - this.resourceMaps['stone'].dumpIm("stone_density_ " + gameState.getTimeElapsed() +".png", 255); - this.resourceMaps['metal'].dumpIm("s_metal_density_ " + gameState.getTimeElapsed() +".png", 255); - this.CCResourceMaps['wood'].dumpIm("CC_TREE " + gameState.getTimeElapsed() +".png", 255); - this.CCResourceMaps['stone'].dumpIm("CC_STONE " + gameState.getTimeElapsed() +".png", 255); - this.CCResourceMaps['metal'].dumpIm("CC_METAL " + gameState.getTimeElapsed() +".png", 255); - }*/ -}; - -// Returns the position of the best place to build a new dropsite for the specified resource -EconomyManager.prototype.getBestResourceBuildSpot = function(gameState, resource){ - - // This builds a map. The procedure is fairly simple. It adds the resource maps - // (which are dynamically updated and are made so that they will facilitate DP placement) - // Then checks for a good spot in the territory. If none, and town/city phase, checks outside - // The AI will currently not build a CC if it wouldn't connect with an existing CC. - - var friendlyTiles = new Map(gameState); - var territory = Map.createTerritoryMap(gameState); - - var obstructions = Map.createObstructionMap(gameState); - obstructions.expandInfluences(); - - var myDropsites = gameState.getOwnEntities().filter(Filters.isDropsite(resource)); - - for (var j = 0; j < friendlyTiles.length; ++j) - { - friendlyTiles.map[j] += this.resourceMaps[resource].map[j] * 1.5; - - // first pass: we remove anything not in our territory - // needed because the obstruction map is by default set true for BuildNeutral - if (territory.getOwnerIndex(j) !== PlayerID) - { - friendlyTiles.map[j] = 0; - continue; - } - // only add where the map is currently not null, ie in our territory and some "Resource" would be close. - // This makes the placement go from "OK" to "human-like". - for (var i in this.resourceMaps) - if (friendlyTiles.map[j] !== 0 && i !== "food") - friendlyTiles.map[j] += this.resourceMaps[i].map[j]; - - // mark as unbuildable if we're realy close from another dropsite. Might avoid rare bugs. - // TODO: should mostly examine why those happen, check top post page 4 of the "WIP new API" topic started by Wraitii. - for (var i in myDropsites._entities) - { - var pos = [j%friendlyTiles.width, Math.floor(j/friendlyTiles.width)]; - if (myDropsites._entities[i].position() && SquareVectorDistance(friendlyTiles.gamePosToMapPos(myDropsites._entities[i].position()), pos) < 100) - friendlyTiles.map[j] = 0; - } - } - - //friendlyTiles.dumpIm(gameState.getTimeElapsed() + "_" + resource + "_dp_placement_base.png", 255); - - var isCivilCenter = false; - var best = friendlyTiles.findBestTile(2, obstructions); // try to find a spot to place a DP. - var bestIdx = best[0]; - - //debug ("Have " + best[1] + " for " + resource); - - // 75, from empirical values, seems reasonable. - if (best[1] <= 75 && gameState.currentPhase() >= 2) - { - // restart the search this time for a CC - friendlyTiles = new Map(gameState); - - var ents = gameState.getOwnEntities().filter(Filters.byClass("CivCentre")); - var eEnts = gameState.getEnemyEntities().filter(Filters.byClass("CivCentre")); - - // This uses a different resource maps,where the point is basically to try to have as many resources as possible in the CC's territory. - for (var j = 0; j < friendlyTiles.length; ++j) - { - // We check for our other CCs: the distance must not be too big. Anything bigger will result in scrapping. - // This ensures territorial continuity. - // TODO: maybe whenever I get around to implement multi-base support (details below, requires being part of the team. If you're not, ask wraitii directly by PM). - // (see www.wildfiregames.com/forum/index.php?showtopic=16702&#entry255631 ) - var mindist = 7101; - var pos = [j%friendlyTiles.width, Math.floor(j/friendlyTiles.width)]; - ents.forEach( function (cc) { - var dist = SquareVectorDistance(friendlyTiles.gamePosToMapPos(cc.position()),pos); - if (dist < mindist) - mindist = dist; - }); - if (mindist > 7100) - { - friendlyTiles.map[j] = 0; - continue; - } - // Checking for enemy CCs - mindist = 7101; - eEnts.forEach( function (cc) { - var dist = SquareVectorDistance(friendlyTiles.gamePosToMapPos(cc.position()),pos); - if (dist < mindist) - mindist = dist; - }); - if (mindist < 3500) // cannot build too close to each other. - { - friendlyTiles.map[j] = 0; - continue; - } - - // mark as unbuildable if we're realy close from another dropsite. Might avoid rare bugs. - // TODO: should mostly examine why those happen, check top post page 4 of the "WIP new API" topic started by Wraitii. - for (var i in myDropsites._entities) - { - var pos = [j%friendlyTiles.width, Math.floor(j/friendlyTiles.width)]; - if (myDropsites._entities[i].position() && SquareVectorDistance(friendlyTiles.gamePosToMapPos(myDropsites._entities[i].position()), pos) < 100) - friendlyTiles.map[j] = 0; - } - - friendlyTiles.map[j] += this.CCResourceMaps[resource].map[j] * 1.5; - - for (var i in this.CCResourceMaps) - if (friendlyTiles.map[j] !== 0 && i !== "food") - friendlyTiles.map[j] += this.CCResourceMaps[i].map[j]; - } - - //friendlyTiles.dumpIm(gameState.getTimeElapsed() + "_" + resource + "_cc_placement_base.png", 5000); - - best = friendlyTiles.findBestTile(4, obstructions); - bestIdx = best[0]; - isCivilCenter = true; - } else { - //friendlyTiles.dumpIm(gameState.getTimeElapsed() + "_" + resource + "_density_fade_final2.png", 5000); - } - - // tell the dropsite builder we haven't found anything satisfactory. - if (best[1] < 60) - return [false, [-1,0]]; - - var x = ((bestIdx % friendlyTiles.width) + 0.5) * gameState.cellSize; - var z = (Math.floor(bestIdx / friendlyTiles.width) + 0.5) * gameState.cellSize; - - return [isCivilCenter, [x,z]]; -}; - -EconomyManager.prototype.updateResourceConcentrations = function(gameState, resource){ - var self = this; - gameState.getOwnDropsites(resource).forEach(function(dropsite) { //}){ - var amount = 0; - var amountFar = 0; - // loop through the entity collections of linked-resources, if there is one. - if (dropsite.getMetadata(PlayerID, "linked-resources-" + resource) == undefined) - return; - dropsite.getMetadata(PlayerID, "linked-resources-" + resource).forEach(function(supply){ //}){ - if (supply.isFull() === true || supply.getMetadata(PlayerID, "inaccessible") == true) - return; - - if (supply.getMetadata(PlayerID, "linked-dropsite-nearby") == true) - amount += supply.resourceSupplyAmount(); - else - amountFar += supply.resourceSupplyAmount(); - supply.setMetadata(PlayerID, "dp-update-value",supply.resourceSupplyAmount()); - }); - dropsite.setMetadata(PlayerID, "resource-quantity-" + resource, amount); - dropsite.setMetadata(PlayerID, "resource-quantity-far-" + resource, amountFar); - //debug (dropsite + " has " + amount + ", " + amountFar +" of " +resource); - }); -}; - -// Stores lists of nearby resources -// This is done only once per dropsite. -EconomyManager.prototype.updateNearbyResources = function(gameState,resource){ - var self = this; - var resources = ["food", "wood", "stone", "metal"]; - var resourceSupplies; - - // By how much to divide the resource amount for plotting. - var decreaseFactor = {'wood': 50.0, 'stone': 90.0, 'metal': 90.0, 'food': 40.0}; - // This is the maximum radius of the influence - var radius = {'wood':10.0, 'stone': 24.0, 'metal': 24.0, 'food': 24.0}; - - // smallRadius is the distance necessary to mark a resource as linked to a dropsite. - var smallRadius = { 'food':90*90,'wood':55*55,'stone':70*70,'metal':70*70 }; - // bigRadius is the distance for a weak link (resources are considered when building other dropsites) - // and their resource amount is divided by 3 when checking for dropsite resource level. - var bigRadius = { 'food':100*100,'wood':100*100,'stone':140*140,'metal':140*140 }; - - gameState.getOwnDropsites(resource).forEach(function(ent) { //}){ - - if (ent.getMetadata(PlayerID, "nearby-resources-" + resource) === undefined){ - // let's defined the entity collections (by metadata) - gameState.getResourceSupplies(resource).filter( function (supply) { //}){ - if (!supply.position() || !ent.position()) - return; - var distance = SquareVectorDistance(supply.position(), ent.position()); - // if we're close than the current linked-dropsite, or if it's not linked - // TODO: change when actualy resource counting is implemented. - - if (supply.getMetadata(PlayerID, "linked-dropsite") == undefined || supply.getMetadata(PlayerID, "linked-dropsite-dist") > distance) { - if (distance < bigRadius[resource]) { - if (distance < smallRadius[resource]) { - // it's new to the game, remove it from the resource maps - if ((supply.getMetadata(PlayerID, "linked-dropsite") == undefined || supply.getMetadata(PlayerID, "linked-dropsite-nearby") == false) - && supply.resourceSupplyType().generic !== "treasure") { - var x = Math.round(supply.position()[0] / gameState.cellSize); - var z = Math.round(supply.position()[1] / gameState.cellSize); - var strength = Math.round(supply.resourceSupplyMax()/decreaseFactor[resource]); - if (resource === "wood" || resource === "food") - { - self.CCResourceMaps[resource].addInfluence(x, z, 15, -strength/2.0,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 2, 5,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 10.0, -strength,'constant'); - } else if (resource === "stone" || resource === "metal") - { - self.CCResourceMaps[resource].addInfluence(x, z, 30, -strength,'constant'); - self.resourceMaps[resource].addInfluence(x, z, 8, 50); - self.resourceMaps[resource].addInfluence(x, z, 12.0, -strength/1.5); - self.resourceMaps[resource].addInfluence(x, z, 12.0, -strength/2.0,'constant'); - } - } - supply.setMetadata(PlayerID, "linked-dropsite-nearby", true ); - } else { - supply.setMetadata(PlayerID, "linked-dropsite-nearby", false ); - } - supply.setMetadata(PlayerID, "linked-dropsite", ent.id() ); - supply.setMetadata(PlayerID, "linked-dropsite-dist", +distance); - } - } - }); - // This one is both for the nearby and the linked - var filter = Filters.byMetadata(PlayerID, "linked-dropsite", ent.id()); - var collection = gameState.getResourceSupplies(resource).filter(filter); - collection.registerUpdates(); - ent.setMetadata(PlayerID, "linked-resources-" + resource, collection); - - filter = Filters.byMetadata(PlayerID, "linked-dropsite-nearby",true); - var collection2 = collection.filter(filter); - collection2.registerUpdates(); - ent.setMetadata(PlayerID, "nearby-resources-" + resource, collection2); - - } - - - - /*// Make resources glow wildly - if (resource == "food"){ - ent.getMetadata(PlayerID, "linked-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [1,0,0]}); - }); - ent.getMetadata(PlayerID, "nearby-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [10,0,0]}); - }); - } - if (resource == "wood"){ - ent.getMetadata(PlayerID, "linked-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,1,0]}); - }); - ent.getMetadata(PlayerID, "nearby-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,10,0]}); - }); - } - if (resource == "metal"){ - ent.getMetadata(PlayerID, "linked-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,0,1]}); - }); - ent.getMetadata(PlayerID, "nearby-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,0,10]}); - }); - } - if (resource == "stone"){ - ent.getMetadata(PlayerID, "linked-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,0.5,1]}); - }); - ent.getMetadata(PlayerID, "nearby-resources-" + resource).forEach(function(ent){ - Engine.PostCommand({"type": "set-shading-color", "entities": [ent.id()], "rgb": [0,5,10]}); - }); - }*/ - }); -}; - -//return the number of resource dropsites with an acceptable amount of the resource nearby -EconomyManager.prototype.checkResourceConcentrations = function(gameState, resource){ - //TODO: make these values adaptive - var requiredInfluence = {"wood": 2500, "stone": 600, "metal": 600}; - var count = 0; - gameState.getOwnDropsites(resource).forEach(function(ent) { //}){ - if (ent.getMetadata(PlayerID, "resource-quantity-" + resource) == undefined || typeof(ent.getMetadata(PlayerID, "resource-quantity-" + resource)) !== "number") { - count++; // assume it's OK if we don't know. - return; - } - var quantity = +ent.getMetadata(PlayerID, "resource-quantity-" + resource); - var quantityFar = +ent.getMetadata(PlayerID, "resource-quantity-far-" + resource); - - if (quantity >= requiredInfluence[resource]) { - count++; - } else if (quantity + quantityFar >= requiredInfluence[resource]) { - count += 0.5 + (quantity/requiredInfluence[resource])/2; - } else { - count += ((quantity + quantityFar)/requiredInfluence[resource])/2; - } - }); - return count; -}; - -EconomyManager.prototype.buildTemple = function(gameState, queues){ - if (gameState.currentPhase() >= 2 ) { - if (queues.economicBuilding.countTotalQueuedUnits() === 0 && - gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_temple")) === 0){ - queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_temple")); - } - } -}; - -EconomyManager.prototype.buildMarket = function(gameState, queues){ - if (this.numWorkers > 50 && gameState.currentPhase() >= 2 ) { - if (queues.economicBuilding.countTotalQueuedUnitsWithClass("BarterMarket") === 0 && - gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_market")) === 0){ - //only ever build one storehouse/CC/market at a time - queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_market")); - } - } -}; - -// Build a farmstead to go to town phase faster and prepare for research. Only really active on higher diff mode. -EconomyManager.prototype.buildFarmstead = function(gameState, queues){ - if (gameState.getTimeElapsed() > this.farmsteadStartTime) { - if (queues.economicBuilding.countTotalQueuedUnitsWithClass("DropsiteFood") === 0 && - gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_farmstead")) === 0){ - //only ever build one storehouse/CC/market at a time - queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_farmstead")); - } - } -}; - -EconomyManager.prototype.buildDock = function(gameState, queues){ - if (!gameState.ai.waterMap || this.dockFailed) - return; - if (gameState.getTimeElapsed() > this.dockStartTime) { - if (queues.economicBuilding.countTotalQueuedUnitsWithClass("NavalMarket") === 0 && - gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_dock")) === 0){ - if (gameState.civ() == "cart" && gameState.currentPhase() > 1) - queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_super_dock")); - else if (gameState.civ() !== "cart") - queues.economicBuilding.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_dock")); - } - } -}; - -// if Aegis has resources it doesn't need, it'll try to barter it for resources it needs -// once per turn because the info doesn't update between a turn and I don't want to fix it. -// Not sure how efficient it is but it seems to be sane, at least. -EconomyManager.prototype.tryBartering = function(gameState){ - var done = false; - if (gameState.countEntitiesByType(gameState.applyCiv("structures/{civ}_market")) >= 1) { - - var needs = gameState.ai.queueManager.futureNeeds(gameState,false); - var ress = gameState.ai.queueManager.getAvailableResources(gameState); - - for (var sell in needs) { - for (var buy in needs) { - if (!done && buy != sell && needs[sell] <= 0 && ress[sell] > 400) { // if we don't need it and have a buffer - if ( (ress[buy] < 400) || needs[buy] > 0) { // if we need that other resource/ have too little of it - var markets = gameState.getOwnEntitiesByType(gameState.applyCiv("structures/{civ}_market")).toEntityArray(); - markets[0].barter(buy,sell,100); - //debug ("bartered " +sell +" for " + buy + ", value 100"); - done = true; - } - } - } - } - } -}; - -// TODO: while the algorithm for dropsite placement is quite good -// This is bad. Choosing when to place dropsites should be improved. -EconomyManager.prototype.buildDropsites = function(gameState, queues){ - if ( queues.dropsites.totalLength() === 0 && gameState.countFoundationsWithType(gameState.applyCiv("structures/{civ}_storehouse")) === 0 && - gameState.countFoundationsWithType(gameState.applyCiv("structures/{civ}_civil_centre")) === 0){ - //only ever build one storehouse/CC/market at a time - if (gameState.getTimeElapsed() > 30 * 1000){ - var built = false; - for (var resource in this.dropsiteNumbers){ - if (this.checkResourceConcentrations(gameState, resource) < this.dropsiteNumbers[resource]){ - var spot = this.getBestResourceBuildSpot(gameState, resource); - if (spot[1][0] === -1) - break; - if (spot[0] === true){ - queues.dropsites.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_civil_centre", spot[1])); - } else { - queues.dropsites.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_storehouse", spot[1])); - } - built = true; - break; - } - } - if (!built) - for (var resource in this.dropsiteNumbers){ - if (this.checkResourceConcentrations(gameState, resource) < Math.ceil(this.dropsiteNumbers[resource])){ - var spot = this.getBestResourceBuildSpot(gameState, resource); - if (spot[1][0] === -1) - break; - if (spot[0] === true){ - queues.dropsites.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_civil_centre", spot[1])); - } else { - queues.dropsites.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_storehouse", spot[1])); - } - built = true; - break; - } - } - } - } -}; -// build more houses if needed. -// kinda ugly, lots of special cases to both build enough houses but not tooo many… -EconomyManager.prototype.buildMoreHouses = function(gameState, queues) { - if ( (this.fastStart && gameState.getTimeElapsed() < 10000) || gameState.getTimeElapsed() < 35000) - return; - - // TODO: temporary 'remaining population space' based check, need to do - // predictive in future - if (gameState.getPopulationLimit() - gameState.getPopulation() < 20 - && gameState.getPopulationLimit() < gameState.getPopulationMax()) { - - var numConstructing = gameState.countEntitiesByType(gameState.applyCiv("foundation|structures/{civ}_house")); - var numPlanned = queues.house.totalLength(); - - var additional = 0; - - if (gameState.currentPhase() > 1) - { - if (gameState.civ() == "gaul" || gameState.civ() == "brit" || gameState.civ() == "iber") - additional = Math.ceil((30 - (gameState.getPopulationLimit() - gameState.getPopulation())) / 5) - numConstructing - numPlanned; - else - additional = Math.ceil((30 - (gameState.getPopulationLimit() - gameState.getPopulation())) / 10) - numConstructing - numPlanned; - } else { - if (gameState.civ() == "gaul" || gameState.civ() == "brit" || gameState.civ() == "iber") - additional = Math.ceil((20 - (gameState.getPopulationLimit() - gameState.getPopulation())) / 5) - numConstructing - numPlanned; - else - additional = Math.ceil((20 - (gameState.getPopulationLimit() - gameState.getPopulation())) / 10) - numConstructing - numPlanned; - } - if (Config.difficulty === 3) - additional *= 2; // we don't build enough otherwise. - - for ( var i = 0; i < additional; i++) { - queues.house.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_house")); - } - } -}; - -// Change our priorities based on our gathering statistics. -// TODO: this is currently unused, I'm not sure how sensible it is -// This should probably be scrapped in favor of improving the queueManager's detection -// of future needs. -EconomyManager.prototype.rePrioritize = function(gameState) { - var statG = gameState.playerData.statistics.resourcesGathered; - var statU = gameState.playerData.statistics.resourcesUsed; - var resources = ["food", "wood", "stone", "metal"]; - for each (var ress in resources) - { - var eff = (statG[ress]-this.lastStatG[ress]) / (statU[ress]-this.lastStatU[ress]); - - if ((statU[ress]-this.lastStatU[ress]) === 0) - continue; - - if (eff < 0.6) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] + 10); - else if (eff < 0.7) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] + 6); - else if (eff < 0.8) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] + 4); - else if (eff > 1.2) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] - 10 ); - else if (eff > 1.1) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] - 8 ); - else if (eff > 1.0) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] - 5 ); - else if (eff > 0.9) - this.baseNeed[ress] = Math.max(10, this.baseNeed[ress] - 3 ); - //debug (ress + " Eff: " + eff); - } - - //debug ("Stats "); - //debug ("Food: " + this.baseNeed["food"]); - //debug ("Wood: " + this.baseNeed["wood"]); - //debug ("Stone: " + this.baseNeed["stone"]); - //debug ("Metal: " + this.baseNeed["metal"]); - - this.lastStatG = statG; - this.lastStatU = statU; -}; - -EconomyManager.prototype.update = function(gameState, queues, events) { - Engine.ProfileStart("economy update"); - - this.reassignRolelessUnits(gameState); - - // run a particular BO if we have no CC as this is highest priority - if (this.buildNewCC(gameState,queues)) - { - Engine.ProfileStart("Update Resource Maps and Concentrations"); - this.updateResourceMaps(gameState, events); - - if (gameState.ai.playedTurn % 2 === 0) { - var resources = ["food", "wood", "stone", "metal"]; - this.updateNearbyResources(gameState, resources[(gameState.ai.playedTurn % 8)/2]); - } else if (gameState.ai.playedTurn % 2 === 1) { - var resources = ["food", "wood", "stone", "metal"]; - this.updateResourceConcentrations(gameState, resources[((gameState.ai.playedTurn+1) % 8)/2]); - } - Engine.ProfileStop(); - - if (Config.difficulty !== 0) - this.tryBartering(gameState); - - if (gameState.ai.playedTurn % 20 === 0){ - this.setWorkersIdleByPriority(gameState); - } else { - Engine.ProfileStart("Reassign Idle Workers"); - this.reassignIdleWorkers(gameState); - Engine.ProfileStop(); - - Engine.ProfileStart("Assign builders"); - this.assignToFoundations(gameState, false); - Engine.ProfileStop(); - } - - Engine.ProfileStart("Run Workers"); - gameState.getOwnEntitiesByRole("worker").forEach(function(ent){ - if (!ent.getMetadata(PlayerID, "worker-object")){ - ent.setMetadata(PlayerID, "worker-object", new Worker(ent)); - } - ent.getMetadata(PlayerID, "worker-object").update(gameState); - }); - - Engine.ProfileStop(); - Engine.ProfileStop(); - return; - } - - // Normal run - - this.numWorkers = gameState.getOwnEntitiesByRole("worker").filter(Filters.not(Filters.byHasMetadata(PlayerID,"plan"))).length; - - // this function also deals with a few things that are number-of-workers related - Engine.ProfileStart("Train workers and build farms, houses. Research techs."); - this.trainMoreWorkers(gameState, queues); - - if ((gameState.ai.playedTurn+2) % 20 === 0 && gameState.getTimeElapsed() > this.techStartTime) - this.tryResearchTechs(gameState,queues); - - if ((gameState.ai.playedTurn+1) % 3 === 0) - this.buildMoreFields(gameState,queues); - - this.buildMoreHouses(gameState,queues); - - Engine.ProfileStop(); - - //Later in the game we want to build stuff faster. - if (gameState.getTimeElapsed() > 15*60*1000) { - this.targetNumBuilders = Config.Economy.targetNumBuilders*4; - }else if (gameState.getTimeElapsed() > 5*60*1000) { - this.targetNumBuilders = Config.Economy.targetNumBuilders*2; - } else { - this.targetNumBuilders = Config.Economy.targetNumBuilders; - } - if (gameState.currentPhase() == 1 && !this.fastStart) - this.femaleRatio = Config.Economy.femaleRatio * 1.3; - else - this.femaleRatio = Config.Economy.femaleRatio; - - if (gameState.getTimeElapsed() > 600000 && this.numWorkers < 50 && Config.difficulty > 0) - { - gameState.ai.queueManager.changePriority("villager", 80); - gameState.ai.queueManager.changePriority("citizenSoldier", 70); - } else if (gameState.getTimeElapsed() > 600000 && this.numWorkers > 80 && Config.difficulty > 0 - && gameState.ai.queueManager.priorities["villager"] == 80) - { - gameState.ai.queueManager.changePriority("villager", Config.priorities.villager); - gameState.ai.queueManager.changePriority("citizenSoldier", Config.priorities.citizenSoldier); - } - - if (this.baseNeed["food"] === 300 && (this.numWorkers >= 15 || gameState.isResearching("phase_town"))) { - this.baseNeed["food"] -= 150; - } else if (this.baseNeed["metal"] === 0 && (gameState.currentPhase() === 2 || gameState.isResearching("phase_town"))) { - // for the little while in town phase, we want a little more more stone/wood than usual - this.baseNeed["food"] = 100; - this.baseNeed["wood"] = 100; - this.baseNeed["stone"] = 80; - this.baseNeed["metal"] = 50; - if (gameState.civ() == "maur" || gameState.civ() == "brit" || gameState.civ() == "gaul") - { - this.baseNeed["wood"] = 120; - this.baseNeed["stone"] = 60; - } - } else if (this.baseNeed["stone"] === 80 && (gameState.currentPhase() === 3 || gameState.isResearching("phase_city_generic")) ) - { - // switch back to less stone but push metal. - this.baseNeed["food"] = 80; - this.baseNeed["wood"] = 80; - this.baseNeed["stone"] = 45; - this.baseNeed["metal"] = 65; - } - //if (Config.difficulty === 2 && gameState.getTimeElapsed() > 900000 && gameState.ai.playedTurn % 60 === 10) - // this.rePrioritize(gameState); - - Engine.ProfileStart("Update Resource Maps and Concentrations"); - this.updateResourceMaps(gameState, events); - if (gameState.ai.playedTurn % 2 === 0) { - var resources = ["food", "wood", "stone", "metal"]; - this.updateNearbyResources(gameState, resources[(gameState.ai.playedTurn % 8)/2]); - } else if (gameState.ai.playedTurn % 2 === 1) { - var resources = ["food", "wood", "stone", "metal"]; - this.updateResourceConcentrations(gameState, resources[((gameState.ai.playedTurn+1) % 8)/2]); - } - Engine.ProfileStop(); - - if (gameState.ai.playedTurn % 4 === 0) { - Engine.ProfileStart("Build new Dropsites"); - this.buildDropsites(gameState, queues); - Engine.ProfileStop(); - } - if (Config.difficulty !== 0) - this.tryBartering(gameState); - - this.buildFarmstead(gameState, queues); - this.buildMarket(gameState, queues); - // Deactivated: the temple had no useful purpose for the AI now. - //if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv("structures/{civ}_market")) === 1) - // this.buildTemple(gameState, queues); - this.buildDock(gameState, queues); // not if not a water map. - - if (gameState.ai.playedTurn % 10 === 0){ - this.setWorkersIdleByPriority(gameState); - } - if (gameState.ai.playedTurn % 3 === 1) - { - Engine.ProfileStart("Reassign Idle Workers"); - this.reassignIdleWorkers(gameState); - Engine.ProfileStop(); - } - - // this is pretty slow, run it once in a while - if (gameState.ai.playedTurn % 6 === 1) { - Engine.ProfileStart("Swap Workers"); - var gathererGroups = {}; - gameState.getOwnEntitiesByRole("worker").forEach(function(ent){ - if (ent.hasClass("Cavalry")) - return; - var key = uneval(ent.resourceGatherRates()); - if (!gathererGroups[key]){ - gathererGroups[key] = {"food": [], "wood": [], "metal": [], "stone": []}; - } - if (ent.getMetadata(PlayerID, "gather-type") in gathererGroups[key]){ - gathererGroups[key][ent.getMetadata(PlayerID, "gather-type")].push(ent); - } - }); - for (var i in gathererGroups){ - for (var j in gathererGroups){ - var a = eval(i); - var b = eval(j); - if (a !== undefined && b !== undefined) - if (a["food.grain"]/b["food.grain"] > a["wood.tree"]/b["wood.tree"] && gathererGroups[i]["wood"].length > 0 - && gathererGroups[j]["food"].length > 0){ - for (var k = 0; k < Math.min(gathererGroups[i]["wood"].length, gathererGroups[j]["food"].length); k++){ - gathererGroups[i]["wood"][k].setMetadata(PlayerID, "gather-type", "food"); - gathererGroups[j]["food"][k].setMetadata(PlayerID, "gather-type", "wood"); - } - } - } - } - Engine.ProfileStop(); - } - - Engine.ProfileStart("Assign builders"); - this.assignToFoundations(gameState); - Engine.ProfileStop(); - - // TODO: do this incrementally a la defence.js (Changed slightly to be faster already). - Engine.ProfileStart("Run Workers"); - gameState.getOwnEntitiesByRole("worker").forEach(function(ent){ - if (!ent.getMetadata(PlayerID, "worker-object")) - ent.setMetadata(PlayerID, "worker-object", new Worker(ent)); - if ((ent.id() + gameState.ai.playedTurn) % 3 === 0) // should make it significantly faster without much drawbacks. - ent.getMetadata(PlayerID, "worker-object").update(gameState); - }); - - Engine.ProfileStop(); - Engine.ProfileStop(); -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/economy.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/worker.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/worker.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/worker.js (nonexistent) @@ -1,511 +0,0 @@ -/** - * This class makes a worker do as instructed by the economy manager - */ - -var 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. -}; - -Worker.prototype.update = function(gameState) { - - 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); - - if (subrole === "gatherer") { - if (this.ent.unitAIState().split(".")[1] !== "GATHER" && this.ent.unitAIState().split(".")[1] !== "COMBAT" && this.ent.unitAIState().split(".")[1] !== "RETURNRESOURCE"){ - // TODO: handle combat for hunting animals - 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.startGathering(gameState); - Engine.ProfileStop(); - } else { - // Should deposit resources - Engine.ProfileStart("Return Resources"); - if (!this.returnResources(gameState)) - { - // no dropsite, abandon cargo. - - // if we have a new order - if (this.ent.resourceCarrying()[0].type !== this.ent.getMetadata(PlayerID, "gather-type")) - this.startGathering(gameState); - else { - this.ent.setMetadata(PlayerID, "gather-type",undefined); - this.ent.setMetadata(PlayerID, "subrole", "idle"); - this.ent.stopMoving(); - } - } - Engine.ProfileStop(); - } - this.startApproachingResourceTime = gameState.getTimeElapsed(); - - //Engine.PostCommand({"type": "set-shading-color", "entities": [this.ent.id()], "rgb": [10,0,0]}); - } else if (this.ent.unitAIState().split(".")[1] === "GATHER") { - if (this.unsatisfactoryResource && (this.ent.id() + gameState.ai.playedTurn) % 20 === 0) - { - Engine.ProfileStart("Start Gathering"); - this.startGathering(gameState); - Engine.ProfileStop(); - } - /*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. - 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. - 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 { - this.startApproachingResourceTime = gameState.getTimeElapsed(); - } - } else if(subrole === "builder") { - if (this.ent.unitAIState().split(".")[1] !== "REPAIR"){ - var target = this.ent.getMetadata(PlayerID, "target-foundation"); - if (target.foundationProgress() === undefined && target.needsRepair() == false) - 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]}); - } else if(subrole === "hunter") { - if (!this.ent.resourceCarrying() || this.ent.resourceCarrying().length === 0){ - Engine.ProfileStart("Start Hunting"); - this.startHunting(gameState); - Engine.ProfileStop(); - } - } else { - this.startApproachingResourceTime = gameState.getTimeElapsed(); - } -}; - -Worker.prototype.startGathering = function(gameState){ - var resource = this.ent.getMetadata(PlayerID, "gather-type"); - var ent = this.ent; - - if (!ent.position()){ - // TODO: work out what to do when entity has no position - return; - } - - this.unsatisfactoryResource = false; - - // TODO: this is not necessarily optimal. - - // find closest dropsite which has nearby resources of the correct type - var minDropsiteDist = Math.min(); // set to infinity initially - var nearestResources = undefined; - var nearestDropsite = undefined; - - // first step: count how many dropsites we have that have enough resources "close" to them. - // TODO: this is a huge part of multi-base support. Count only those in the same base as the worker. - var number = 0; - var ourDropsites = gameState.getOwnDropsites(resource); - - if (ourDropsites.length === 0) - { - debug ("We do not have a dropsite for " + resource + ", aborting"); - return; - } - - ourDropsites.forEach(function (dropsite) { - if (dropsite.getMetadata(PlayerID, "linked-resources-" +resource) !== undefined - && dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) !== undefined && dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) > 200) { - number++; - } - }); - - //debug ("Available " +resource + " dropsites: " +ourDropsites.length); - - // Allright second step, if there are any such dropsites, we pick the closest. - // we pick one with a lot of resource, or we pick the only one available (if it's high enough, otherwise we'll see with "far" below). - if (number > 0) - { - ourDropsites.forEach(function (dropsite) { //}){ - if (dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) == undefined) - return; - if (dropsite.position() && (dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) > 700 || (number === 1 && dropsite.getMetadata(PlayerID, "resource-quantity-" +resource) > 200) ) ) { - var dist = SquareVectorDistance(ent.position(), dropsite.position()); - if (dist < minDropsiteDist){ - minDropsiteDist = dist; - nearestResources = dropsite.getMetadata(PlayerID, "linked-resources-" + resource); - nearestDropsite = dropsite; - } - } - }); - } - //debug ("Nearest dropsite: " +nearestDropsite); - - // Now if we have no dropsites, we repeat the process with resources "far" from dropsites but still linked with them. - // I add the "close" value for code sanity. - // Again, we choose a dropsite with a lot of resources left, or we pick the only one available (in this case whatever happens). - if (!nearestResources || nearestResources.length === 0) { - //debug ("here(1)"); - gameState.getOwnDropsites(resource).forEach(function (dropsite){ //}){ - var quantity = dropsite.getMetadata(PlayerID, "resource-quantity-" +resource)+dropsite.getMetadata(PlayerID, "resource-quantity-far-" +resource); - if (dropsite.position() && (quantity) > 700 || number === 1) { - var dist = SquareVectorDistance(ent.position(), dropsite.position()); - if (dist < minDropsiteDist){ - minDropsiteDist = dist; - nearestResources = dropsite.getMetadata(PlayerID, "linked-resources-" + resource); - nearestDropsite = dropsite; - } - } - }); - this.unsatisfactoryResource = true; - //debug ("Nearest dropsite: " +nearestDropsite); - } - // If we still haven't found any fitting dropsite... - // Then we'll just pick any resource, and we'll check for the closest dropsite to that one - if (!nearestResources || nearestResources.length === 0){ - //debug ("No fitting dropsite for " + resource + " found, iterating the map."); - nearestResources = gameState.getResourceSupplies(resource); - this.unsatisfactoryResource = true; - } - - if (nearestResources.length === 0){ - if (resource === "food") - { - if (this.buildAnyField(gameState)) - return; - debug("No " + resource + " found! (1)"); - } - else - debug("No " + resource + " found! (1)"); - return; - } - //debug("Found " + nearestResources.length + "spots for " + resource); - - /*if (!nearestDropsite) { - debug ("No dropsite for " +resource); - return; - }*/ - - var supplies = []; - var nearestSupplyDist = Math.min(); - var nearestSupply = undefined; - - // filter resources - // TODo: add a bonus for resources with a lot of resources left, perhaps, to spread gathering? - nearestResources.forEach(function(supply) { //}){ - - // sanity check, perhaps sheep could be garrisoned? - if (!supply.position()) { - //debug ("noposition"); - return; - } - - if (supply.getMetadata(PlayerID, "inaccessible") === true) { - //debug ("inaccessible"); - return; - } - - if (supply.isFull() === true || (supply.maxGatherers() - supply.resourceSupplyGatherers().length == 0) || - (gameState.turnCache["ressGathererNB"] && gameState.turnCache["ressGathererNB"][supply.id()] - && gameState.turnCache["ressGathererNB"][supply.id()] + supply.resourceSupplyGatherers().length >= supply.maxGatherers())) { - return; - } - - // Don't gather enemy farms - if (!supply.isOwn(PlayerID) && supply.owner() !== 0) { - //debug ("enemy"); - return; - } - - // quickscope accessbility check. - if (!gameState.ai.accessibility.pathAvailable(gameState, ent.position(), supply.position(), true)) { - //debug ("nopath"); - return; - } - // some simple check for chickens: if they're in a square that's inaccessible, we won't gather from them. - if (supply.footprintRadius() < 1) - { - var fakeMap = new Map(gameState,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; - } - } - - // measure the distance to the resource (largely irrelevant) - var dist = SquareVectorDistance(supply.position(), ent.position()); - - if (dist > 4900 && supply.hasClass("Animal")) - return; - - // Add on a factor for the nearest dropsite if one exists - if (nearestDropsite !== undefined ){ - dist += 4*SquareVectorDistance(supply.position(), nearestDropsite.position()); - dist /= 5.0; - } - - var territoryOwner = Map.createTerritoryMap(gameState).getOwner(supply.position()); - if (territoryOwner != PlayerID && territoryOwner != 0) { - dist *= 3.0; - //return; - } - - // Go for treasure as a priority - if (dist < 40000 && supply.resourceSupplyType().generic == "treasure"){ - dist /= 1000; - } - - if (dist < nearestSupplyDist) { - nearestSupplyDist = dist; - nearestSupply = supply; - } - }); - - if (nearestSupply) { - var pos = nearestSupply.position(); - - // find a fitting dropsites in case we haven't already. - if (!nearestDropsite) { - ourDropsites.forEach(function (dropsite){ //}){ - if (dropsite.position()){ - var dist = SquareVectorDistance(pos, dropsite.position()); - if (dist < minDropsiteDist){ - minDropsiteDist = dist; - nearestDropsite = dropsite; - } - } - }); - if (!nearestDropsite) - { - debug ("No dropsite for " +resource); - return; - } - } - - // if the resource is far away, try to build a farm instead. - var tried = false; - if (resource === "food" && SquareVectorDistance(pos,this.ent.position()) > 22500) - { - tried = this.buildAnyField(gameState); - if (!tried && SquareVectorDistance(pos,this.ent.position()) > 62500) { - return; // wait. a farm should appear. - } - } - if (!tried) { - - if (!gameState.turnCache["ressGathererNB"]) - { - gameState.turnCache["ressGathererNB"] = {}; - gameState.turnCache["ressGathererNB"][nearestSupply.id()] = 1; - } else if (!gameState.turnCache["ressGathererNB"][nearestSupply.id()]) - gameState.turnCache["ressGathererNB"][nearestSupply.id()] = 1; - else - gameState.turnCache["ressGathererNB"][nearestSupply.id()]++; - - this.maxApproachTime = Math.max(25000, VectorDistance(pos,this.ent.position()) * 1000); - ent.gather(nearestSupply); - ent.setMetadata(PlayerID, "target-foundation", undefined); - - // check if the resource we've started gathering from is now full, in which case inform the dropsite. - if (gameState.turnCache["ressGathererNB"][nearestSupply.id()] + nearestSupply.resourceSupplyGatherers().length >= nearestSupply.maxGatherers() - && nearestSupply.getMetadata(PlayerID, "linked-dropsite") != undefined) - { - var dropsite = gameState.getEntityById(nearestSupply.getMetadata(PlayerID, "linked-dropsite")); - if (dropsite == undefined || dropsite.getMetadata(PlayerID, "linked-resources-" + resource) === undefined) - return; - if (nearestSupply.getMetadata(PlayerID, "linked-dropsite-nearby") == true) { - dropsite.setMetadata(PlayerID, "resource-quantity-" + resource, +dropsite.getMetadata(PlayerID, "resource-quantity-" + resource) - (+nearestSupply.getMetadata(PlayerID, "dp-update-value"))); - dropsite.getMetadata(PlayerID, "linked-resources-" + resource).updateEnt(nearestSupply); - dropsite.getMetadata(PlayerID, "nearby-resources-" + resource).updateEnt(nearestSupply); - } else { - dropsite.setMetadata(PlayerID, "resource-quantity-far-" + resource, +dropsite.getMetadata(PlayerID, "resource-quantity-" + resource) - (+nearestSupply.getMetadata(PlayerID, "dp-update-value"))); - dropsite.getMetadata(PlayerID, "linked-resources-" + resource).updateEnt(nearestSupply); - } - - } - - } - } else { - if (resource === "food" && this.buildAnyField(gameState)) - return; - - debug("No " + resource + " found! (2)"); - // If we had a fitting closest dropsite with a lot of resources, mark it as not good. It means it's probably full. Then retry. - // it'll be resetted next time it's counted anyway. - if (nearestDropsite && nearestDropsite.getMetadata(PlayerID, "resource-quantity-" +resource)+nearestDropsite.getMetadata(PlayerID, "resource-quantity-far-" +resource) > 400) - { - nearestDropsite.setMetadata(PlayerID, "resource-quantity-" +resource, 0); - nearestDropsite.setMetadata(PlayerID, "resource-quantity-far-" +resource, 0); - this.startGathering(gameState); - } - } -}; - -// Makes the worker deposit the currently carried resources at the closest dropsite -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 = SquareVectorDistance(self.ent.position(), dropsite.position()); - if (d < dist){ - dist = d; - closestDropsite = dropsite; - } - } - }); - - if (!closestDropsite){ - debug("No dropsite found to deposit " + resource); - return false; - } - - this.ent.returnResources(closestDropsite); - return true; -}; - -Worker.prototype.startHunting = function(gameState){ - var ent = this.ent; - - if (!ent.position() || ent.getMetadata(PlayerID, "stoppedHunting")) - 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){ - 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 = SquareVectorDistance(supply.position(), ent.position()); - - var territoryOwner = Map.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(), 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 = SquareVectorDistance(pos, dropsite.position()); - if (dist < minDropsiteDist){ - minDropsiteDist = dist; - nearestDropsite = dropsite; - } - } - }); - if (!nearestDropsite) - { - ent.setMetadata(PlayerID, "stoppedHunting", true); - ent.setMetadata(PlayerID, "role", undefined); - debug ("No dropsite for hunting food"); - return; - } - if (minDropsiteDist > 45000) { - ent.setMetadata(PlayerID, "stoppedHunting", true); - ent.setMetadata(PlayerID, "role", undefined); - } else { - ent.gather(nearestSupply); - ent.setMetadata(PlayerID, "target-foundation", undefined); - } - } else { - ent.setMetadata(PlayerID, "stoppedHunting", true); - ent.setMetadata(PlayerID, "role", undefined); - debug("No food found for hunting! (2)"); - } -}; - -Worker.prototype.getResourceType = function(type){ - if (!type || !type.generic){ - return undefined; - } - - if (type.generic === "treasure"){ - return type.specific; - }else{ - return type.generic; - } -}; - -Worker.prototype.buildAnyField = function(gameState){ - var self = this; - var okay = false; - var foundations = gameState.getOwnFoundations(); - foundations.filterNearest(this.ent.position(), foundations.length); - foundations.forEach(function (found) { - if (found._template.BuildRestrictions.Category === "Field" && !okay) { - self.ent.repair(found); - okay = true; - return; - } - }); - return okay; -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/worker.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entitycollection-extend.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entitycollection-extend.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entitycollection-extend.js (nonexistent) @@ -1,10 +0,0 @@ -function EntityCollectionFromIds(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 EntityCollection(gameState.ai, ents); -} Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entitycollection-extend.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/timer.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/timer.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/timer.js (nonexistent) @@ -1,106 +0,0 @@ -//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 // -var 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 // -function alarm(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; -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/timer.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/attack_plan.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/attack_plan.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/attack_plan.js (nonexistent) @@ -1,1335 +0,0 @@ -/* This is an attack plan (despite the name, it's a relic of older times). - * It deals with everything in an attack, from picking a target to picking a path to it - * To making sure units rae built, and pushing elements to the queue manager otherwise - * It also handles the actual attack, though much work is needed on that. - * These should be extremely flexible with only minimal work. - * There is a basic support for naval expeditions here. - */ - -function CityAttack(gameState, militaryManager, uniqueID, targetEnemy, type , targetFinder) { - - //This is the list of IDs of the units in the plan - this.idList=[]; - - this.state = "unexecuted"; - this.targetPlayer = targetEnemy; - if (this.targetPlayer === -1 || this.targetPlayer === undefined) { - // let's find our prefered target, basically counting our enemies units. - var enemyCount = {}; - for (var i = 1; i <=8; i++) - enemyCount[i] = 0; - gameState.getEntities().forEach(function(ent) { if (gameState.isEntityEnemy(ent) && ent.owner() !== 0) { enemyCount[ent.owner()]++; } }); - var max = 0; - for (var i in enemyCount) - if (enemyCount[i] > max && +i !== PlayerID) - { - this.targetPlayer = +i; - max = enemyCount[i]; - } - } - if (this.targetPlayer === undefined || this.targetPlayer === -1) - { - this.failed = true; - return false; - } - - var CCs = gameState.getOwnEntities().filter(Filters.byClass("CivCentre")); - if (CCs.length === 0) - { - this.failed = true; - return false; - } - - debug ("Target (" + PlayerID +") = " +this.targetPlayer); - this.targetFinder = targetFinder || this.defaultTargetFinder; - this.type = type || "normal"; - this.name = uniqueID; - this.healthRecord = []; - - this.timeOfPlanStart = gameState.getTimeElapsed(); // we get the time at which we decided to start the attack - - this.maxPreparationTime = 210*1000; - // in this case we want to have the attack ready by the 13th minute. Countdown. Minimum 2 minutes. - if (type !== "superSized" && Config.difficulty >= 1) - this.maxPreparationTime = 780000 - gameState.getTimeElapsed() < 120000 ? 120000 : 780000 - gameState.getTimeElapsed(); - - this.pausingStart = 0; - this.totalPausingTime = 0; - this.paused = false; - - this.onArrivalReaction = "proceedOnTargets"; - - // priority is relative. If all are 0, the only relevant criteria is "currentsize/targetsize". - // if not, this is a "bonus". The higher the priority, the faster this unit will get built. - // Should really be clamped to [0.1-1.5] (assuming 1 is default/the norm) - // Eg: if all are priority 1, and the siege is 0.5, the siege units will get built - // only once every other category is at least 50% of its target size. - // note: siege build order is currently added by the military manager if a fortress is there. - this.unitStat = {}; - this.unitStat["RangedInfantry"] = { "priority" : 1, "minSize" : 4, "targetSize" : 10, "batchSize" : 5, "classes" : ["Infantry","Ranged"], - "interests" : [ ["canGather", 2], ["strength",2], ["cost",1] ], "templates" : [] }; - this.unitStat["MeleeInfantry"] = { "priority" : 1, "minSize" : 4, "targetSize" : 10, "batchSize" : 5, "classes" : ["Infantry","Melee"], - "interests" : [ ["canGather", 2], ["strength",2], ["cost",1] ], "templates" : [] }; - this.unitStat["MeleeCavalry"] = { "priority" : 1, "minSize" : 3, "targetSize" : 8 , "batchSize" : 3, "classes" : ["Cavalry","Melee"], - "interests" : [ ["strength",2], ["cost",1] ], "templates" : [] }; - this.unitStat["RangedCavalry"] = { "priority" : 1, "minSize" : 3, "targetSize" : 8 , "batchSize" : 3, "classes" : ["Cavalry","Ranged"], - "interests" : [ ["strength",2], ["cost",1] ], "templates" : [] }; - var priority = 50; - - if (type === "rush") { - // we have 3 minutes to train infantry. - delete this.unitStat["RangedInfantry"]; - delete this.unitStat["MeleeInfantry"]; - delete this.unitStat["MeleeCavalry"]; - delete this.unitStat["RangedCavalry"]; - this.unitStat["Infantry"] = { "priority" : 1, "minSize" : 10, "targetSize" : 30, "batchSize" : 1, "classes" : ["Infantry"], "interests" : [ ["strength",1], ["cost",1] ], "templates" : [] }; - this.maxPreparationTime = 150*1000; - priority = 120; - } else if (type === "superSized") { - // our first attack has started worst case at the 14th minute, we want to attack another time by the 21th minute, so we rock 6.5 minutes - this.maxPreparationTime = 480000; - // basically we want a mix of citizen soldiers so our barracks have a purpose, and champion units. - this.unitStat["RangedInfantry"] = { "priority" : 1, "minSize" : 5, "targetSize" : 20, "batchSize" : 5, "classes" : ["Infantry","Ranged", "CitizenSoldier"], - "interests" : [["strength",3], ["cost",1] ], "templates" : [] }; - this.unitStat["MeleeInfantry"] = { "priority" : 1, "minSize" : 5, "targetSize" : 20, "batchSize" : 5, "classes" : ["Infantry","Melee", "CitizenSoldier" ], - "interests" : [ ["strength",3], ["cost",1] ], "templates" : [] }; - this.unitStat["ChampRangedInfantry"] = { "priority" : 1, "minSize" : 5, "targetSize" : 15, "batchSize" : 5, "classes" : ["Infantry","Ranged", "Champion"], - "interests" : [["strength",3], ["cost",1] ], "templates" : [] }; - this.unitStat["ChampMeleeInfantry"] = { "priority" : 1, "minSize" : 5, "targetSize" : 15, "batchSize" : 5, "classes" : ["Infantry","Melee", "Champion" ], - "interests" : [ ["strength",3], ["cost",1] ], "templates" : [] }; - this.unitStat["MeleeCavalry"] = { "priority" : 1, "minSize" : 3, "targetSize" : 18, "batchSize" : 3, "classes" : ["Cavalry","Melee", "CitizenSoldier" ], - "interests" : [ ["strength",2], ["cost",1] ], "templates" : [] }; - this.unitStat["RangedCavalry"] = { "priority" : 1, "minSize" : 3, "targetSize" : 18 , "batchSize" : 3, "classes" : ["Cavalry","Ranged", "CitizenSoldier"], - "interests" : [ ["strength",2], ["cost",1] ], "templates" : [] }; - this.unitStat["ChampMeleeInfantry"] = { "priority" : 0.8, "minSize" : 3, "targetSize" : 12, "batchSize" : 3, "classes" : ["Infantry","Melee", "Champion" ], - "interests" : [ ["strength",3], ["cost",1] ], "templates" : [] }; - this.unitStat["ChampMeleeCavalry"] = { "priority" : 0.8, "minSize" : 3, "targetSize" : 12, "batchSize" : 3, "classes" : ["Cavalry","Melee", "Champion" ], - "interests" : [ ["strength",2], ["cost",1] ], "templates" : [] }; - - priority = 70; - } - - // TODO: there should probably be one queue per type of training building - gameState.ai.queueManager.addQueue("plan_" + this.name, priority); - this.queue = gameState.ai.queues["plan_" + this.name]; - gameState.ai.queueManager.addQueue("plan_" + this.name +"_champ", priority); - this.queueChamp = gameState.ai.queues["plan_" + this.name +"_champ"]; - /* - this.unitStat["Siege"]["filter"] = function (ent) { - var strength = [ent.attackStrengths("Melee")["crush"],ent.attackStrengths("Ranged")["crush"]]; - return (strength[0] > 15 || strength[1] > 15); - };*/ - - var filter = Filters.and(Filters.byMetadata(PlayerID, "plan",this.name),Filters.byOwner(PlayerID)); - this.unitCollection = gameState.getOwnEntities().filter(filter); - this.unitCollection.registerUpdates(); - this.unitCollection.length; - - this.unit = {}; - - // each array is [ratio, [associated classes], associated EntityColl, associated unitStat, name ] - this.buildOrder = []; - - // defining the entity collections. Will look for units I own, that are part of this plan. - // Also defining the buildOrders. - for (var unitCat in this.unitStat) { - var cat = unitCat; - var Unit = this.unitStat[cat]; - - filter = Filters.and(Filters.byClassesAnd(Unit["classes"]),Filters.and(Filters.byMetadata(PlayerID, "plan",this.name),Filters.byOwner(PlayerID))); - this.unit[cat] = gameState.getOwnEntities().filter(filter); - this.unit[cat].registerUpdates(); - this.unit[cat].length; - this.buildOrder.push([0, Unit["classes"], this.unit[cat], Unit, cat]); - } - /*if (gameState.getTimeElapsed() > 900000) // 15 minutes - { - - this.unitStat.Cavalry.Ranged["minSize"] = 5; - this.unitStat.Cavalry.Melee["minSize"] = 5; - this.unitStat.Infantry.Ranged["minSize"] = 10; - this.unitStat.Infantry.Melee["minSize"] = 10; - this.unitStat.Cavalry.Ranged["targetSize"] = 10; - this.unitStat.Cavalry.Melee["targetSize"] = 10; - this.unitStat.Infantry.Ranged["targetSize"] = 20; - this.unitStat.Infantry.Melee["targetSize"] = 20; - this.unitStat.Siege["targetSize"] = 5; - this.unitStat.Siege["minSize"] = 2; - - } else { - this.maxPreparationTime = 180000; - }*/ - // todo: REACTIVATE (in all caps) - if (type === "harass_raid" && 0 == 1) - { - this.targetFinder = this.raidingTargetFinder; - this.onArrivalReaction = "huntVillagers"; - - this.type = "harass_raid"; - // This is a Cavalry raid against villagers. A Cavalry Swordsman has a bonus against these. Only build these - this.maxPreparationTime = 180000; // 3 minutes. - if (gameState.playerData.civ === "hele") // hellenes have an ealry Cavalry Swordsman - { - this.unitCount.Cavalry.Melee = { "subCat" : ["Swordsman"] , "usesSubcategories" : true, "Swordsman" : undefined, "priority" : 1, "currentAmount" : 0, "minimalAmount" : 0, "preferedAmount" : 0 }; - this.unitCount.Cavalry.Melee.Swordsman = { "priority" : 1, "currentAmount" : 0, "minimalAmount" : 4, "preferedAmount" : 7, "fallback" : "abort" }; - } else { - this.unitCount.Cavalry.Melee = { "subCat" : undefined , "usesSubcategories" : false, "priority" : 1, "currentAmount" : 0, "minimalAmount" : 4, "preferedAmount" : 7 }; - } - this.unitCount.Cavalry.Ranged["minimalAmount"] = 0; - this.unitCount.Cavalry.Ranged["preferedAmount"] = 0; - this.unitCount.Infantry.Ranged["minimalAmount"] = 0; - this.unitCount.Infantry.Ranged["preferedAmount"] = 0; - this.unitCount.Infantry.Melee["minimalAmount"] = 0; - this.unitCount.Infantry.Melee["preferedAmount"] = 0; - this.unitCount.Siege["preferedAmount"] = 0; - } - this.anyNotMinimal = true; // used for support plans - - - var myFortresses = gameState.getOwnTrainingFacilities().filter(Filters.byClass("GarrisonFortress")); - if (myFortresses.length !== 0) - { - // make this our rallypoint - for (var i in myFortresses._entities) - { - if (myFortresses._entities[i].position()) - { - this.rallyPoint = myFortresses._entities[i].position(); - break; - } - } - } else { - - if(gameState.ai.pathsToMe.length > 1) - var position = [(gameState.ai.pathsToMe[0][0]+gameState.ai.pathsToMe[1][0])/2.0,(gameState.ai.pathsToMe[0][1]+gameState.ai.pathsToMe[1][1])/2.0]; - else if (gameState.ai.pathsToMe.length !== 0) - var position = [gameState.ai.pathsToMe[0][0],gameState.ai.pathsToMe[0][1]]; - else - var position = [-1,-1]; - - if (gameState.ai.accessibility.getAccessValue(position) !== gameState.ai.myIndex) - var position = [-1,-1]; - - var nearestCCArray = CCs.filterNearest(position, 1).toEntityArray(); - var CCpos = nearestCCArray[0].position(); - this.rallyPoint = [0,0]; - if (position[0] !== -1) { - this.rallyPoint[0] = position[0]; - this.rallyPoint[1] = position[1]; - } else { - this.rallyPoint[0] = CCpos[0]; - this.rallyPoint[1] = CCpos[1]; - } - if (type == 'harass_raid') - { - this.rallyPoint[0] = (position[0]*3.9 + 0.1 * CCpos[0]) / 4.0; - this.rallyPoint[1] = (position[1]*3.9 + 0.1 * CCpos[1]) / 4.0; - } - } - - // some variables for during the attack - this.position5TurnsAgo = [0,0]; - this.lastPosition = [0,0]; - this.position = [0,0]; - - this.threatList = []; // sounds so FBI - this.tactics = undefined; - - this.assignUnits(gameState); - - //debug ("Before"); - //Engine.DumpHeap(); - - // get a good path to an estimated target. - this.pathFinder = new aStarPath(gameState,false,false, this.targetPlayer); - //Engine.DumpImage("widthmap.png", this.pathFinder.widthMap, this.pathFinder.width,this.pathFinder.height,255); - - this.pathWidth = 6; // prefer a path far from entities. This will avoid units getting stuck in trees and also results in less straight paths. - this.pathSampling = 2; - this.onBoat = false; // tells us if our units are loaded on boats. - this.needsShip = false; - - //debug ("after"); - //Engine.DumpHeap(); - return true; -}; - -CityAttack.prototype.getName = function(){ - return this.name; -}; -CityAttack.prototype.getType = function(){ - return this.type; -}; -// Returns true if the attack can be executed at the current time -// Basically his checks we have enough units. -// We run a count of our units. -CityAttack.prototype.canStart = function(gameState){ - for (var unitCat in this.unitStat) { - var Unit = this.unitStat[unitCat]; - if (this.unit[unitCat].length < Unit["minSize"]) - return false; - } - return true; - - // TODO: check if our target is valid and a few other stuffs (good moment to attack?) -}; -CityAttack.prototype.isStarted = function(){ - if ((this.state !== "unexecuted")) - debug ("Attack plan already started"); - return !(this.state == "unexecuted"); -}; - -CityAttack.prototype.isPaused = function(){ - return this.paused; -}; -CityAttack.prototype.setPaused = function(gameState, boolValue){ - if (!this.paused && boolValue === true) { - this.pausingStart = gameState.getTimeElapsed(); - this.paused = true; - debug ("Pausing attack plan " +this.name); - } else if (this.paused && boolValue === false) { - this.totalPausingTime += gameState.getTimeElapsed() - this.pausingStart; - this.paused = false; - debug ("Unpausing attack plan " +this.name); - } -}; -CityAttack.prototype.mustStart = function(gameState){ - if (this.isPaused() || this.path === undefined) - return false; - var MaxReachedEverywhere = true; - for (var unitCat in this.unitStat) { - var Unit = this.unitStat[unitCat]; - if (this.unit[unitCat].length < Unit["targetSize"]) { - MaxReachedEverywhere = false; - } - } - if (MaxReachedEverywhere || (gameState.getPopulationMax() - gameState.getPopulation() < 10 && this.canStart(gameState))) - return true; - return (this.maxPreparationTime + this.timeOfPlanStart + this.totalPausingTime < gameState.getTimeElapsed()); -}; - -// Adds a build order. If resetQueue is true, this will reset the queue. -CityAttack.prototype.addBuildOrder = function(gameState, name, unitStats, resetQueue) { - if (!this.isStarted()) - { - debug ("Adding a build order for " + name); - // no minsize as we don't want the plan to fail at the last minute though. - this.unitStat[name] = unitStats; - var Unit = this.unitStat[name]; - var filter = Filters.and(Filters.byClassesAnd(Unit["classes"]),Filters.and(Filters.byMetadata(PlayerID, "plan",this.name),Filters.byOwner(PlayerID))); - this.unit[name] = gameState.getOwnEntities().filter(filter); - this.unit[name].registerUpdates(); - this.buildOrder.push([0, Unit["classes"], this.unit[name], Unit, name]); - if (resetQueue) - { - this.queue.empty(); - this.queueChamp.empty(); - } - } -}; - -// Three returns possible: 1 is "keep going", 0 is "failed plan", 2 is "start" -// 3 is a special case: no valid path returned. Right now I stop attacking alltogether. -CityAttack.prototype.updatePreparation = function(gameState, militaryManager,events) { - var self = this; - - if (this.path == undefined || this.target == undefined || this.path === "toBeContinued") { - // find our target - if (this.target == undefined) - { - var targets = this.targetFinder(gameState, militaryManager); - if (targets.length === 0) - targets = this.defaultTargetFinder(gameState, militaryManager); - - if (targets.length !== 0) { - debug ("Aiming for " + targets); - // picking a target - var maxDist = -1; - var index = 0; - for (var i in targets._entities) - { - // we're sure it has a position has TargetFinder already checks that. - var dist = SquareVectorDistance(targets._entities[i].position(), this.rallyPoint); - if (dist < maxDist || maxDist === -1) - { - maxDist = dist; - index = i; - } - } - this.target = targets._entities[index]; - this.targetPos = this.target.position(); - } - } - // when we have a target, we path to it. - // I'd like a good high width sampling first. - // Thus I will not do everything at once. - // It will probably carry over a few turns but that's no issue. - if (this.path === undefined) - this.path = this.pathFinder.getPath(this.rallyPoint,this.targetPos, this.pathSampling, this.pathWidth,250);//,gameState); - else if (this.path === "toBeContinued") - this.path = this.pathFinder.continuePath();//gameState); - - if (this.path === undefined) { - if (this.pathWidth == 6) - { - this.pathWidth = 2; - delete this.path; - } else { - delete this.pathFinder; - return 3; // no path. - } - } else if (this.path === "toBeContinued") { - // carry on. - } else if (this.path[1] === true && this.pathWidth == 2) { - // okay so we need a ship. - // Basically we'll add it as a new class to train compulsorily, and we'll recompute our path. - if (!gameState.ai.waterMap) - { - debug ("This is actually a water map."); - gameState.ai.waterMap = true; - } - debug ("We need a ship."); - var stat = { "priority" : 1.1, "minSize" : 2, "targetSize" : 2, "batchSize" : 1, "classes" : ["Warship"], - "interests" : [ ["strength",1], ["cost",1] ] ,"templates" : [] }; - if (type === "superSized") { - this.unitStat["TransportShip"]["minSize"] = 4; - this.unitStat["TransportShip"]["targetSize"] = 4; - } - this.addBuildOrder(gameState, "TransportShip", stat); - this.needsShip = true; - this.pathWidth = 3; - this.pathSampling = 3; - this.path = this.path[0].reverse(); - delete this.pathFinder; - // Change the rally point to something useful (should avoid rams getting stuck in houses in my territory, which is dumb.) - for (var i = 0; i < this.path.length; ++i) - { - // my pathfinder returns arrays in arrays in arrays. - var waypointPos = this.path[i][0]; - var territory = Map.createTerritoryMap(gameState); - if (territory.getOwner(waypointPos) !== PlayerID || this.path[i][1] === true) - { - // if we're suddenly out of our territory or this is the point where we change transportation method. - if (i !== 0) - this.rallyPoint = this.path[i-1][0]; - else - this.rallyPoint = this.path[0][0]; - break; - } - } - } else if (this.path[1] === true && this.pathWidth == 6) { - // retry with a smaller pathwidth: - this.pathWidth = 2; - delete this.path; - } else { - this.path = this.path[0].reverse(); - delete this.pathFinder; - - // Change the rally point to something useful (should avoid rams getting stuck in houses in my territory, which is dumb.) - for (var i = 0; i < this.path.length; ++i) - { - // my pathfinder returns arrays in arrays in arrays. - var waypointPos = this.path[i][0]; - var territory = Map.createTerritoryMap(gameState); - if (territory.getOwner(waypointPos) !== PlayerID || this.path[i][1] === true) - { - // if we're suddenly out of our territory or this is the point where we change transportation method. - if (i !== 0) - { - this.rallyPoint = this.path[i-1][0]; - } else - this.rallyPoint = this.path[0][0]; - if (i >= 1) - this.path.splice(0,i-1); - break; - } - } - } - } - - Engine.ProfileStart("Update Preparation"); - - // special case: if we're reached max pop, and we can start the plan, start it. - if ((gameState.getPopulationMax() - gameState.getPopulation() < 10) && this.canStart()) - { - this.assignUnits(gameState); - this.queue.empty(); - this.queueChamp.empty(); - if ( gameState.ai.playedTurn % 5 == 0) - this.AllToRallyPoint(gameState, true); - } else if (this.mustStart(gameState) && (gameState.countOwnQueuedEntitiesWithMetadata("plan", +this.name) > 0)) { - // keep on while the units finish being trained, then we'll start - this.assignUnits(gameState); - - this.queue.empty(); - this.queueChamp.empty(); - - if (gameState.ai.playedTurn % 5 == 0) { - this.AllToRallyPoint(gameState, true); - // TODO: should use this time to let gatherers deposit resources. - } - Engine.ProfileStop(); - return 1; - } else if (!this.mustStart(gameState)) { - // We still have time left to recruit units and do stuffs. - - // let's sort by training advancement, ie 'current size / target size' - // count the number of queued units too. - // substract priority. - this.buildOrder.sort(function (a,b) { //}) { - var aQueued = gameState.countOwnQueuedEntitiesWithMetadata("special","Plan_"+self.name+"_"+a[4]); - aQueued += self.queue.countTotalQueuedUnitsWithMetadata("special","Plan_"+self.name+"_"+a[4]); - aQueued += self.queueChamp.countTotalQueuedUnitsWithMetadata("special","Plan_"+self.name+"_"+a[4]); - a[0] = (a[2].length + aQueued)/a[3]["targetSize"]; - - var bQueued = gameState.countOwnQueuedEntitiesWithMetadata("special","Plan_"+self.name+"_"+b[4]); - bQueued += self.queue.countTotalQueuedUnitsWithMetadata("special","Plan_"+self.name+"_"+b[4]); - bQueued += self.queueChamp.countTotalQueuedUnitsWithMetadata("special","Plan_"+self.name+"_"+b[4]); - b[0] = (b[2].length + bQueued)/b[3]["targetSize"]; - - a[0] -= a[3]["priority"]; - b[0] -= b[3]["priority"]; - return (a[0]) - (b[0]); - }); - - this.assignUnits(gameState); - - if (gameState.ai.playedTurn % 5 == 0) { - this.AllToRallyPoint(gameState, false); - this.unitCollection.setStance("standground"); // make sure units won't disperse out of control - } - - Engine.ProfileStart("Creating units."); - - // gets the number in training of the same kind as the first one. - var specialData = "Plan_"+this.name+"_"+this.buildOrder[0][4]; - var inTraining = gameState.countOwnQueuedEntitiesWithMetadata("special",specialData); - - var queued = this.queue.countTotalQueuedUnitsWithMetadata("special",specialData) + this.queueChamp.countTotalQueuedUnitsWithMetadata("special",specialData) - - if (queued + inTraining + this.buildOrder[0][2].length <= this.buildOrder[0][3]["targetSize"]) { - // find the actual queue we want - var queue = this.queue; - if (this.buildOrder[0][3]["classes"].indexOf("Champion") !== -1) - queue = this.queueChamp; - - if (this.buildOrder[0][0] < 1 && queue.length() <= 5) { - var template = militaryManager.findBestTrainableUnit(gameState, this.buildOrder[0][1], this.buildOrder[0][3]["interests"] ); - //debug ("tried " + uneval(this.buildOrder[0][1]) +", and " + template); - // HACK (TODO replace) : if we have no trainable template... Then we'll simply remove the buildOrder, effectively removing the unit from the plan. - if (template === undefined) { - // TODO: this is a complete hack. - if (this.needsShip && this.buildOrder[0][4] == "TransportShip") { - Engine.ProfileStop(); - Engine.ProfileStop(); - return 0; - } - delete this.unitStat[this.buildOrder[0][4]]; // deleting the associated unitstat. - this.buildOrder.splice(0,1); - } else { - var max = this.buildOrder[0][3]["batchSize"]; - // TODO: this should be plan dependant. - if (gameState.getTimeElapsed() > 1800000) - max *= 2; - if (gameState.getTemplate(template).hasClasses(["CitizenSoldier", "Infantry"])) - queue.addItem( new UnitTrainingPlan(gameState,template, { "role" : "worker", "plan" : this.name, "special" : specialData }, this.buildOrder[0][3]["batchSize"],max ) ); - else - queue.addItem( new UnitTrainingPlan(gameState,template, { "role" : "attack", "plan" : this.name, "special" : specialData }, this.buildOrder[0][3]["batchSize"],max ) ); - } - } - } - /* - if (!this.startedPathing && this.path === undefined) { - - // find our target - var targets = this.targetFinder(gameState, militaryManager); - if (targets.length === 0){ - targets = this.defaultTargetFinder(gameState, militaryManager); - } - if (targets.length) { - this.targetPos = undefined; - var count = 0; - while (!this.targetPos){ - var rand = Math.floor((Math.random()*targets.length)); - var target = targets.toEntityArray()[rand]; - this.targetPos = target.position(); - count++; - if (count > 1000){ - debug("No target with a valid position found"); - return false; - } - } - this.startedPathing = true; - // Start pathfinding using the optimized version, with a minimal sampling of 2 - this.pathFinder.getPath(this.rallyPoint,this.targetPos, false, 2, gameState); - } - } else if (this.startedPathing) { - var path = this.pathFinder.continuePath(gameState); - if (path !== "toBeContinued") { - this.startedPathing = false; - this.path = path; - debug("Pathing ended"); - } - } - */ - Engine.ProfileStop(); - Engine.ProfileStop(); - // can happen for now - if (this.buildOrder.length === 0) { - debug ("Ending plan: no build orders"); - return 0; // will abort the plan, should return something else - } - return 1; - } - this.unitCollection.forEach(function (entity) { entity.setMetadata(PlayerID, "role","attack"); }); - - Engine.ProfileStop(); - // if we're here, it means we must start (and have no units in training left). - // if we can, do, else, abort. - if (this.canStart(gameState)) - return 2; - else - return 0; - return 0; -}; -CityAttack.prototype.assignUnits = function(gameState){ - var self = this; - - // TODO: assign myself units that fit only, right now I'm getting anything. - // Assign all no-roles that fit (after a plan aborts, for example). - var NoRole = gameState.getOwnEntitiesByRole(undefined); - if (this.type === "rush") - NoRole = gameState.getOwnEntitiesByRole("worker"); - NoRole.forEach(function(ent) { - if (ent.hasClass("Unit") && ent.attackTypes() !== undefined) - { - if (ent.hasClasses(["CitizenSoldier", "Infantry"])) - ent.setMetadata(PlayerID, "role", "worker"); - else - ent.setMetadata(PlayerID, "role", "attack"); - ent.setMetadata(PlayerID, "plan", self.name); - } - }); - -}; -// this sends a unit by ID back to the "rally point" -CityAttack.prototype.ToRallyPoint = function(gameState,id) -{ - // Move back to nearest rallypoint - gameState.getEntityById(id).move(this.rallyPoint[0],this.rallyPoint[1]); -} -// this sends all units back to the "rally point" by entity collections. -// It doesn't disturb ones that could be currently defending, even if the plan is not (yet) paused. -CityAttack.prototype.AllToRallyPoint = function(gameState, evenWorkers) { - var self = this; - if (evenWorkers) { - for (var unitCat in this.unit) { - this.unit[unitCat].forEach(function (ent) { - if (ent.getMetadata(PlayerID, "role") != "defence" && !ent.hasClass("Warship")) - { - ent.setMetadata(PlayerID,"role", "attack"); - ent.move(self.rallyPoint[0],self.rallyPoint[1]); - } - }); - } - } else { - for (var unitCat in this.unit) { - this.unit[unitCat].forEach(function (ent) { - if (ent.getMetadata(PlayerID, "role") != "worker" && ent.getMetadata(PlayerID, "role") != "defence" && !ent.hasClass("Warship")) - ent.move(self.rallyPoint[0],self.rallyPoint[1]); - }); - } - } -} - -// Default target finder aims for conquest critical targets -CityAttack.prototype.defaultTargetFinder = function(gameState, militaryManager){ - var targets = undefined; - - targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings(gameState, "CivCentre",true); - if (targets.length == 0) { - targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings(gameState, "ConquestCritical"); - } - // If there's nothing, attack anything else that's less critical - if (targets.length == 0) { - targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings(gameState, "Town",true); - } - if (targets.length == 0) { - targets = militaryManager.enemyWatchers[this.targetPlayer].getEnemyBuildings(gameState, "Village",true); - } - // no buildings, attack anything conquest critical, even units (it's assuming it won't move). - if (targets.length == 0) { - targets = gameState.getEnemyEntities().filter(Filters.and( Filters.byOwner(this.targetPlayer),Filters.byClass("ConquestCritical"))); - } - return targets; -}; - -// tupdate -CityAttack.prototype.raidingTargetFinder = function(gameState, militaryManager, Target){ - var targets = undefined; - if (Target == "villager") - { - // let's aim for any resource dropsite. We assume villagers are in the neighborhood (note: the human player could certainly troll us... small (scouting) TODO here.) - targets = gameState.entities.filter(function(ent) { - return (ent.hasClass("Structure") && ent.resourceDropsiteTypes() !== undefined && !ent.hasClass("CivCentre") && ent.owner() === this.targetPlayer && ent.position()); - }); - if (targets.length == 0) { - targets = gameState.entities.filter(function(ent) { - return (ent.hasClass("CivCentre") && ent.resourceDropsiteTypes() !== undefined && ent.owner() === this.targetPlayer && ent.position()); - }); - } - if (targets.length == 0) { - // if we're here, it means they also don't have no CC... So I'll just take any building at this point. - targets = gameState.entities.filter(function(ent) { - return (ent.hasClass("Structure") && ent.owner() === this.targetPlayer && ent.position()); - }); - } - return targets; - } else { - return this.defaultTargetFinder(gameState, militaryManager); - } -}; - -// Executes the attack plan, after this is executed the update function will be run every turn -// If we're here, it's because we have in our IDlist enough units. -// now the IDlist units are treated turn by turn -CityAttack.prototype.StartAttack = function(gameState, militaryManager){ - - // check we have a target and a path. - if (this.targetPos && this.path !== undefined) { - // erase our queue. This will stop any leftover unit from being trained. - gameState.ai.queueManager.removeQueue("plan_" + this.name); - gameState.ai.queueManager.removeQueue("plan_" + this.name + "_champ"); - - var curPos = this.unitCollection.getCentrePosition(); - - this.unitCollection.forEach(function(ent) { ent.setMetadata(PlayerID, "subrole", "walking"); ent.setMetadata(PlayerID, "role", "attack") ;}); - - this.unitCollectionNoWarship = this.unitCollection.filter(Filters.not(Filters.byClass("Warship"))); - this.unitCollectionNoWarship.registerUpdates(); - - this.unitCollection.moveIndiv(this.path[0][0][0], this.path[0][0][1]); - this.unitCollection.setStance("aggressive"); - this.unitCollection.filter(Filters.byClass("Siege")).setStance("defensive"); - - this.state = "walking"; - } else { - gameState.ai.gameFinished = true; - debug ("I do not have any target. So I'll just assume I won the game."); - return false; - } - return true; -}; - -// Runs every turn after the attack is executed -CityAttack.prototype.update = function(gameState, militaryManager, events){ - var self = this; - - Engine.ProfileStart("Update Attack"); - - // we're marching towards the target - // Check for attacked units in our band. - var bool_attacked = false; - // raids don't care about attacks much - - if (this.unitCollection.length === 0) { - Engine.ProfileStop(); - return 0; - } - - this.position = this.unitCollection.getCentrePosition(); - - var IDs = this.unitCollection.toIdArray(); - - // this actually doesn't do anything right now. - if (this.state === "walking") { - - var attackedNB = 0; - - var toProcess = {}; - var armyToProcess = {}; - // Let's check if any of our unit has been attacked. In case yes, we'll determine if we're simply off against an enemy army, a lone unit/builing - // or if we reached the enemy base. Different plans may react differently. - for (var key in events) { - var e = events[key]; - if (e.type === "Attacked" && e.msg) { - if (IDs.indexOf(e.msg.target) !== -1) { - var attacker = gameState.getEntityById(e.msg.attacker); - var ourUnit = gameState.getEntityById(e.msg.target); - - if (attacker && attacker.position() && attacker.hasClass("Unit") && attacker.owner() != 0 && attacker.owner() != PlayerID) { - - var territoryMap = Map.createTerritoryMap(gameState); - if ( +territoryMap.point(attacker.position()) - 64 === +this.targetPlayer) - { - attackedNB++; - } - //if (militaryManager.enemyWatchers[attacker.owner()]) { - //toProcess[attacker.id()] = attacker; - //var armyID = militaryManager.enemyWatchers[attacker.owner()].getArmyFromMember(attacker.id()); - //armyToProcess[armyID[0]] = armyID[1]; - //} - } - // if we're being attacked by a building, flee. - if (attacker && ourUnit && attacker.hasClass("Structure")) { - ourUnit.flee(attacker); - } - } - } - } - if (attackedNB > 4) { - debug ("Attack Plan " +this.type +" " +this.name +" has arrived to destination."); - // we must assume we've arrived at the end of the trail. - this.state = "arrived"; - } - - /* - - }&& this.type !== "harass_raid"){ // walking toward the target - var sumAttackerPos = [0,0]; - var numAttackers = 0; - // let's check if one of our unit is not under attack, by any chance. - for (var key in events){ - var e = events[key]; - if (e.type === "Attacked" && e.msg){ - if (this.unitCollection.toIdArray().indexOf(e.msg.target) !== -1){ - var attacker = HeadQuarters.entity(e.msg.attacker); - if (attacker && attacker.position()){ - sumAttackerPos[0] += attacker.position()[0]; - sumAttackerPos[1] += attacker.position()[1]; - numAttackers += 1; - bool_attacked = true; - // todo: differentiate depending on attacker type... If it's a ship, let's not do anythin, a building, depends on the attack type/ - if (this.threatList.indexOf(e.msg.attacker) === -1) - { - var enemySoldiers = HeadQuarters.getEnemySoldiers().toEntityArray(); - for (var j in enemySoldiers) - { - var enemy = enemySoldiers[j]; - if (enemy.position() === undefined) // likely garrisoned - continue; - if (inRange(enemy.position(), attacker.position(), 1000) && this.threatList.indexOf(enemy.id()) === -1) - this.threatList.push(enemy.id()); - } - this.threatList.push(e.msg.attacker); - } - } - } - } - } - if (bool_attacked > 0){ - var avgAttackerPos = [sumAttackerPos[0]/numAttackers, sumAttackerPos[1]/numAttackers]; - units.move(avgAttackerPos[0], avgAttackerPos[1]); // let's run towards it. - this.tactics = new Tactics(gameState,HeadQuarters, this.idList,this.threatList,true); - this.state = "attacking_threat"; - } - }else if (this.state === "attacking_threat"){ - this.tactics.eventMetadataCleanup(events,HeadQuarters); - var removeList = this.tactics.removeTheirDeads(HeadQuarters); - this.tactics.removeMyDeads(HeadQuarters); - for (var i in removeList){ - this.threatList.splice(this.threatList.indexOf(removeList[i]),1); - } - if (this.threatList.length <= 0) - { - this.tactics.disband(HeadQuarters,events); - this.tactics = undefined; - this.state = "walking"; - units.move(this.path[0][0], this.path[0][1]); - }else - { - this.tactics.reassignAttacks(HeadQuarters); - } - }*/ - } - if (this.state === "walking"){ - - this.position = this.unitCollectionNoWarship.getCentrePosition(); - - // probably not too good. - if (!this.position) { - Engine.ProfileStop(); - return undefined; // should spawn an error. - } - - // basically haven't moved an inch: very likely stuck) - if (SquareVectorDistance(this.position, this.position5TurnsAgo) < 10 && this.path.length > 0 && gameState.ai.playedTurn % 5 === 0) { - // check for stuck siege units - - var sieges = this.unitCollection.filter(Filters.byClass("Siege")); - var farthest = 0; - var farthestEnt = -1; - sieges.forEach (function (ent) { - if (SquareVectorDistance(ent.position(),self.position) > farthest) - { - farthest = SquareVectorDistance(ent.position(),self.position); - farthestEnt = ent; - } - }); - if (farthestEnt !== -1) - farthestEnt.destroy(); - } - if (gameState.ai.playedTurn % 5 === 0) - this.position5TurnsAgo = this.position; - - if (this.lastPosition && SquareVectorDistance(this.position, this.lastPosition) < 20 && this.path.length > 0) { - this.unitCollectionNoWarship.moveIndiv(this.path[0][0][0], this.path[0][0][1]); - // We're stuck, presumably. Check if there are no walls just close to us. If so, we're arrived, and we're gonna tear down some serious stone. - var walls = gameState.getEnemyEntities().filter(Filters.and(Filters.byOwner(this.targetPlayer), Filters.byClass("StoneWall"))); - var nexttoWalls = false; - walls.forEach( function (ent) { - if (!nexttoWalls && SquareVectorDistance(self.position, ent.position()) < 800) - nexttoWalls = true; - }); - // there are walls but we can attack - if (nexttoWalls && this.unitCollection.filter(Filters.byCanAttack("StoneWall")).length !== 0) - { - debug ("Attack Plan " +this.type +" " +this.name +" has met walls and is not happy."); - this.state = "arrived"; - } else if (nexttoWalls) { - // abort plan. - debug ("Attack Plan " +this.type +" " +this.name +" has met walls and gives up."); - Engine.ProfileStop(); - return 0; - } - } - - // check if our land units are close enough from the next waypoint. - if (SquareVectorDistance(this.unitCollectionNoWarship.getCentrePosition(), this.targetPos) < 7500 || - SquareVectorDistance(this.unitCollectionNoWarship.getCentrePosition(), this.path[0][0]) < 850) { - if (this.unitCollection.filter(Filters.byClass("Siege")).length !== 0 - && SquareVectorDistance(this.unitCollectionNoWarship.getCentrePosition(), this.targetPos) > 7500 - && SquareVectorDistance(this.unitCollection.filter(Filters.byClass("Siege")).getCentrePosition(), this.path[0][0]) > 850) - { - } else { - // okay so here basically two cases. The first one is "we need a boat at this point". - // the second one is "we need to unload at this point". The third is "normal". - if (this.path[0][1] !== true) - { - this.path.shift(); - if (this.path.length > 0){ - this.unitCollectionNoWarship.moveIndiv(this.path[0][0][0], this.path[0][0][1]); - } else { - debug ("Attack Plan " +this.type +" " +this.name +" has arrived to destination."); - // we must assume we've arrived at the end of the trail. - this.state = "arrived"; - } - } else if (this.path[0][1] === true) - { - // okay we must load our units. - // check if we have some kind of ships. - var ships = this.unitCollection.filter(Filters.byClass("Warship")); - if (ships.length === 0) { - Engine.ProfileStop(); - return 0; // abort - } - - debug ("switch to boarding"); - this.state = "boarding"; - } - } - } - } else if (this.state === "shipping") { - this.position = this.unitCollection.filter(Filters.byClass("Warship")).getCentrePosition(); - - if (!this.lastPosition) - this.lastPosition = [0,0]; - - if (SquareVectorDistance(this.position, this.lastPosition) < 20 && this.path.length > 0) { - this.unitCollection.filter(Filters.byClass("Warship")).move(this.path[0][0][0], this.path[0][0][1]); - } - if (SquareVectorDistance(this.position, this.path[0][0]) < 1600) { - if (this.path[0][1] !== true) - { - this.path.shift(); - if (this.path.length > 0){ - this.unitCollection.filter(Filters.byClass("Warship")).move(this.path[0][0][0], this.path[0][0][1]); - } else { - debug ("Attack Plan " +this.type +" " +this.name +" has arrived to destination, but it's still on the ship…"); - Engine.ProfileStop(); - return 0; // abort - } - } else if (this.path[0][1] === true) - { - debug ("switch to unboarding"); - // we unload - this.state = "unboarding"; - } - } - } else if (this.state === "boarding") { - this.position = this.unitCollectionNoWarship.getCentrePosition(); - - var ships = this.unitCollection.filter(Filters.byClass("Warship")); - if (ships.length === 0) { - Engine.ProfileStop(); - return 0; // abort - } - - var globalPos = this.unitCollectionNoWarship.getCentrePosition(); - var shipPos = ships.getCentrePosition(); - - if (globalPos !== undefined && SquareVectorDistance(globalPos,shipPos) > 800) - { // get them closer - ships.moveIndiv(globalPos[0],globalPos[1]); - this.unitCollectionNoWarship.moveIndiv(shipPos[0],shipPos[1]); - } else { - // okay try to garrison. - var shipsArray = ships.toEntityArray(); - this.unitCollectionNoWarship.forEach(function (ent) { //}){ - if (ent.position()) // if we're not garrisoned - for (var shipId = 0; shipId < shipsArray.length; shipId++) { - if (shipsArray[shipId].garrisoned().length < shipsArray[shipId].garrisonMax()) - { - ent.garrison(shipsArray[shipId]); - break; - } - } - }); - var garrLength = 0; - for (var shipId = 0; shipId < shipsArray.length; shipId++) - garrLength += shipsArray[shipId].garrisoned().length; - - if (garrLength == this.unitCollectionNoWarship.length) { - // okay. - this.path.shift(); - if (this.path.length > 0){ - ships.move(this.path[0][0][0], this.path[0][0][1]); - debug ("switch to shipping"); - this.state = "shipping"; - } else { - debug ("Attack Plan " +this.type +" " +this.name +" has arrived to destination."); - // we must assume we've arrived at the end of the trail. - this.state = "arrived"; - } - } - } - } else if (this.state === "unboarding") { - - var ships = this.unitCollection.filter(Filters.byClass("Warship")); - if (ships.length === 0) { - Engine.ProfileStop(); - return 0; // abort - } - - this.position = ships.getCentrePosition(); - - // the procedure is pretty simple: we move the ships to the next point and try to unload until all units are over. - // TODO: make it better, like avoiding collisions, and so on. - - if (this.path.length > 1) - ships.move(this.path[1][0][0], this.path[1][0][1]); - - ships.forEach(function (ship) { - ship.unloadAll(); - }); - - var shipsArray = ships.toEntityArray(); - var garrLength = 0; - for (var shipId = 0; shipId < shipsArray.length; shipId++) - garrLength += shipsArray[shipId].garrisoned().length; - - if (garrLength == 0) { - // release the ships - - ships.forEach(function (ent) { - ent.setMetadata(PlayerID, "role",undefined); - ent.setMetadata(PlayerID, "subrole",undefined); - ent.setMetadata(PlayerID, "plan",undefined); - }); - for (var shipId = 0; shipId < shipsArray.length; shipId++) - this.unitCollection.removeEnt(shipsArray[shipId]); - - this.path.shift(); - if (this.path.length > 0){ - this.unitCollection.moveIndiv(this.path[0][0][0], this.path[0][0][1]); - debug ("switch to walking"); - this.state = "walking"; - } else { - debug ("Attack Plan " +this.type +" " +this.name +" has arrived to destination."); - // we must assume we've arrived at the end of the trail. - this.state = "arrived"; - } - } - - } - - - // todo: re-implement raiding - if (this.state === "arrived"){ - // let's proceed on with whatever happens now. - // There's a ton of TODOs on this part. - if (this.onArrivalReaction == "proceedOnTargets") { - this.state = ""; - this.unitCollection.forEach( function (ent) { //}) { - ent.stopMoving(); - ent.setMetadata(PlayerID, "subrole", "attacking"); - }); - } else if (this.onArrivalReaction == "huntVillagers") { - // let's get any villager and target them with a tactics manager - var enemyCitizens = gameState.entities.filter(function(ent) { - return (gameState.isEntityEnemy(ent) && ent.hasClass("Support") && ent.owner() !== 0 && ent.position()); - }); - var targetList = []; - enemyCitizens.forEach( function (enemy) { - if (inRange(enemy.position(), units.getCentrePosition(), 2500) && targetList.indexOf(enemy.id()) === -1) - targetList.push(enemy.id()); - }); - if (targetList.length > 0) - { - this.tactics = new Tactics(gameState,HeadQuarters, this.idList,targetList); - this.state = "huntVillagers"; - var arrivedthisTurn = true; - } else { - this.state = ""; - var arrivedthisTurn = true; - } - } - } - - if (this.state === "") { - - // Units attacked will target their attacker unless they're siege. Then we take another non-siege unit to attack them. - for (var key in events) { - var e = events[key]; - if (e.type === "Attacked" && e.msg) { - if (IDs.indexOf(e.msg.target) !== -1) { - var attacker = gameState.getEntityById(e.msg.attacker); - var ourUnit = gameState.getEntityById(e.msg.target); - - if (attacker && attacker.position() && attacker.hasClass("Unit") && attacker.owner() != 0 && attacker.owner() != PlayerID) { - if (ourUnit.hasClass("Siege")) - { - var help = this.unitCollection.filter(Filters.and(Filters.not(Filters.byClass("Siege")),Filters.isIdle())); - if (help.length === 0) - help = this.unitCollection.filter(Filters.not(Filters.byClass("Siege"))); - if (help.length > 0) - help.toEntityArray()[0].attack(attacker.id()); - if (help.length > 1) - help.toEntityArray()[1].attack(attacker.id()); - - } else { - ourUnit.attack(attacker.id()); - } - } - } - } - } - - - var enemyUnits = gameState.getEnemyEntities().filter(Filters.and(Filters.byOwner(this.targetPlayer), Filters.byClass("Unit"))); - var enemyStructures = gameState.getEnemyEntities().filter(Filters.and(Filters.byOwner(this.targetPlayer), Filters.byClass("Structure"))); - - if (this.unitCollUpdateArray === undefined || this.unitCollUpdateArray.length === 0) - { - this.unitCollUpdateArray = this.unitCollection.toEntityArray(); - } else { - // Let's check a few units each time we update. Currently 10 - for (var check = 0; check < Math.min(this.unitCollUpdateArray.length,10); check++) - { - var ent = this.unitCollUpdateArray[0]; - - // if the unit is not in my territory, make it move. - var territoryMap = Map.createTerritoryMap(gameState); - if (territoryMap.point(ent.position()) - 64 === PlayerID) - ent.move(this.targetPos[0],this.targetPos[1]); - // update it. - var needsUpdate = false; - if (ent.isIdle()) - needsUpdate = true; - if (ent.hasClass("Siege") && (!ent.unitAIOrderData() || !ent.unitAIOrderData()["target"] || !gameState.getEntityById(ent.unitAIOrderData()["target"]).hasClass("ConquestCritical")) ) - needsUpdate = true; - else if (ent.unitAIOrderData() && ent.unitAIOrderData()["target"] && gameState.getEntityById(ent.unitAIOrderData()["target"]).hasClass("Structure")) - needsUpdate = true; // try to make it attack a unit instead - - if (gameState.getTimeElapsed() - ent.getMetadata(PlayerID, "lastAttackPlanUpdateTime") < 10000) - needsUpdate = false; - - if (needsUpdate || arrivedthisTurn) - { - ent.setMetadata(PlayerID, "lastAttackPlanUpdateTime", gameState.getTimeElapsed()); - var mStruct = enemyStructures.filter(function (enemy) { //}){ - if (!enemy.position() || (enemy.hasClass("StoneWall") && ent.canAttackClass("StoneWall"))) { - return false; - } - if (SquareVectorDistance(enemy.position(),ent.position()) > 2000) { - return false; - } - return true; - }); - var mUnit; - if (ent.hasClass("Cavalry")) { - mUnit = enemyUnits.filter(function (enemy) { //}){ - if (!enemy.position()) { - return false; - } - if (!enemy.hasClass("Support")) - return false; - if (SquareVectorDistance(enemy.position(),ent.position()) > 2000) { - return false; - } - return true; - }); - } - if (!ent.hasClass("Cavalry") || mUnit.length === 0) { - mUnit = enemyUnits.filter(function (enemy) { //}){ - if (!enemy.position()) { - return false; - } - if (SquareVectorDistance(enemy.position(),ent.position()) > 2000) { - return false; - } - return true; - }); - } - var isGate = false; - mUnit = mUnit.toEntityArray(); - mStruct = mStruct.toEntityArray(); - if (ent.hasClass("Siege")) { - mStruct.sort(function (structa,structb) { //}){ - var vala = structa.costSum(); - if (structa.hasClass("Gates") && ent.canAttackClass("StoneWall")) // we hate gates - { - isGate = true; - vala += 10000; - } else if (structa.hasClass("ConquestCritical")) - vala += 200; - var valb = structb.costSum(); - if (structb.hasClass("Gates") && ent.canAttackClass("StoneWall")) // we hate gates - { - isGate = true; - valb += 10000; - } else if (structb.hasClass("ConquestCritical")) - valb += 200; - //warn ("Structure " +structa.genericName() + " is worth " +vala); - //warn ("Structure " +structb.genericName() + " is worth " +valb); - return (valb - vala); - }); - - if (mStruct.length !== 0) { - if (isGate) - ent.attack(mStruct[0].id()); - else - { - var rand = Math.floor(Math.random() * mStruct.length*0.1); - ent.attack(mStruct[+rand].id()); - //debug ("Siege units attacking a structure from " +mStruct[+rand].owner() + " , " +mStruct[+rand].templateName()); - } - } else if (SquareVectorDistance(self.targetPos, ent.position()) > 900 ){ - //debug ("Siege units moving to " + uneval(self.targetPos)); - ent.move(self.targetPos[0],self.targetPos[1]); - } - } else { - if (mUnit.length !== 0 && !isGate) { - var rand = Math.floor(Math.random() * mUnit.length*0.99); - ent.attack(mUnit[(+rand)].id()); - //debug ("Units attacking a unit from " +mUnit[+rand].owner() + " , " +mUnit[+rand].templateName()); - } else if (mStruct.length !== 0) { - mStruct.sort(function (structa,structb) { //}){ - var vala = structa.costSum(); - if (structa.hasClass("Gates") && ent.canAttackClass("StoneWall")) // we hate gates - { - isGate = true; - vala += 10000; - } else if (structa.hasClass("ConquestCritical")) - vala += 100; - var valb = structb.costSum(); - if (structb.hasClass("Gates") && ent.canAttackClass("StoneWall")) // we hate gates - { - isGate = true; - valb += 10000; - } else if (structb.hasClass("ConquestCritical")) - valb += 100; - return (valb - vala); - }); - if (isGate) - ent.attack(mStruct[0].id()); - else - { - var rand = Math.floor(Math.random() * mStruct.length*0.1); - ent.attack(mStruct[+rand].id()); - //debug ("Units attacking a structure from " +mStruct[+rand].owner() + " , " +mStruct[+rand].templateName()); - } - } else if (SquareVectorDistance(self.targetPos, ent.position()) > 900 ){ - //debug ("Units moving to " + uneval(self.targetPos)); - ent.move(self.targetPos[0],self.targetPos[1]); - } - } - } - - this.unitCollUpdateArray.splice(0,1); - } - } - // updating targets. - if (!gameState.getEntityById(this.target.id())) - { - var targets = this.targetFinder(gameState, militaryManager); - if (targets.length === 0){ - targets = this.defaultTargetFinder(gameState, militaryManager); - } - if (targets.length) { - debug ("Seems like our target has been destroyed. Switching."); - debug ("Aiming for " + targets); - // picking a target - this.targetPos = undefined; - var count = 0; - while (!this.targetPos){ - var rand = Math.floor((Math.random()*targets.length)); - this.target = targets.toEntityArray()[rand]; - this.targetPos = this.target.position(); - count++; - if (count > 1000){ - debug("No target with a valid position found"); - Engine.ProfileStop(); - return false; - } - } - } - } - - // regularly update the target position in case it's a unit. - if (this.target.hasClass("Unit")) - this.targetPos = this.target.position(); - } - /* - if (this.state === "huntVillagers") - { - this.tactics.eventMetadataCleanup(events,HeadQuarters); - this.tactics.removeTheirDeads(HeadQuarters); - this.tactics.removeMyDeads(HeadQuarters); - if (this.tactics.isBattleOver()) - { - this.tactics.disband(HeadQuarters,events); - this.tactics = undefined; - this.state = ""; - return 0; // assume over - } else - this.tactics.reassignAttacks(HeadQuarters); - }*/ - this.lastPosition = this.position; - Engine.ProfileStop(); - - return this.unitCollection.length; -}; -CityAttack.prototype.totalCountUnits = function(gameState){ - var totalcount = 0; - for (var i in this.idList) - { - totalcount++; - } - return totalcount; -}; -// reset any units -CityAttack.prototype.Abort = function(gameState){ - this.unitCollection.forEach(function(ent) { - ent.setMetadata(PlayerID, "role",undefined); - ent.setMetadata(PlayerID, "subrole",undefined); - ent.setMetadata(PlayerID, "plan",undefined); - }); - for (var unitCat in this.unitStat) { - delete this.unitStat[unitCat]; - delete this.unit[unitCat]; - } - delete this.unitCollection; - gameState.ai.queueManager.removeQueue("plan_" + this.name); - gameState.ai.queueManager.removeQueue("plan_" + this.name + "_champ"); -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/attack_plan.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:executable ## -1 +0,0 ## -* \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/template-manager.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/template-manager.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/template-manager.js (nonexistent) @@ -1,116 +0,0 @@ -/* - * Used to know which templates I have, which templates I know I can train, things like that. - * Mostly unused. - */ - -var 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); - -}; -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); - } - - }); -} -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); - } - } - } - } -} -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); - } - } - } - } -} -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 -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; -} - Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/template-manager.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:executable ## -1 +0,0 ## -* \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-research.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-research.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-research.js (nonexistent) @@ -1,54 +0,0 @@ -var ResearchPlan = function(gameState, type, rush) { - this.type = type; - - this.template = gameState.getTemplate(this.type); - if (!this.template || this.template.researchTime === undefined) { - this.invalidTemplate = true; - this.template = undefined; - debug ("Invalid research"); - return false; - } - this.category = "technology"; - this.cost = new Resources(this.template.cost(),0); - this.number = 1; // Obligatory for compatibility - if (rush) - this.rush = true; - else - this.rush = false; - return true; -}; - -ResearchPlan.prototype.canExecute = function(gameState) { - if (this.invalidTemplate) - return false; - - // also checks canResearch - return (gameState.findResearchers(this.type).length !== 0); -}; - -ResearchPlan.prototype.execute = function(gameState) { - var self = this; - //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); - } -}; - -ResearchPlan.prototype.getCost = function(){ - return this.cost; -}; - Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-research.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/license_gpl-2.0.txt =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/license_gpl-2.0.txt (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/license_gpl-2.0.txt (nonexistent) @@ -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. - - - Copyright (C) - - 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. - - , 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. Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/license_gpl-2.0.txt ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue.js (nonexistent) @@ -1,152 +0,0 @@ -/* - * Holds a list of wanted items to train or construct - */ - -var Queue = function() { - this.queue = []; - this.outQueue = []; -}; - -Queue.prototype.empty = function() { - this.queue = []; - this.outQueue = []; -}; - - -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); -}; - -Queue.prototype.getNext = function() { - if (this.queue.length > 0) { - return this.queue[0]; - } else { - return null; - } -}; - -Queue.prototype.outQueueNext = function(){ - if (this.outQueue.length > 0) { - return this.outQueue[0]; - } else { - return null; - } -}; - -Queue.prototype.outQueueCost = function(){ - var cost = new Resources(); - for (var key in this.outQueue){ - cost.add(this.outQueue[key].getCost()); - } - return cost; -}; - -Queue.prototype.queueCost = function(){ - var cost = new Resources(); - for (var key in this.queue){ - cost.add(this.queue[key].getCost()); - } - return cost; -}; - -Queue.prototype.nextToOutQueue = function(){ - if (this.queue.length > 0){ - this.outQueue.push(this.queue.shift()); - } -}; - -Queue.prototype.executeNext = function(gameState) { - if (this.outQueue.length > 0) { - this.outQueue.shift().execute(gameState); - return true; - } else { - return false; - } -}; - -Queue.prototype.length = function() { - return this.queue.length; -}; - -Queue.prototype.countQueuedUnits = function(){ - var count = 0; - for (var i in this.queue){ - count += this.queue[i].number; - } - return count; -}; - -Queue.prototype.countOutQueuedUnits = function(){ - var count = 0; - for (var i in this.outQueue){ - count += this.outQueue[i].number; - } - return count; -}; - -Queue.prototype.countTotalQueuedUnits = function(){ - var count = 0; - for (var i in this.queue){ - count += this.queue[i].number; - } - for (var i in this.outQueue){ - count += this.outQueue[i].number; - } - return count; -}; -Queue.prototype.countTotalQueuedUnitsWithClass = 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; - } - for (var i in this.outQueue){ - if (this.outQueue[i].template && this.outQueue[i].template.hasClass(classe)) - count += this.outQueue[i].number; - } - return count; -}; -Queue.prototype.countTotalQueuedUnitsWithMetadata = 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; - } - for (var i in this.outQueue){ - if (this.outQueue[i].metadata[data] && this.outQueue[i].metadata[data] == value) - count += this.outQueue[i].number; - } - return count; -}; - -Queue.prototype.totalLength = function(){ - return this.queue.length + this.outQueue.length; -}; - -Queue.prototype.outQueueLength = function(){ - return this.outQueue.length; -}; - -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; - } - } - for (var i = 0; i < this.outQueue.length; i++){ - if (this.outQueue[i].type === t){ - count += this.outQueue[i].number; - } - } - return count; -}; \ No newline at end of file Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/utils-extend.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/utils-extend.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/utils-extend.js (nonexistent) @@ -1,26 +0,0 @@ -function AssocArraytoArray(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 -function inRange(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. -function ManhattanDistance(a, b) -{ - var dx = a[0] - b[0]; - var dz = a[1] - b[1]; - return Math.abs(dx) + Math.abs(dz); -} Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/utils-extend.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:executable ## -1 +0,0 ## -* \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-building.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-building.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-building.js (nonexistent) @@ -1,198 +0,0 @@ -var BuildingConstructionPlan = function(gameState, type, position) { - this.type = gameState.applyCiv(type); - this.position = position; - - this.template = gameState.getTemplate(this.type); - if (!this.template) { - this.invalidTemplate = true; - this.template = undefined; - debug("Cannot build " + this.type); - return; - } - this.category = "building"; - this.cost = new Resources(this.template.cost()); - this.number = 1; // The number of buildings to build -}; - -BuildingConstructionPlan.prototype.canExecute = function(gameState) { - if (this.invalidTemplate){ - 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); -}; - -BuildingConstructionPlan.prototype.execute = 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.modules.economy.dockFailed = true; - debug("No room to place " + this.type); - return; - } - - 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); - } - } else - builders[0].construct(this.type, pos.x, pos.z, pos.angle); -}; - -BuildingConstructionPlan.prototype.getCost = function() { - return this.cost; -}; - -BuildingConstructionPlan.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 = Map.createObstructionMap(gameState,template); - - //obstructionMap.dumpIm(template.buildCategory() + "_obstructions.png"); - - if (template.buildCategory() !== "Dock") - obstructionMap.expandInfluences(); - - // Compute each tile's closeness to friendly structures: - - var friendlyTiles = new Map(gameState); - - var alreadyHasHouses = false; - - // If a position was specified then place the building as close to it as possible - if (this.position){ - var x = Math.round(this.position[0] / cellSize); - var z = Math.round(this.position[1] / cellSize); - friendlyTiles.addInfluence(x, z, 200); - } else { - // No position was specified so try and find a sensible place to build - gameState.getOwnEntities().forEach(function(ent) { - if (ent.hasClass("Structure")) { - var infl = 32; - if (ent.hasClass("CivCentre")) - infl *= 4; - - var pos = ent.position(); - var x = Math.round(pos[0] / cellSize); - var z = Math.round(pos[1] / cellSize); - - if (ent.buildCategory() == "Wall") { // no real blockers, but can't build where they are - friendlyTiles.addInfluence(x, z, 2,-1000); - return; - } - - if (template._template.BuildRestrictions.Category === "Field"){ - if (ent.resourceDropsiteTypes() && ent.resourceDropsiteTypes().indexOf("food") !== -1){ - if (ent.hasClass("CivCentre")) - friendlyTiles.addInfluence(x, z, infl/4, infl); - else - friendlyTiles.addInfluence(x, z, infl, infl); - - } - }else{ - if (template.genericName() == "House" && ent.genericName() == "House") { - friendlyTiles.addInfluence(x, z, 15.0,20,'linear'); // houses are close to other houses - alreadyHasHouses = true; - } else if (template.hasClass("GarrisonFortress") && ent.genericName() == "House") - { - friendlyTiles.addInfluence(x, z, 30, -50); - } else if (template.genericName() == "House") { - friendlyTiles.addInfluence(x, z, Math.ceil(infl/2.0),infl); // houses are farther away from other buildings but houses - friendlyTiles.addInfluence(x, z, Math.ceil(infl/4.0),-infl/2.0); // houses are farther away from other buildings but houses - } else if (template.hasClass("GarrisonFortress")) - { - friendlyTiles.addInfluence(x, z, 20, 10); - friendlyTiles.addInfluence(x, z, 10, -40, 'linear'); - } else if (ent.genericName() != "House") // houses have no influence on other buildings - { - friendlyTiles.addInfluence(x, z, infl); - //avoid building too close to each other if possible. - friendlyTiles.addInfluence(x, z, 5, -5, 'linear'); - } - // 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") && template.genericName() != "House"){ - friendlyTiles.addInfluence(x, z, Math.floor(infl/8), Math.floor(-infl/2)); - } else if (ent.hasClass("CivCentre")) { - friendlyTiles.addInfluence(x, z, infl/3.0, infl + 1); - friendlyTiles.addInfluence(x, z, Math.ceil(infl/5.0), -(infl/2.0), 'linear'); - } - } - } - }); - } - - //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.genericName() == "Field") - radius = Math.ceil(template.obstructionRadius() / cellSize) - 0.4; - else if (template.hasClass("GarrisonFortress")) - radius = Math.ceil(template.obstructionRadius() / cellSize) + 2; - else if (template.buildCategory() === "Dock") - radius = 1;//Math.floor(template.obstructionRadius() / cellSize); - else if (!template.hasClass("DropsiteWood") && !template.hasClass("DropsiteStone") && !template.hasClass("DropsiteMetal")) - 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.genericName() == "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; - - // default angle - var angle = 3*Math.PI/4; - - return { - "x" : x, - "z" : z, - "angle" : angle - }; -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-building.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/defence.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/defence.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/defence.js (nonexistent) @@ -1,830 +0,0 @@ -// directly imported from Marilyn, with slight modifications to work with qBot. - -function Defence(){ - this.defenceRatio = Config.Defence.defenceRatio;// How many defenders we want per attacker. Need to balance fewer losses vs. lost economy - // note: the choice should be a no-brainer most of the time: better deflect the attack. - // This is also sometimes forcebly overcome by the defense manager. - this.armyCompactSize = Config.Defence.armyCompactSize; // a bit more than 40 wide in diameter - this.armyBreakawaySize = Config.Defence.armyBreakawaySize; // a bit more than 45 wide in diameter - - this.totalAttackNb = 0; // used for attack IDs - this.attacks = []; - this.toKill = []; - - - // keeps a list of targeted enemy at instant T - this.enemyArmy = {}; // array of players, storing for each an array of armies. - this.attackerCache = {}; - this.listOfEnemies = {}; - this.listedEnemyCollection = null; // entity collection of this.listOfEnemies - - // Some Stats - this.nbAttackers = 0; - this.nbDefenders = 0; - - // Caching variables - this.totalArmyNB = 0; - this.enemyUnits = {}; - this.enemyArmyLoop = {}; - // boolean 0/1 that's for optimization - this.attackerCacheLoopIndicator = 0; - - // this is a list of units to kill. They should be gaia animals, or lonely units. Works the same as listOfEnemies, ie an entityColelction which I'll have to cleanup - this.listOfWantedUnits = {}; - this.WantedUnitsAttacker = {}; // same as attackerCache. - - this.defenders = null; - this.idleDefs = null; -} - -// DO NOTE: the Defence manager, when it calls for Defence, makes the military manager go into "Defence mode"... This makes it not update any plan that's started or not. -// This allows the Defence manager to take units from the plans for Defence. - -// Defcon levels -// 5: no danger whatsoever detected -// 4: a few enemy units are being dealt with, but nothing too dangerous. -// 3: A reasonnably sized enemy army is being dealt with, but it should not be a problem. -// 2: A big enemy army is in the base, but we are not outnumbered -// 1: Huge army in the base, outnumbering us. - - -Defence.prototype.update = function(gameState, events, militaryManager){ - - Engine.ProfileStart("Defence Manager"); - - // a litlle cache-ing - if (!this.idleDefs) { - var filter = Filters.and(Filters.byMetadata(PlayerID, "role", "defence"), Filters.isIdle()); - this.idleDefs = gameState.getOwnEntities().filter(filter); - this.idleDefs.registerUpdates(); - } - if (!this.defenders) { - var filter = Filters.byMetadata(PlayerID, "role", "defence"); - this.defenders = gameState.getOwnEntities().filter(filter); - this.defenders.registerUpdates(); - } - /*if (!this.listedEnemyCollection) { - var filter = Filters.byMetadata(PlayerID, "listed-enemy", true); - this.listedEnemyCollection = gameState.getEnemyEntities().filter(filter); - this.listedEnemyCollection.registerUpdates(); - } - this.myBuildings = gameState.getOwnEntities().filter(Filters.byClass("Structure")).toEntityArray(); - this.myUnits = gameState.getOwnEntities().filter(Filters.byClass("Unit")); - */ - var filter = Filters.and(Filters.byClassesOr(["CitizenSoldier", "Hero", "Champion", "Siege"]), Filters.byOwner(PlayerID)); - this.myUnits = gameState.updatingGlobalCollection("player-" +PlayerID + "-soldiers", filter); - - filter = Filters.and(Filters.byClass("Structure"), Filters.byOwner(PlayerID)); - this.myBuildings = gameState.updatingGlobalCollection("player-" +PlayerID + "-structures", filter); - - this.territoryMap = Map.createTerritoryMap(gameState); // used by many func - - // First step: we deal with enemy armies, those are the highest priority. - this.defendFromEnemies(gameState, events, militaryManager); - - // second step: we loop through messages, and sort things as needed (dangerous buildings, attack by animals, ships, lone units, whatever). - // TODO : a lot. - this.MessageProcess(gameState,events,militaryManager); - - this.DealWithWantedUnits(gameState,events,militaryManager); - - /* - var self = this; - // putting unneeded units at rest - this.idleDefs.forEach(function(ent) { - if (ent.getMetadata(PlayerID, "formerrole")) - ent.setMetadata(PlayerID, "role", ent.getMetadata(PlayerID, "formerrole") ); - else - ent.setMetadata(PlayerID, "role", "worker"); - ent.setMetadata(PlayerID, "subrole", undefined); - self.nbDefenders--; - });*/ - - Engine.ProfileStop(); - - return; -}; -/* -// returns armies that are still seen as dangerous (in the LOS of any of my buildings for now) -Defence.prototype.reevaluateDangerousArmies = function(gameState, armies) { - var stillDangerousArmies = {}; - for (var i in armies) { - var pos = armies[i].getCentrePosition(); - if (pos === undefined) - - if (+this.territoryMap.point(pos) - 64 === +PlayerID) { - stillDangerousArmies[i] = armies[i]; - continue; - } - for (var o in this.myBuildings) { - // if the armies out of my buildings LOS (with a little more, because we're cheating right now and big armies could go undetected) - if (inRange(pos, this.myBuildings[o].position(),this.myBuildings[o].visionRange()*this.myBuildings[o].visionRange() + 2500)) { - stillDangerousArmies[i] = armies[i]; - break; - } - } - } - return stillDangerousArmies; -} -// returns armies we now see as dangerous, ie in my territory -Defence.prototype.evaluateArmies = function(gameState, armies) { - var DangerousArmies = {}; - for (var i in armies) { - if (armies[i].getCentrePosition() && +this.territoryMap.point(armies[i].getCentrePosition()) - 64 === +PlayerID) { - DangerousArmies[i] = armies[i]; - } - } - return DangerousArmies; -}*/ -// Incorporates an entity in an army. If no army fits, it creates a new one around this one. -// an army is basically an entity collection. -Defence.prototype.armify = function(gameState, entity, militaryManager, minNBForArmy) { - if (entity.position() === undefined) - return; - if (this.enemyArmy[entity.owner()] === undefined) - { - this.enemyArmy[entity.owner()] = {}; - } else { - for (var armyIndex in this.enemyArmy[entity.owner()]) - { - var army = this.enemyArmy[entity.owner()][armyIndex]; - if (army.getCentrePosition() === undefined) - { - } else { - if (SquareVectorDistance(army.getCentrePosition(), entity.position()) < this.armyCompactSize) - { - entity.setMetadata(PlayerID, "inArmy", armyIndex); - army.addEnt(entity); - return; - } - } - } - } - if (militaryManager) - { - var self = this; - var close = militaryManager.enemyWatchers[entity.owner()].enemySoldiers.filter(Filters.byDistance(entity.position(), self.armyCompactSize)); - if (!minNBForArmy || close.length >= minNBForArmy) - { - // if we're here, we need to create an army for it, and freeze it to make sure no unit will be added automatically - var newArmy = new EntityCollection(gameState.sharedScript, {}, [Filters.byOwner(entity.owner())]); - newArmy.addEnt(entity); - newArmy.freeze(); - newArmy.registerUpdates(); - entity.setMetadata(PlayerID, "inArmy", this.totalArmyNB); - this.enemyArmy[entity.owner()][this.totalArmyNB] = newArmy; - close.forEach(function (ent) { //}){ - if (ent.position() !== undefined && self.reevaluateEntity(gameState, ent)) - { - ent.setMetadata(PlayerID, "inArmy", self.totalArmyNB); - self.enemyArmy[ent.owner()][self.totalArmyNB].addEnt(ent); - } - }); - this.totalArmyNB++; - } - } else { - // if we're here, we need to create an army for it, and freeze it to make sure no unit will be added automatically - var newArmy = new EntityCollection(gameState.sharedScript, {}, [Filters.byOwner(entity.owner())]); - newArmy.addEnt(entity); - newArmy.freeze(); - newArmy.registerUpdates(); - entity.setMetadata(PlayerID, "inArmy", this.totalArmyNB); - this.enemyArmy[entity.owner()][this.totalArmyNB] = newArmy; - this.totalArmyNB++; - } - return; -} -// Returns if a unit should be seen as dangerous or not. -Defence.prototype.evaluateRawEntity = function(gameState, entity) { - if (entity.position && +this.territoryMap.point(entity.position) - 64 === +PlayerID && entity._template.Attack !== undefined) - return true; - return false; -} -Defence.prototype.evaluateEntity = function(gameState, entity) { - if (!entity.position()) - return false; - if (this.territoryMap.point(entity.position()) - 64 === entity.owner() || entity.attackTypes() === undefined) - return false; - - for (var i in this.myBuildings._entities) - { - if (!this.myBuildings._entities[i].hasClass("ConquestCritical")) - continue; - if (SquareVectorDistance(this.myBuildings._entities[i].position(), entity.position()) < 6000) - return true; - } - return false; -} -// returns false if the unit is in its territory -Defence.prototype.reevaluateEntity = function(gameState, entity) { - if ( (entity.position() && +this.territoryMap.point(entity.position()) - 64 === +entity.owner()) || entity.attackTypes() === undefined) - return false; - return true; -} -// This deals with incoming enemy armies, setting the defcon if needed. It will take new soldiers, and assign them to attack -// TODO: still is still pretty dumb, it could use improvements. -Defence.prototype.defendFromEnemies = function(gameState, events, militaryManager) { - var self = this; - - // New, faster system will loop for enemy soldiers, and also females on occasions ( TODO ) - // if a dangerous unit is found, it will check for neighbors and make them into an "army", an entityCollection - // > updated against owner, for the day when I throw healers in the deal. - // armies are checked against each other now and then to see if they should be merged, and units in armies are checked to see if they should be taken away from the army. - // We keep a list of idle defenders. For any new attacker, we'll check if we have any idle defender available, and if not, we assign available units. - // At the end of each turn, if we still have idle defenders, we either assign them to neighboring units, or we release them. - - var nbOfAttackers = 0; // actually new attackers. - var newEnemies = []; - - // clean up using events. - for each(var evt in events) - { - if (evt.type == "Destroy") - { - if (this.listOfEnemies[evt.msg.entity] !== undefined) - { - if (this.attackerCache[evt.msg.entity] !== undefined) { - this.attackerCache[evt.msg.entity].forEach(function(ent) { ent.stopMoving(); }); - delete self.attackerCache[evt.msg.entity]; - } - delete this.listOfEnemies[evt.msg.entity]; - this.nbAttackers--; - } else if (evt.msg.entityObj && evt.msg.entityObj.owner() === PlayerID && evt.msg.metadata[PlayerID] && evt.msg.metadata[PlayerID]["role"] - && evt.msg.metadata[PlayerID]["role"] === "defence") - { - // lost a brave man there. - this.nbDefenders--; - } - } - } - - // Optimizations: this will slowly iterate over all units (saved at an instant T) and all armies. - // It'll add new units if they are now dangerous and were not before - // It'll also deal with cleanup of armies. - // When it's finished it'll start over. - for (var enemyID in this.enemyArmy) - { - //this.enemyUnits[enemyID] = militaryManager.enemyWatchers[enemyID].getAllEnemySoldiers(); - if (this.enemyUnits[enemyID] === undefined || this.enemyUnits[enemyID].length === 0) - { - this.enemyUnits[enemyID] = militaryManager.enemyWatchers[enemyID].enemySoldiers.toEntityArray(); - } else { - // we have some units still to check in this array. Check 15 (TODO: DIFFLEVEL) - // Note: given the way memory works, if the entity has been recently deleted, its reference may still exist. - // and this.enemyUnits[enemyID][0] may still point to that reference, "reviving" the unit. - // So we've got to make sure it's not supposed to be dead. - for (var check = 0; check < 20; check++) - { - if (this.enemyUnits[enemyID].length > 0 && gameState.getEntityById(this.enemyUnits[enemyID][0].id()) !== undefined) - { - if (this.enemyUnits[enemyID][0].getMetadata(PlayerID, "inArmy") !== undefined) - { - this.enemyUnits[enemyID].splice(0,1); - } else { - var dangerous = this.evaluateEntity(gameState, this.enemyUnits[enemyID][0]); - if (dangerous) - this.armify(gameState, this.enemyUnits[enemyID][0], militaryManager,2); - this.enemyUnits[enemyID].splice(0,1); - } - } else if (this.enemyUnits[enemyID].length > 0 && gameState.getEntityById(this.enemyUnits[enemyID][0].id()) === undefined) - { - this.enemyUnits[enemyID].splice(0,1); - } - } - } - // okay then we'll check one of the armies - // creating the array to iterate over. - if (this.enemyArmyLoop[enemyID] === undefined || this.enemyArmyLoop[enemyID].length === 0) - { - this.enemyArmyLoop[enemyID] = []; - for (var i in this.enemyArmy[enemyID]) - this.enemyArmyLoop[enemyID].push([this.enemyArmy[enemyID][i],i]); - } - // and now we check the last known army. - if (this.enemyArmyLoop[enemyID].length !== 0) { - var army = this.enemyArmyLoop[enemyID][0][0]; - var position = army.getCentrePosition(); - - if (!position) - { - var index = this.enemyArmyLoop[enemyID][0][1]; - delete this.enemyArmy[enemyID][index]; - this.enemyArmyLoop[enemyID].splice(0,1); - } else { - army.forEach(function (ent) { //}){ - // check if the unit is a breakaway - if (ent.position() && SquareVectorDistance(position, ent.position()) > self.armyBreakawaySize) - { - ent.setMetadata(PlayerID, "inArmy", undefined); - army.removeEnt(ent); - if (self.evaluateEntity(gameState,ent)) - self.armify(gameState,ent); - } else { - // check if we have registered that unit already. - if (self.listOfEnemies[ent.id()] === undefined) { - self.listOfEnemies[ent.id()] = new EntityCollection(gameState.sharedScript, {}, [Filters.byOwner(ent.owner())]); - self.listOfEnemies[ent.id()].freeze(); - self.listOfEnemies[ent.id()].addEnt(ent); - self.listOfEnemies[ent.id()].registerUpdates(); - - self.attackerCache[ent.id()] = self.myUnits.filter(Filters.byTargetedEntity(ent.id())); - self.attackerCache[ent.id()].registerUpdates(); - nbOfAttackers++; - self.nbAttackers++; - newEnemies.push(ent); - } else if (self.attackerCache[ent.id()] === undefined || self.attackerCache[ent.id()].length == 0) { - nbOfAttackers++; - newEnemies.push(ent); - } else if (!self.reevaluateEntity(gameState,ent)) - { - ent.setMetadata(PlayerID, "inArmy", undefined); - army.removeEnt(ent); - if (self.attackerCache[ent.id()] !== undefined) - { - self.attackerCache[ent.id()].forEach(function(ent) { ent.stopMoving(); }); - delete self.attackerCache[ent.id()]; - delete self.listOfEnemies[ent.id()]; - self.nbAttackers--; - } - } - } - }); - // TODO: check if the army itself is not dangerous anymore. - this.enemyArmyLoop[enemyID].splice(0,1); - } - } - - // okay so now the army update is done. - } - - // Reordering attack because the pathfinder is for now not dynamically updated - for (var o in this.attackerCache) { - if ((this.attackerCacheLoopIndicator + o) % 2 === 0) { - this.attackerCache[o].forEach(function (ent) { - ent.attack(+o); - }); - } - } - this.attackerCacheLoopIndicator++; - this.attackerCacheLoopIndicator = this.attackerCacheLoopIndicator % 2; - - if (this.nbAttackers === 0 && this.nbDefenders === 0) { - // Release all our units - this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).forEach(function (defender) { //}){ - defender.stopMoving(); - if (defender.getMetadata(PlayerID, "formerrole")) - defender.setMetadata(PlayerID, "role", defender.getMetadata(PlayerID, "formerrole") ); - else - defender.setMetadata(PlayerID, "role", "worker"); - defender.setMetadata(PlayerID, "subrole", undefined); - self.nbDefenders--; - }); - militaryManager.ungarrisonAll(gameState); - militaryManager.unpauseAllPlans(gameState); - return; - } else if (this.nbAttackers === 0 && this.nbDefenders !== 0) { - // Release all our units - this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).forEach(function (defender) { //}){ - defender.stopMoving(); - if (defender.getMetadata(PlayerID, "formerrole")) - defender.setMetadata(PlayerID, "role", defender.getMetadata(PlayerID, "formerrole") ); - else - defender.setMetadata(PlayerID, "role", "worker"); - defender.setMetadata(PlayerID, "subrole", undefined); - self.nbDefenders--; - }); - militaryManager.ungarrisonAll(gameState); - militaryManager.unpauseAllPlans(gameState); - return; - } - if ( (this.nbDefenders < 4 && this.nbAttackers >= 5) || this.nbDefenders === 0) { - militaryManager.ungarrisonAll(gameState); - } - - //debug ("total number of attackers:"+ this.nbAttackers); - //debug ("total number of defenders:"+ this.nbDefenders); - - // If I'm here, I have a list of enemy units, and a list of my units attacking it (in absolute terms, I could use a list of any unit attacking it). - // now I'll list my idle defenders, then my idle soldiers that could defend. - // and then I'll assign my units. - // and then rock on. - - if (this.nbAttackers > 15){ - gameState.setDefcon(3); - } else if (this.nbAttackers > 5){ - gameState.setDefcon(4); - } - - // we're having too many. Release those that attack units already dealt with, or idle ones. - if (this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).length > nbOfAttackers*this.defenceRatio*1.2) { - this.myUnits.filter(Filters.byMetadata(PlayerID, "role","defence")).forEach(function (defender) { //}){ - if ( defender.isIdle() || (defender.unitAIOrderData() && defender.unitAIOrderData()["target"])) { - if ( defender.isIdle() || (self.attackerCache[defender.unitAIOrderData()["target"]] && self.attackerCache[defender.unitAIOrderData()["target"]].length > 3)) { - // okay release me. - defender.stopMoving(); - if (defender.getMetadata(PlayerID, "formerrole")) - defender.setMetadata(PlayerID, "role", defender.getMetadata(PlayerID, "formerrole") ); - else - defender.setMetadata(PlayerID, "role", "worker"); - defender.setMetadata(PlayerID, "subrole", undefined); - self.nbDefenders--; - } - } - }); - } - - - var nonDefenders = this.myUnits.filter(Filters.or(Filters.not(Filters.byMetadata(PlayerID, "role","defence")),Filters.isIdle())); - nonDefenders = nonDefenders.filter(Filters.not(Filters.byClass("Female"))); - nonDefenders = nonDefenders.filter(Filters.not(Filters.byMetadata(PlayerID, "subrole","attacking"))); - var defenceRatio = this.defenceRatio; - - if (newEnemies.length + this.nbAttackers > (this.nbDefenders + nonDefenders.length) * 0.8 && this.nbAttackers > 9) - gameState.setDefcon(2); - - if (newEnemies.length + this.nbAttackers > (this.nbDefenders + nonDefenders.length) * 1.5 && this.nbAttackers > 5) - gameState.setDefcon(1); - - //debug ("newEnemies.length "+ newEnemies.length); - //debug ("nonDefenders.length "+ nonDefenders.length); - - if (gameState.defcon() > 3) - militaryManager.unpauseAllPlans(gameState); - - if ( (nonDefenders.length + this.nbDefenders > newEnemies.length + this.nbAttackers) - || this.nbDefenders + nonDefenders.length < 4) - { - var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray(); - buildings.forEach( function (struct) { - if (struct.garrisoned() && struct.garrisoned().length) - struct.unloadAll(); - }); - }; - - if (newEnemies.length === 0) - return; - - /* - if (gameState.defcon() < 2 && (this.nbAttackers-this.nbDefenders) > 15) - { - militaryManager.pauseAllPlans(gameState); - } else if (gameState.defcon() < 3 && this.nbDefenders === 0 && newEnemies.length === 0) { - militaryManager.ungarrisonAll(gameState); - }*/ - - // A little sorting to target sieges/champions first. - newEnemies.sort (function (a,b) { - var vala = 1; - var valb = 1; - if (a.hasClass("Siege")) - vala = 10; - else if (a.hasClass("Champion") || a.hasClass("Hero")) - vala = 5; - if (b.hasClass("Siege")) - valb = 10; - else if (b.hasClass("Champion") || b.hasClass("Hero")) - valb = 5; - return valb - vala; - }); - - // For each enemy, we'll pick two units. - for each (var enemy in newEnemies) { - if (nonDefenders.length === 0 || self.nbDefenders >= self.nbAttackers * 1.8) - break; - // garrisoned. - if (enemy.position() === undefined) - continue; - - var assigned = self.attackerCache[enemy.id()].length; - - var defRatio = defenceRatio; - if (enemy.hasClass("Siege")) - defRatio *= 1.2; - - if (assigned >= defRatio) - return; - - // We'll sort through our units that can legitimately attack. - var data = []; - for (var id in nonDefenders._entities) - { - var ent = nonDefenders._entities[id]; - if (ent.position()) - data.push([id, ent, SquareVectorDistance(enemy.position(), ent.position())]); - } - // refine the defenders we want. Since it's the distance squared, it has the effect - // of tending to always prefer closer units, though this refinement should change it slighty. - data.sort(function (a, b) { - var vala = a[2]; - var valb = b[2]; - - // don't defend with siege units unless enemy is also a siege unit. - if (a[1].hasClass("Siege") && !enemy.hasClass("Siege")) - vala *= 9; - if (b[1].hasClass("Siege") && !enemy.hasClass("Siege")) - valb *= 9; - // If it's a siege unit, We basically ignore units that only deal pierce damage. - if (enemy.hasClass("Siege") && a[1].attackStrengths("Melee") !== undefined) - vala /= (a[1].attackStrengths("Melee")["hack"] + a[1].attackStrengths("Melee")["crush"]); - if (enemy.hasClass("Siege") && b[1].attackStrengths("Melee") !== undefined) - valb /= (b[1].attackStrengths("Melee")["hack"] + b[1].attackStrengths("Melee")["crush"]); - // If it's a counter, it's better. - if (a[1].countersClasses(b[1].classes())) - vala *= 0.1; // quite low but remember it's squared distance. - if (b[1].countersClasses(a[1].classes())) - valb *= 0.1; - // If the unit is idle, we prefer. ALso if attack plan. - if ((a[1].isIdle() || a[1].getMetadata(PlayerID, "plan") !== undefined) && !a[1].hasClass("Siege")) - vala *= 0.15; - if ((b[1].isIdle() || b[1].getMetadata(PlayerID, "plan") !== undefined) && !b[1].hasClass("Siege")) - valb *= 0.15; - return (vala - valb); }); - - var ret = {}; - for each (var val in data.slice(0, Math.min(nonDefenders._length, defRatio - assigned))) - ret[val[0]] = val[1]; - - var defs = new EntityCollection(nonDefenders._ai, ret); - - // successfully sorted - defs.forEach(function (defender) { //}){ - if (defender.getMetadata(PlayerID, "plan") != undefined && (gameState.defcon() < 4 || defender.getMetadata(PlayerID,"subrole") == "walking")) - militaryManager.pausePlan(gameState, defender.getMetadata(PlayerID, "plan")); - //debug ("Against " +enemy.id() + " Assigning " + defender.id()); - if (defender.getMetadata(PlayerID, "role") == "worker" || defender.getMetadata(PlayerID, "role") == "attack") - defender.setMetadata(PlayerID, "formerrole", defender.getMetadata(PlayerID, "role")); - defender.setMetadata(PlayerID, "role","defence"); - defender.setMetadata(PlayerID, "subrole","defending"); - defender.attack(+enemy.id()); - defender._entity.idle = false; // hack to prevent a bug as informations aren't updated during a turn - nonDefenders.updateEnt(defender); - assigned++; - self.nbDefenders++; - }); - - /*if (gameState.defcon() <= 3) - { - // let's try to garrison neighboring females. - var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray(); - var females = gameState.getOwnEntities().filter(Filters.byClass("Support")); - - var cache = {}; - var garrisoned = false; - females.forEach( function (ent) { //}){ - garrisoned = false; - if (ent.position()) - { - if (SquareVectorDistance(ent.position(), enemy.position()) < 3500) - { - for (var i in buildings) - { - var struct = buildings[i]; - if (!cache[struct.id()]) - cache[struct.id()] = 0; - if (struct.garrisoned() && struct.garrisonMax() - struct.garrisoned().length - cache[struct.id()] > 0) - { - garrisoned = true; - ent.garrison(struct); - cache[struct.id()]++; - break; - } - } - if (!garrisoned) { - ent.flee(enemy); - ent.setMetadata(PlayerID,"fleeing", gameState.getTimeElapsed()); - } - } - } - }); - }*/ - } - - return; -} - -// this processes the attackmessages -// So that a unit that gets attacked will not be completely dumb. -// warning: huge levels of indentation coming. -Defence.prototype.MessageProcess = function(gameState,events, militaryManager) { - var self = this; - - for (var key in events){ - var e = events[key]; - if (e.type === "Attacked" && e.msg){ - if (gameState.isEntityOwn(gameState.getEntityById(e.msg.target))) { - var attacker = gameState.getEntityById(e.msg.attacker); - var ourUnit = gameState.getEntityById(e.msg.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) { - // note: our unit can already by dead by now... We'll then have to rely on the enemy to react. - // if we're not on enemy territory - var territory = +this.territoryMap.point(attacker.position()) - 64; - - // we do not consider units that are defenders, and we do not consider units that are part of an attacking attack plan - // (attacking attacking plans are dealing with threats on their own). - if (ourUnit !== undefined && (ourUnit.getMetadata(PlayerID, "role") == "defence" || ourUnit.getMetadata(PlayerID, "role") == "attack")) - continue; - - // let's check for animals - if (attacker.owner() == 0) { - // if our unit is still alive, we make it react - // in this case we attack. - if (ourUnit !== undefined) { - if (ourUnit.hasClass("Unit") && !ourUnit.hasClass("Support")) - ourUnit.attack(e.msg.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(); - } - } // preliminary check: we do not count attacked military units (for sanity for now, TODO). - else if ( (territory != attacker.owner() && ourUnit.hasClass("Support")) || (!ourUnit.hasClass("Support") && territory == PlayerID)) - { - // Also 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. - if (!attacker.hasClass("Female") && !attacker.hasClass("Ship")) { - // 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 = militaryManager.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 (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 && 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.msg.attacker); - } - } - } - } - } - } - } - } - } -}; // nice sets of closing brackets, isn't it? - -// At most, this will put defcon to 4 -Defence.prototype.DealWithWantedUnits = function(gameState, events, militaryManager) { - //if (gameState.defcon() < 3) - // return; - - var self = this; - - var nbOfAttackers = 0; - var nbOfDealtWith = 0; - - // clean up before adding new units (slight speeding up, since new units can't already be dead) - for (var i in this.listOfWantedUnits) { - if (this.listOfWantedUnits[i].length === 0 || this.listOfEnemies[i] !== undefined) { // unit died/was converted/is already dealt with as part of an army - delete this.WantedUnitsAttacker[i]; - delete this.listOfWantedUnits[i]; - } else { - nbOfAttackers++; - if (this.WantedUnitsAttacker[i].length > 0) - nbOfDealtWith++; - } - } - - // note: we can deal with units the way we want because anyway, the Army Defender has already done its task. - // If there are still idle defenders here, it's because they aren't needed. - // I can also call other units: they're not needed. - // Note however that if the defcon level is too high, this won't do anything because it's low priority. - // this also won't take units from attack managers - - if (nbOfAttackers === 0) - return; - - // at most, we'll deal with 3 enemies at once. - if (nbOfDealtWith >= 3) - return; - - // dynamic properties are not updated nearly fast enough here so a little caching - var addedto = {}; - - // we send 3 units to each target just to be sure. TODO refine. - // we do not use plan units - this.idleDefs.forEach(function(ent) { - if (nbOfDealtWith < 3 && nbOfAttackers > 0 && ent.getMetadata(PlayerID, "plan") == undefined) - for (var o in self.listOfWantedUnits) { - if ( (addedto[o] == undefined && self.WantedUnitsAttacker[o].length < 3) || (addedto[o] && self.WantedUnitsAttacker[o].length + addedto[o] < 3)) { - if (self.WantedUnitsAttacker[o].length === 0) - nbOfDealtWith++; - - ent.setMetadata(PlayerID, "formerrole", ent.getMetadata(PlayerID, "role")); - ent.setMetadata(PlayerID, "role","defence"); - ent.setMetadata(PlayerID, "subrole", "defending"); - ent.attack(+o); - if (addedto[o]) - addedto[o]++; - else - addedto[o] = 1; - break; - } - if (self.WantedUnitsAttacker[o].length == 3) - nbOfAttackers--; // we hav eenough units, mark this one as being OKAY - } - }); - - // still some undealt with attackers, recruit citizen soldiers - if (nbOfAttackers > 0 && nbOfDealtWith < 2) { - - gameState.setDefcon(4); - - var newSoldiers = gameState.getOwnEntitiesByRole("worker"); - newSoldiers.forEach(function(ent) { - // If we're not female, we attack - if (ent.hasClass("CitizenSoldier")) - if (nbOfDealtWith < 3 && nbOfAttackers > 0) - for (var o in self.listOfWantedUnits) { - if ( (addedto[o] == undefined && self.WantedUnitsAttacker[o].length < 3) || (addedto[o] && self.WantedUnitsAttacker[o].length + addedto[o] < 3)) { - if (self.WantedUnitsAttacker[o].length === 0) - nbOfDealtWith++; - ent.setMetadata(PlayerID, "formerrole", ent.getMetadata(PlayerID, "role")); - ent.setMetadata(PlayerID, "role","defence"); - ent.setMetadata(PlayerID, "subrole", "defending"); - ent.attack(+o); - if (addedto[o]) - addedto[o]++; - else - addedto[o] = 1; - break; - } - if (self.WantedUnitsAttacker[o].length == 3) - nbOfAttackers--; // we hav eenough units, mark this one as being OKAY - } - }); - } - return; -} Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/defence.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:executable ## -1 +0,0 ## -* \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/military.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/military.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/military.js (nonexistent) @@ -1,489 +0,0 @@ -/* - * Military Manager. - * Basically this deals with constructing defense and attack buildings, but it's not very developped yet. - * There's a lot of work still to do here. - * It also handles the attack plans (see attack_plan.js) - * Not completely cleaned up from the original version in qBot. - */ - -var MilitaryAttackManager = function() { - - this.fortressStartTime = 0; - this.fortressLapseTime = Config.Military.fortressLapseTime * 1000; - this.defenceBuildingTime = Config.Military.defenceBuildingTime * 1000; - this.attackPlansStartTime = Config.Military.attackPlansStartTime * 1000; - this.defenceManager = new Defence(); - - - this.TotalAttackNumber = 0; - this.upcomingAttacks = { "CityAttack" : [] }; - this.startedAttacks = { "CityAttack" : [] }; -}; - -MilitaryAttackManager.prototype.init = function(gameState) { - var civ = gameState.playerData.civ; - - // load units and buildings from the config files - - if (civ in Config.buildings.moderate){ - this.bModerate = Config.buildings.moderate[civ]; - }else{ - this.bModerate = Config.buildings.moderate['default']; - } - - if (civ in Config.buildings.advanced){ - this.bAdvanced = Config.buildings.advanced[civ]; - }else{ - this.bAdvanced = Config.buildings.advanced['default']; - } - - if (civ in Config.buildings.fort){ - this.bFort = Config.buildings.fort[civ]; - }else{ - this.bFort = Config.buildings.fort['default']; - } - - for (var i in this.bAdvanced){ - this.bAdvanced[i] = gameState.applyCiv(this.bAdvanced[i]); - } - for (var i in this.bFort){ - this.bFort[i] = gameState.applyCiv(this.bFort[i]); - } - - // TODO: figure out how to make this generic - for (var i in this.attackManagers){ - this.availableAttacks[i] = new this.attackManagers[i](gameState, this); - } - - var enemies = gameState.getEnemyEntities(); - var filter = Filters.byClassesOr(["CitizenSoldier", "Champion", "Hero", "Siege"]); - this.enemySoldiers = enemies.filter(filter); // TODO: cope with diplomacy changes - this.enemySoldiers.registerUpdates(); - - // each enemy watchers keeps a list of entity collections about the enemy it watches - // It also keeps track of enemy armies, merging/splitting as needed - this.enemyWatchers = {}; - this.ennWatcherIndex = []; - for (var i = 1; i <= 8; i++) - if (PlayerID != i && gameState.isPlayerEnemy(i)) { - this.enemyWatchers[i] = new enemyWatcher(gameState, i); - this.ennWatcherIndex.push(i); - this.defenceManager.enemyArmy[i] = []; - } - -}; - -// picks the best template based on parameters and classes -MilitaryAttackManager.prototype.findBestTrainableUnit = function(gameState, classes, parameters) { - var units = gameState.findTrainableUnits(classes); - - if (units.length === 0) - return undefined; - - - units.sort(function(a, b) { //}) { - var aDivParam = 0, bDivParam = 0; - var aTopParam = 0, bTopParam = 0; - for (var i in parameters) { - var param = parameters[i]; - - if (param[0] == "base") { - aTopParam = param[1]; - bTopParam = param[1]; - } - if (param[0] == "strength") { - aTopParam += getMaxStrength(a[1]) * param[1]; - bTopParam += getMaxStrength(b[1]) * param[1]; - } - if (param[0] == "siegeStrength") { - aTopParam += getMaxStrength(a[1], "Structure") * param[1]; - bTopParam += getMaxStrength(b[1], "Structure") * param[1]; - } - if (param[0] == "speed") { - aTopParam += a[1].walkSpeed() * param[1]; - bTopParam += b[1].walkSpeed() * param[1]; - } - - if (param[0] == "cost") { - aDivParam += a[1].costSum() * param[1]; - bDivParam += b[1].costSum() * param[1]; - } - if (param[0] == "canGather") { - // checking against wood, could be anything else really. - if (a[1].resourceGatherRates() && a[1].resourceGatherRates()["wood.tree"]) - aTopParam *= param[1]; - if (b[1].resourceGatherRates() && b[1].resourceGatherRates()["wood.tree"]) - bTopParam *= param[1]; - } - } - return -(aTopParam/(aDivParam+1)) + (bTopParam/(bDivParam+1)); - }); - return units[0][0]; -}; - -// Deals with building fortresses and towers. -// Currently build towers next to every useful dropsites. -// TODO: Fortresses are placed randomly atm. -MilitaryAttackManager.prototype.buildDefences = function(gameState, queues){ - - var workersNumber = gameState.getOwnEntitiesByRole("worker").filter(Filters.not(Filters.byHasMetadata(PlayerID,"plan"))).length; - - if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv('structures/{civ}_defense_tower')) - + queues.defenceBuilding.totalLength() < gameState.getEntityLimits()["DefenseTower"] && queues.defenceBuilding.totalLength() < 4 - && gameState.currentPhase() > 1 && queues.defenceBuilding.totalLength() < 3) { - gameState.getOwnEntities().forEach(function(dropsiteEnt) { - if (dropsiteEnt.resourceDropsiteTypes() && dropsiteEnt.getMetadata(PlayerID, "defenseTower") !== true - && (dropsiteEnt.getMetadata(PlayerID, "resource-quantity-wood") > 400 || dropsiteEnt.getMetadata(PlayerID, "resource-quantity-stone") > 500 - || dropsiteEnt.getMetadata(PlayerID, "resource-quantity-metal") > 500) ){ - var position = dropsiteEnt.position(); - if (position){ - queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, 'structures/{civ}_defense_tower', position)); - } - dropsiteEnt.setMetadata(PlayerID, "defenseTower", true); - } - }); - } - - var numFortresses = 0; - for (var i in this.bFort){ - numFortresses += gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bFort[i])); - } - - if (queues.defenceBuilding.totalLength() < 1 && (gameState.currentPhase() > 2 || gameState.isResearching("phase_city_generic"))) - { - if (workersNumber >= 80 && gameState.getTimeElapsed() > numFortresses * this.fortressLapseTime + this.fortressStartTime) - { - if (!this.fortressStartTime) - this.fortressStartTime = gameState.getTimeElapsed(); - queues.defenceBuilding.addItem(new BuildingConstructionPlan(gameState, this.bFort[0])); - debug ("Building a fortress"); - } - } - if (gameState.countEntitiesByType(gameState.applyCiv(this.bFort[i])) >= 1) { - // let's add a siege building plan to the current attack plan if there is none currently. - if (this.upcomingAttacks["CityAttack"].length !== 0) - { - var attack = this.upcomingAttacks["CityAttack"][0]; - if (!attack.unitStat["Siege"]) - { - // no minsize as we don't want the plan to fail at the last minute though. - var stat = { "priority" : 1.1, "minSize" : 0, "targetSize" : 4, "batchSize" : 2, "classes" : ["Siege"], - "interests" : [ ["siegeStrength", 3], ["cost",1] ] ,"templates" : [] }; - if (gameState.civ() == "cart" || gameState.civ() == "maur") - stat["classes"] = ["Elephant"]; - attack.addBuildOrder(gameState, "Siege", stat, true); - } - } - } -}; - -// Deals with constructing military buildings (barracks, stables…) -// They are mostly defined by Config.js. This is unreliable since changes could be done easily. -// TODO: We need to determine these dynamically. Also doesn't build fortresses since the above function does that. -// TODO: building placement is bad. Choice of buildings is also fairly dumb. -MilitaryAttackManager.prototype.constructTrainingBuildings = function(gameState, queues) { - Engine.ProfileStart("Build buildings"); - var workersNumber = gameState.getOwnEntitiesByRole("worker").filter(Filters.not(Filters.byHasMetadata(PlayerID, "plan"))).length; - - if (workersNumber > 30 && (gameState.currentPhase() > 1 || gameState.isResearching("phase_town"))) { - if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0])) + queues.militaryBuilding.totalLength() < 1) { - debug ("Trying to build barracks"); - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0])); - } - } - - if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0])) < 2 && workersNumber > 85) - if (queues.militaryBuilding.totalLength() < 1) - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0])); - - if (gameState.countEntitiesByType(gameState.applyCiv(this.bModerate[0])) === 2 && gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bModerate[0])) < 3 && workersNumber > 125) - if (queues.militaryBuilding.totalLength() < 1) - { - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0])); - if (gameState.civ() == "gaul" || gameState.civ() == "brit" || gameState.civ() == "iber") { - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0])); - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bModerate[0])); - } - } - //build advanced military buildings - if (workersNumber >= 75 && gameState.currentPhase() > 2){ - if (queues.militaryBuilding.totalLength() === 0){ - var inConst = 0; - for (var i in this.bAdvanced) - inConst += gameState.countFoundationsWithType(gameState.applyCiv(this.bAdvanced[i])); - if (inConst == 0 && this.bAdvanced && this.bAdvanced.length !== 0) { - var i = Math.floor(Math.random() * this.bAdvanced.length); - if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bAdvanced[i])) < 1){ - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i])); - } - } - } - } - if (gameState.civ() !== "gaul" && gameState.civ() !== "brit" && gameState.civ() !== "iber" && - workersNumber > 130 && gameState.currentPhase() > 2) - { - var Const = 0; - for (var i in this.bAdvanced) - Const += gameState.countEntitiesByType(gameState.applyCiv(this.bAdvanced[i])); - if (inConst == 1) { - var i = Math.floor(Math.random() * this.bAdvanced.length); - if (gameState.countEntitiesAndQueuedByType(gameState.applyCiv(this.bAdvanced[i])) < 1){ - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i])); - queues.militaryBuilding.addItem(new BuildingConstructionPlan(gameState, this.bAdvanced[i])); - } - } - } - - Engine.ProfileStop(); -}; - -// TODO: use pop(). Currently unused as this is too gameable. -MilitaryAttackManager.prototype.garrisonAllFemales = function(gameState) { - var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray(); - var females = gameState.getOwnEntities().filter(Filters.byClass("Support")); - - var cache = {}; - - females.forEach( function (ent) { - for (var i in buildings) - { - if (ent.position()) - { - var struct = buildings[i]; - if (!cache[struct.id()]) - cache[struct.id()] = 0; - if (struct.garrisoned() && struct.garrisonMax() - struct.garrisoned().length - cache[struct.id()] > 0) - { - ent.garrison(struct); - cache[struct.id()]++; - break; - } - } - } - }); - this.hasGarrisonedFemales = true; -}; -MilitaryAttackManager.prototype.ungarrisonAll = function(gameState) { - this.hasGarrisonedFemales = false; - var buildings = gameState.getOwnEntities().filter(Filters.byCanGarrison()).toEntityArray(); - buildings.forEach( function (struct) { - if (struct.garrisoned() && struct.garrisoned().length) - struct.unloadAll(); - }); -}; - -MilitaryAttackManager.prototype.pausePlan = function(gameState, planName) { - for (var attackType in this.upcomingAttacks) { - for (var i in this.upcomingAttacks[attackType]) { - var attack = this.upcomingAttacks[attackType][i]; - if (attack.getName() == planName) - attack.setPaused(gameState, true); - } - } - for (var attackType in this.startedAttacks) { - for (var i in this.startedAttacks[attackType]) { - var attack = this.startedAttacks[attackType][i]; - if (attack.getName() == planName) - attack.setPaused(gameState, true); - } - } -} -MilitaryAttackManager.prototype.unpausePlan = function(gameState, planName) { - for (var attackType in this.upcomingAttacks) { - for (var i in this.upcomingAttacks[attackType]) { - var attack = this.upcomingAttacks[attackType][i]; - if (attack.getName() == planName) - attack.setPaused(gameState, false); - } - } - for (var attackType in this.startedAttacks) { - for (var i in this.startedAttacks[attackType]) { - var attack = this.startedAttacks[attackType][i]; - if (attack.getName() == planName) - attack.setPaused(gameState, false); - } - } -} -MilitaryAttackManager.prototype.pauseAllPlans = function(gameState) { - for (var attackType in this.upcomingAttacks) { - for (var i in this.upcomingAttacks[attackType]) { - var attack = this.upcomingAttacks[attackType][i]; - attack.setPaused(gameState, true); - } - } - for (var attackType in this.startedAttacks) { - for (var i in this.startedAttacks[attackType]) { - var attack = this.startedAttacks[attackType][i]; - attack.setPaused(gameState, true); - } - } -} -MilitaryAttackManager.prototype.unpauseAllPlans = function(gameState) { - for (var attackType in this.upcomingAttacks) { - for (var i in this.upcomingAttacks[attackType]) { - var attack = this.upcomingAttacks[attackType][i]; - attack.setPaused(gameState, false); - } - } - for (var attackType in this.startedAttacks) { - for (var i in this.startedAttacks[attackType]) { - var attack = this.startedAttacks[attackType][i]; - attack.setPaused(gameState, false); - } - } -} -MilitaryAttackManager.prototype.update = function(gameState, queues, events) { - var self = this; - - Engine.ProfileStart("military update"); - - this.gameState = gameState; - - Engine.ProfileStart("Constructing military buildings and building defences"); - this.constructTrainingBuildings(gameState, queues); - - if(gameState.getTimeElapsed() > this.defenceBuildingTime) - this.buildDefences(gameState, queues); - Engine.ProfileStop(); - - this.defenceManager.update(gameState, events, this); - - Engine.ProfileStart("Looping through attack plans"); - // TODO: implement some form of check before starting a new attack plans. Sometimes it is not the priority. - if (1) { - for (var attackType in this.upcomingAttacks) { - for (var i = 0;i < this.upcomingAttacks[attackType].length; ++i) { - - var attack = this.upcomingAttacks[attackType][i]; - - // okay so we'll get the support plan - if (!attack.isStarted()) { - var updateStep = attack.updatePreparation(gameState, this,events); - - // now we're gonna check if the preparation time is over - if (updateStep === 1 || attack.isPaused() ) { - // just chillin' - } else if (updateStep === 0 || updateStep === 3) { - debug ("Military Manager: " +attack.getType() +" plan " +attack.getName() +" aborted."); - if (updateStep === 3) { - this.attackPlansEncounteredWater = true; - debug("No attack path found. Aborting."); - } - attack.Abort(gameState, this); - this.upcomingAttacks[attackType].splice(i--,1); - } else if (updateStep === 2) { - var chatText = "I am launching an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - if (Math.random() < 0.2) - chatText = "Attacking " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - else if (Math.random() < 0.3) - chatText = "I have sent an army against " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - else if (Math.random() < 0.3) - chatText = "I'm starting an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - gameState.ai.chatTeam(chatText); - - debug ("Military Manager: Starting " +attack.getType() +" plan " +attack.getName()); - attack.StartAttack(gameState,this); - this.startedAttacks[attackType].push(attack); - this.upcomingAttacks[attackType].splice(i--,1); - } - } else { - var chatText = "I am launching an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - if (Math.random() < 0.2) - chatText = "Attacking " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - else if (Math.random() < 0.3) - chatText = "I have sent an army against " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - else if (Math.random() < 0.3) - chatText = "I'm starting an attack against " + gameState.sharedScript.playersData[attack.targetPlayer].name + "."; - gameState.ai.chatTeam(chatText); - - debug ("Military Manager: Starting " +attack.getType() +" plan " +attack.getName()); - this.startedAttacks[attackType].push(attack); - this.upcomingAttacks[attackType].splice(i--,1); - } - } - } - } - for (var attackType in this.startedAttacks) { - for (var i = 0; i < this.startedAttacks[attackType].length; ++i) { - var attack = this.startedAttacks[attackType][i]; - // okay so then we'll update the attack. - if (!attack.isPaused()) - { - var remaining = attack.update(gameState,this,events); - if (remaining == 0 || remaining == undefined) { - debug ("Military Manager: " +attack.getType() +" plan " +attack.getName() +" is now finished."); - attack.Abort(gameState); - this.startedAttacks[attackType].splice(i--,1); - } - } - } - } - // Note: these indications of "rush" are currently unused. - if (gameState.ai.strategy === "rush" && this.startedAttacks["CityAttack"].length !== 0) { - // and then we revert. - gameState.ai.strategy = "normal"; - Config.Economy.femaleRatio = 0.4; - gameState.ai.modules.economy.targetNumWorkers = Math.max(Math.floor(gameState.getPopulationMax()*0.55), 1); - } else if (gameState.ai.strategy === "rush" && this.upcomingAttacks["CityAttack"].length === 0) - { - Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1, "rush") - this.TotalAttackNumber++; - this.upcomingAttacks["CityAttack"].push(Lalala); - debug ("Starting a little something"); - } else if (gameState.ai.strategy !== "rush") - { - // creating plans after updating because an aborted plan might be reused in that case. - if (gameState.countEntitiesByType(gameState.applyCiv(this.bModerate[0])) >= 1 && !this.attackPlansEncounteredWater - && gameState.getTimeElapsed() > this.attackPlansStartTime) { - if (gameState.countEntitiesByType(gameState.applyCiv("structures/{civ}_dock")) === 0 && gameState.ai.waterMap) - { - // wait till we get a dock. - } else { - // basically only the first plan, really. - if (this.upcomingAttacks["CityAttack"].length == 0 && (gameState.getTimeElapsed() < 12*60000 || Config.difficulty < 1)) { - var Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1); - if (Lalala.failed) - { - this.attackPlansEncounteredWater = true; // hack - } else { - debug ("Military Manager: Creating the plan " +this.TotalAttackNumber); - this.TotalAttackNumber++; - this.upcomingAttacks["CityAttack"].push(Lalala); - } - } else if (this.upcomingAttacks["CityAttack"].length == 0 && Config.difficulty !== 0) { - var Lalala = new CityAttack(gameState, this,this.TotalAttackNumber, -1, "superSized"); - if (Lalala.failed) - { - this.attackPlansEncounteredWater = true; // hack - } else { - debug ("Military Manager: Creating the super sized plan " +this.TotalAttackNumber); - this.TotalAttackNumber++; - this.upcomingAttacks["CityAttack"].push(Lalala); - } - } - } - } - } - - /* - // very old relic. This should be reimplemented someday so the code stays here. - - if (this.HarassRaiding && this.preparingRaidNumber + this.startedRaidNumber < 1 && gameState.getTimeElapsed() < 780000) { - var Lalala = new CityAttack(gameState, this,this.totalStartedAttackNumber, -1, "harass_raid"); - if (!Lalala.createSupportPlans(gameState, this, )) { - debug ("Military Manager: harrassing plan not a valid option"); - this.HarassRaiding = false; - } else { - debug ("Military Manager: Creating the harass raid plan " +this.totalStartedAttackNumber); - - this.totalStartedAttackNumber++; - this.preparingRaidNumber++; - this.currentAttacks.push(Lalala); - } - } - */ - - - Engine.ProfileStop(); - Engine.ProfileStop(); -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/military.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:executable ## -1 +0,0 ## -* \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue-manager.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue-manager.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue-manager.js (nonexistent) @@ -1,296 +0,0 @@ -// 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. -// -// The fact that there is an outqueue is mostly a relic of qBot. -// -// This system should be improved. It's probably not flexible enough. - -var QueueManager = function(queues, priorities) { - this.queues = queues; - this.priorities = priorities; - this.account = {}; - this.accounts = {}; - - // the sorting would need to be updated on priority change but there is currently none. - var self = this; - this.queueArrays = []; - for (var p in this.queues) { - this.account[p] = 0; - this.accounts[p] = new 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 = []; - -}; - -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; -}; - -QueueManager.prototype.futureNeeds = function(gameState, EcoManager) { - var needs = new Resources(); - // get ouy 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 < Math.min(2,queue.length()); ++j) - { - needs.add(queue.queue[j].getCost()); - } - } - if (EcoManager === false) { - return { - "food" : Math.max(needs.food - current.food, 0), - "wood" : Math.max(needs.wood - current.wood, 0), - "stone" : Math.max(needs.stone - current.stone, 0), - "metal" : Math.max(needs.metal - current.metal, 0) - }; - } else { - // Return predicted values minus the current stockpiles along with a base rater for all resources - return { - "food" : (Math.max(needs.food - current.food, 0) + EcoManager.baseNeed["food"])/2, - "wood" : (Math.max(needs.wood - current.wood, 0) + EcoManager.baseNeed["wood"])/2, - "stone" : (Math.max(needs.stone - current.stone, 0) + EcoManager.baseNeed["stone"])/2, - "metal" : (Math.max(needs.metal - current.metal, 0) + EcoManager.baseNeed["metal"])/2 - }; - } -}; - -QueueManager.prototype.printQueues = function(gameState){ - debug("OUTQUEUES"); - for (var i in this.queues){ - var qStr = ""; - var q = this.queues[i]; - if (q.outQueue.length > 0) - debug((i + ":")); - for (var j in q.outQueue){ - qStr = " " + q.outQueue[j].type + " "; - if (q.outQueue[j].number) - qStr += "x" + q.outQueue[j].number; - debug (qStr); - } - } - - debug("INQUEUES"); - for (var i in this.queues){ - var qStr = ""; - var q = this.queues[i]; - if (q.queue.length > 0) - debug((i + ":")); - for (var j in q.queue){ - qStr = " " + q.queue[j].type + " "; - if (q.queue[j].number) - qStr += "x" + q.queue[j].number; - debug (qStr); - } - } - debug ("Accounts"); - for (var p in this.accounts) - { - debug(p + ": " + uneval(this.accounts[p])); - } - debug("Needed Resources:" + uneval(this.futureNeeds(gameState,false))); - debug ("Current Resources:" + uneval(gameState.getResources())); - debug ("Available Resources:" + uneval(this.getAvailableResources(gameState))); -}; - -QueueManager.prototype.clear = function(){ - this.curItemQueue = []; - for (var i in this.queues) - this.queues[i].empty(); -}; - -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"); - - //if (gameState.ai.playedTurn % 10 === 0) - // this.printQueues(gameState); - - Engine.ProfileStart("Pick items from queues"); - - // TODO: this only pushes the first object. SHould probably try to push any possible object to maximize productivity. Perhaps a settinh? - // looking at queues in decreasing priorities and pushing to the current item queues. - for (var i in this.queueArrays) - { - var name = this.queueArrays[i][0]; - var queue = this.queueArrays[i][1]; - if (queue.length() > 0) - { - var item = queue.getNext(); - var total = new Resources(); - total.add(this.accounts[name]); - total.subtract(queue.outQueueCost()); - if (total.canAfford(item.getCost())) - { - queue.nextToOutQueue(); - } - } else if (queue.totalLength() === 0) { - this.accounts[name].reset(); - } - } - - var availableRes = this.getAvailableResources(gameState); - // assign some accounts to queues. This is done by priority, and by need. - for (var ress in availableRes) - { - if (availableRes[ress] > 0 && ress != "population") - { - 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 or the outqueue) - // 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) { - var outQueueCost = this.queues[j].outQueueCost(); - var queueCost = this.queues[j].queueCost(); - if (this.accounts[j][ress] < queueCost[ress] + outQueueCost[ress]) - { - // adding us to the list of queues that need an update. - tempPrio[j] = this.priorities[j]; - maxNeed[j] = outQueueCost[ress] + this.queues[j].getNext().getCost()[ress]; - // if we have enough of that resource for the outqueue and our first resource in the queue, diminish our priority. - if (this.accounts[j][ress] >= outQueueCost[ress] + this.queues[j].getNext().getCost()[ress]) - { - tempPrio[j] /= 2; - if (this.queues[j].length() !== 1) - { - var halfcost = this.queues[j].queue[1].getCost()[ress]*0.8; - maxNeed[j] += halfcost; - if (this.accounts[j][ress] >= outQueueCost[ress] + this.queues[j].getNext().getCost()[ress] + halfcost) - delete tempPrio[j]; - } - } - if (tempPrio[j]) - totalPriority += tempPrio[j]; - } - } - // 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 = Math.floor(tempPrio[j]/totalPriority * availableRes[ress]); - // let's check we're not adding too much. - var maxAdd = Math.min(maxNeed[j] - this.accounts[j][ress], toAdd); - this.accounts[j][ress] += maxAdd; - } - } - } - Engine.ProfileStop(); - - Engine.ProfileStart("Execute items"); - - var units_Techs_passed = 0; - // Handle output queues by executing items where possible - for (var p in this.queueArrays) { - var name = this.queueArrays[p][0]; - var queue = this.queueArrays[p][1]; - var next = queue.outQueueNext(); - if (!next) - continue; - if (next.category === "building") { - if (gameState.buildingsBuilt == 0) { - if (next.canExecute(gameState)) { - this.accounts[name].subtract(next.getCost()) - //debug ("Starting " + next.type + " substracted " + uneval(next.getCost())) - queue.executeNext(gameState); - gameState.buildingsBuilt += 1; - } - } - } else { - if (units_Techs_passed < 2 && queue.outQueueNext().canExecute(gameState)){ - //debug ("Starting " + next.type + " substracted " + uneval(next.getCost())) - this.accounts[name].subtract(next.getCost()) - queue.executeNext(gameState); - units_Techs_passed++; - } - } - if (units_Techs_passed >= 2) - continue; - } - Engine.ProfileStop(); - Engine.ProfileStop(); -}; - -QueueManager.prototype.addQueue = function(queueName, priority) { - if (this.queues[queueName] == undefined) { - this.queues[queueName] = new Queue(); - this.priorities[queueName] = priority; - this.account[queueName] = 0; - this.accounts[queueName] = new 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]]) }); - } -} -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.account[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]]) }); - } -} -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]]) }); -} - Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/queue-manager.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_Read Me.txt =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_Read Me.txt (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_Read Me.txt (nonexistent) @@ -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/qbot-wc 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-v3. - -(note: no saved game support as of yet). \ No newline at end of file Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_Read Me.txt ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/map-module.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/map-module.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/map-module.js (nonexistent) @@ -1,378 +0,0 @@ -const TERRITORY_PLAYER_MASK = 0x3F; - -//TODO: Make this cope with negative cell values -// This is by default a 16-bit map but can be adapted into 8-bit. -function Map(gameState, originalMap, actualCopy){ - // get the map to find out the correct dimensions - var gameMap = gameState.getMap(); - this.width = gameMap.width; - this.height = gameMap.height; - this.length = gameMap.data.length; - - this.maxVal = 65535; - - if (originalMap && actualCopy){ - this.map = new Uint16Array(this.length); - for (var i = 0; i < originalMap.length; ++i) - this.map[i] = originalMap[i]; - } else if (originalMap) { - this.map = originalMap; - } else { - this.map = new Uint16Array(this.length); - } - this.cellSize = gameState.cellSize; -} -Map.prototype.setMaxVal = function(val){ - this.maxVal = val; -}; - -Map.prototype.gamePosToMapPos = function(p){ - return [Math.floor(p[0]/this.cellSize), Math.floor(p[1]/this.cellSize)]; -}; - -Map.prototype.point = function(p){ - var q = this.gamePosToMapPos(p); - return this.map[q[0] + this.width * q[1]]; -}; - -// returns an 8-bit map. -Map.createObstructionMap = function(gameState, 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) - { - okay = false; - var i = x + y*passabilityMap.width; - var tilePlayer = (territoryMap.data[i] & TERRITORY_PLAYER_MASK); - - 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) > 500) - if ((passabilityMap.data[index2] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index2) > 500) - if ((passabilityMap.data[index3] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index3) > 500) - if ((passabilityMap.data[index4] & gameState.getPassabilityClassMask("default")) && gameState.ai.accessibility.getRegionSizei(index4) > 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; - } - if (gameState.ai.myIndex !== gameState.ai.accessibility.passMap[i]) - okay = false; - if (gameState.isPlayerEnemy(tilePlayer) && tilePlayer !== 0) - okay = false; - if ((passabilityMap.data[i] & (gameState.getPassabilityClassMask("building-shore") | gameState.getPassabilityClassMask("default")))) - 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] & TERRITORY_PLAYER_MASK); - var invalidTerritory = ( - (!buildOwn && tilePlayer == playerID) || - (!buildAlly && gameState.isPlayerAlly(tilePlayer) && tilePlayer != playerID) || - (!buildNeutral && tilePlayer == 0) || - (!buildEnemy && gameState.isPlayerEnemy(tilePlayer) && tilePlayer != 0) - ); - var tileAccessible = (gameState.ai.myIndex === gameState.ai.accessibility.passMap[i]); - if (placementType === "shore") - tileAccessible = true; - obstructionTiles[i] = (!tileAccessible || invalidTerritory || (passabilityMap.data[i] & obstructionMask)) ? 0 : 255; - } - } - - var map = new Map(gameState, obstructionTiles); - map.setMaxVal(255); - - if (template && template.buildDistance()){ - var minDist = template.buildDistance().MinDistance; - var category = template.buildDistance().FromCategory; - if (minDist !== undefined && category !== undefined){ - gameState.getOwnEntities().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; -}; - -Map.createTerritoryMap = function(gameState) { - var map = gameState.ai.territoryMap; - - var ret = new Map(gameState, map.data); - - ret.getOwner = function(p) { - return this.point(p) & TERRITORY_PLAYER_MASK; - } - ret.getOwnerIndex = function(p) { - return this.map[p] & TERRITORY_PLAYER_MASK; - } - return ret; -}; - -Map.prototype.addInfluence = function(cx, cy, maxDist, strength, type) { - strength = strength ? +strength : +maxDist; - type = type ? type : 'linear'; - - var x0 = Math.max(0, cx - maxDist); - var y0 = Math.max(0, cy - maxDist); - var x1 = Math.min(this.width, cx + maxDist); - var y1 = Math.min(this.height, cy + maxDist); - var maxDist2 = maxDist * maxDist; - - var str = 0.0; - switch (type){ - case 'linear': - str = +strength / +maxDist; - break; - case 'quadratic': - str = +strength / +maxDist2; - break; - case 'constant': - str = +strength; - break; - } - - for ( var y = y0; y < y1; ++y) { - for ( var x = x0; x < x1; ++x) { - var dx = x - cx; - var dy = y - cy; - var r2 = dx*dx + dy*dy; - if (r2 < maxDist2){ - var quant = 0; - switch (type){ - case 'linear': - var r = Math.sqrt(r2); - quant = str * (maxDist - r); - break; - case 'quadratic': - quant = str * (maxDist2 - r2); - break; - case 'constant': - quant = str; - break; - } - if (this.map[x + y * this.width] + quant < 0) - this.map[x + y * this.width] = 0; - else if (this.map[x + y * this.width] + quant > this.maxVal) - this.map[x + y * this.width] = this.maxVal; // avoids overflow. - else - this.map[x + y * this.width] += quant; - } - } - } -}; - -Map.prototype.multiplyInfluence = function(cx, cy, maxDist, strength, type) { - strength = strength ? +strength : +maxDist; - type = type ? type : 'constant'; - - var x0 = Math.max(0, cx - maxDist); - var y0 = Math.max(0, cy - maxDist); - var x1 = Math.min(this.width, cx + maxDist); - var y1 = Math.min(this.height, cy + maxDist); - var maxDist2 = maxDist * maxDist; - - var str = 0.0; - switch (type){ - case 'linear': - str = strength / maxDist; - break; - case 'quadratic': - str = strength / maxDist2; - break; - case 'constant': - str = strength; - break; - } - - for ( var y = y0; y < y1; ++y) { - for ( var x = x0; x < x1; ++x) { - var dx = x - cx; - var dy = y - cy; - var r2 = dx*dx + dy*dy; - if (r2 < maxDist2){ - var quant = 0; - switch (type){ - case 'linear': - var r = Math.sqrt(r2); - quant = str * (maxDist - r); - break; - case 'quadratic': - quant = str * (maxDist2 - r2); - break; - case 'constant': - quant = str; - break; - } - var machin = this.map[x + y * this.width] * quant; - if (machin < 0) - this.map[x + y * this.width] = 0; - else if (machin > this.maxVal) - this.map[x + y * this.width] = this.maxVal; - else - this.map[x + y * this.width] = machin; - } - } - } -}; -// doesn't check for overflow. -Map.prototype.setInfluence = function(cx, cy, maxDist, value) { - value = value ? value : 0; - - var x0 = Math.max(0, cx - maxDist); - var y0 = Math.max(0, cy - maxDist); - var x1 = Math.min(this.width, cx + maxDist); - var y1 = Math.min(this.height, cy + maxDist); - var maxDist2 = maxDist * maxDist; - - for ( var y = y0; y < y1; ++y) { - for ( var x = x0; x < x1; ++x) { - var dx = x - cx; - var dy = y - cy; - var r2 = dx*dx + dy*dy; - if (r2 < maxDist2){ - this.map[x + y * this.width] = value; - } - } - } -}; - -/** - * Make each cell's 16-bit/8-bit value at least one greater than each of its - * neighbours' values. (If the grid is initialised with 0s and 65535s or 255s, the - * result of each cell is its Manhattan distance to the nearest 0.) - */ -Map.prototype.expandInfluences = function() { - var w = this.width; - var h = this.height; - var grid = this.map; - for ( var y = 0; y < h; ++y) { - var min = this.maxVal; - for ( var x = 0; x < w; ++x) { - var g = grid[x + y * w]; - if (g > min) - grid[x + y * w] = min; - else if (g < min) - min = g; - ++min; - } - - for ( var x = w - 2; x >= 0; --x) { - var g = grid[x + y * w]; - if (g > min) - grid[x + y * w] = min; - else if (g < min) - min = g; - ++min; - } - } - - for ( var x = 0; x < w; ++x) { - var min = this.maxVal; - for ( var y = 0; y < h; ++y) { - var g = grid[x + y * w]; - if (g > min) - grid[x + y * w] = min; - else if (g < min) - min = g; - ++min; - } - - for ( var y = h - 2; y >= 0; --y) { - var g = grid[x + y * w]; - if (g > min) - grid[x + y * w] = min; - else if (g < min) - min = g; - ++min; - } - } -}; - -Map.prototype.findBestTile = function(radius, obstructionTiles){ - // Find the best non-obstructed tile - var bestIdx = 0; - var bestVal = -1; - for ( var i = 0; i < this.length; ++i) { - if (obstructionTiles.map[i] > radius) { - var v = this.map[i]; - if (v > bestVal) { - bestVal = v; - bestIdx = i; - } - } - } - - return [bestIdx, bestVal]; -}; - -// add to current map by the parameter map pixelwise -Map.prototype.add = function(map){ - for (var i = 0; i < this.length; ++i) { - if (this.map[i] + map.map[i] < 0) - this.map[i] = 0; - else if (this.map[i] + map.map[i] > this.maxVal) - this.map[i] = this.maxVal; - else - this.map[i] += map.map[i]; - } -}; - -Map.prototype.dumpIm = function(name, threshold){ - name = name ? name : "default.png"; - threshold = threshold ? threshold : this.maxVal; - Engine.DumpImage(name, this.map, this.width, this.height, threshold); -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/map-module.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entity-extend.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entity-extend.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entity-extend.js (nonexistent) @@ -1,63 +0,0 @@ -// returns some sort of DPS * health factor. If you specify a class, it'll use the modifiers against that class too. -function getMaxStrength(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; -}; Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/entity-extend.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_init.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_init.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_init.js (nonexistent) @@ -1 +0,0 @@ -Engine.IncludeModule("common-api-v3"); Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/_init.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-training.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-training.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-training.js (nonexistent) @@ -1,69 +0,0 @@ -var UnitTrainingPlan = function(gameState, type, metadata, number, maxMerge) { - this.type = gameState.applyCiv(type); - this.metadata = metadata; - - this.template = gameState.getTemplate(this.type); - if (!this.template) { - this.invalidTemplate = true; - this.template = undefined; - return; - } - this.category= "unit"; - this.cost = new Resources(this.template.cost(), this.template._template.Cost.Population); - if (!number){ - this.number = 1; - }else{ - this.number = number; - } - if (!maxMerge) - this.maxMerge = 5; - else - this.maxMerge = maxMerge; -}; - -UnitTrainingPlan.prototype.canExecute = function(gameState) { - if (this.invalidTemplate) - return false; - - // TODO: we should probably check pop caps - - var trainers = gameState.findTrainers(this.type); - - return (trainers.length != 0); -}; - -UnitTrainingPlan.prototype.execute = function(gameState) { - //warn("Executing UnitTrainingPlan " + 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 += 0.9; - if (b.hasClass("Civic") && !self.template.hasClass("Support")) - bb += 0.9; - return (aa - bb); - }); - - trainers[0].train(this.type, this.number, this.metadata); - } -}; - -UnitTrainingPlan.prototype.getCost = function(){ - var multCost = new Resources(); - multCost.add(this.cost); - multCost.multiply(this.number); - return multCost; -}; - -UnitTrainingPlan.prototype.addItem = function(amount){ - if (amount === undefined) - amount = 1; - this.number += amount; -}; \ No newline at end of file Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/plan-training.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/qbot.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/qbot.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/qbot.js (nonexistent) @@ -1,367 +0,0 @@ -function QBotAI(settings) { - BaseAI.call(this, settings); - - Config.updateDifficulty(settings.difficulty); - - this.turn = 0; - - this.playedTurn = 0; - - this.modules = { - "economy": new EconomyManager(), - "military": new MilitaryAttackManager() - }; - - // this.queues can only be modified by the queue manager or things will go awry. - this.queues = { - house : new Queue(), - citizenSoldier : new Queue(), - villager : new Queue(), - economicBuilding : new Queue(), - dropsites : new Queue(), - field : new Queue(), - militaryBuilding : new Queue(), - defenceBuilding : new Queue(), - civilCentre: new Queue(), - majorTech: new Queue(), - minorTech: new Queue() - }; - - this.productionQueues = []; - - this.priorities = Config.priorities; - - this.queueManager = new QueueManager(this.queues, this.priorities); - - this.firstTime = true; - - this.savedEvents = []; - - this.waterMap = false; - - this.defcon = 5; - this.defconChangeTime = -10000000; -} - -QBotAI.prototype = new BaseAI(); - -// Bit of a hack: I run the pathfinder early, before the map apears, to avoid a sometimes substantial lag right at the start. -QBotAI.prototype.InitShared = function(gameState, sharedScript) { - var ents = gameState.getEntities().filter(Filters.byOwner(PlayerID)); - var myKeyEntities = ents.filter(function(ent) { - return ent.hasClass("CivCentre"); - }); - - if (myKeyEntities.length == 0){ - myKeyEntities = gameState.getEntities().filter(Filters.byOwner(PlayerID)); - } - - var filter = Filters.byClass("CivCentre"); - var enemyKeyEntities = gameState.getEntities().filter(Filters.not(Filters.byOwner(PlayerID))).filter(filter); - - if (enemyKeyEntities.length == 0){ - enemyKeyEntities = gameState.getEntities().filter(Filters.not(Filters.byOwner(PlayerID))); - } - - this.pathFinder = new 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" + PlayerID + ".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; -} - -//Some modules need the gameState to fully initialise -QBotAI.prototype.runInit = function(gameState, events){ - - this.chooseRandomStrategy(); - - for (var i in this.modules){ - if (this.modules[i].init){ - this.modules[i].init(gameState, events); - } - } - debug ("Inited, diff is " + Config.difficulty); - this.timer = new Timer(); - - - var ents = gameState.getOwnEntities(); - var myKeyEntities = gameState.getOwnEntities().filter(function(ent) { - return ent.hasClass("CivCentre"); - }); - - if (myKeyEntities.length == 0){ - myKeyEntities = gameState.getOwnEntities(); - } - - // disband the walls themselves - if (gameState.playerData.civ == "iber") { - gameState.getOwnEntities().filter(function(ent) { //}){ - if (ent.hasClass("StoneWall") && !ent.hasClass("Tower")) - ent.destroy(); - }); - } - - var filter = Filters.byClass("CivCentre"); - var enemyKeyEntities = gameState.getEnemyEntities().filter(filter); - - if (enemyKeyEntities.length == 0){ - enemyKeyEntities = gameState.getEnemyEntities(); - } - - //this.accessibility = new Accessibility(gameState, myKeyEntities.toEntityArray()[0].position()); - - this.myIndex = this.accessibility.getAccessValue(myKeyEntities.toEntityArray()[0].position()); - - if (enemyKeyEntities.length == 0) - return; - - this.templateManager = new TemplateManager(gameState); -}; - -QBotAI.prototype.OnUpdate = function(sharedScript) { - if (this.gameFinished){ - return; - } - - if (this.events.length > 0){ - this.savedEvents = this.savedEvents.concat(this.events); - } - - - - // Run the update every n turns, offset depending on player ID to balance the load - // this also means that init at turn 0 always happen and is never run in parallel to the first played turn so I use an else if. - if (this.turn == 0) { - - //Engine.DumpImage("terrain.png", this.accessibility.map, this.accessibility.width,this.accessibility.height,255) - //Engine.DumpImage("Access.png", this.accessibility.passMap, this.accessibility.width,this.accessibility.height,this.accessibility.regionID+1) - - var gameState = sharedScript.gameState[PlayerID]; - gameState.ai = this; - - this.runInit(gameState, this.savedEvents); - - // Delete creation events - delete this.savedEvents; - this.savedEvents = []; - } else if ((this.turn + this.player) % 8 == 5) { - - Engine.ProfileStart("Aegis bot"); - - this.playedTurn++; - - var gameState = sharedScript.gameState[PlayerID]; - gameState.ai = this; - - if (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, 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) - { - debug ("Assuming this is a water map"); - this.waterMap = true; - } - delete this.pathFinder; - delete this.pathInfo; - } - } - - // try going up phases. - if (gameState.canResearch("phase_town",true) && gameState.getTimeElapsed() > (Config.Economy.townPhase*1000) - && gameState.findResearchers("phase_town",true).length != 0 && this.queues.majorTech.totalLength() === 0) { - this.queues.majorTech.addItem(new ResearchPlan(gameState, "phase_town",true)); // we rush the town phase. - debug ("Trying to reach town phase"); - var nb = gameState.getOwnEntities().filter(Filters.byClass("Village")).length-1; - if (nb < 5) - { - while (nb < 5 && ++nb) - this.queues.house.addItem(new BuildingConstructionPlan(gameState, "structures/{civ}_house")); - } - } else if (gameState.canResearch("phase_city_generic",true) && gameState.getTimeElapsed() > (Config.Economy.cityPhase*1000) - && gameState.getOwnEntitiesByRole("worker").length > 85 - && gameState.findResearchers("phase_city_generic", true).length != 0 && this.queues.majorTech.totalLength() === 0) { - debug ("Trying to reach city phase"); - this.queues.majorTech.addItem(new ResearchPlan(gameState, "phase_city_generic")); - } - // defcon cooldown - if (this.defcon < 5 && gameState.timeSinceDefconChange() > 20000) - { - this.defcon++; - debug ("updefconing to " +this.defcon); - if (this.defcon >= 4 && this.modules.military.hasGarrisonedFemales) - this.modules.military.ungarrisonAll(gameState); - } - - for (var i in this.modules){ - this.modules[i].update(gameState, this.queues, this.savedEvents); - } - - this.queueManager.update(gameState); - - /* - // Use this to debug informations about the metadata. - if (this.playedTurn % 10 === 0) - { - // some debug informations about units. - var units = 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(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.length % 29; - for (var i = 0; i < n; i++){ - Math.random(); - } - - delete this.savedEvents; - this.savedEvents = []; - - Engine.ProfileStop(); - } - - this.turn++; -}; - -QBotAI.prototype.chooseRandomStrategy = function() -{ - // deactivated for now. - this.strategy = "normal"; - // rarely and if we can assume it's not a water map. - if (!this.pathInfo.needboat && 0)//Math.random() < 0.2 && Config.difficulty == 2) - { - this.strategy = "rush"; - // going to rush. - this.modules.economy.targetNumWorkers = 0; - Config.Economy.townPhase = 480; - Config.Economy.cityPhase = 900; - Config.Economy.farmsteadStartTime = 600; - Config.Economy.femaleRatio = 0; // raise it since we'll want to rush age 2. - } -}; - -// TODO: Remove override when the whole AI state is serialised -// TODO: this currently is very much equivalent to "rungamestateinit" with a few hacks. Should deserialize/serialize properly someday. -QBotAI.prototype.Deserialize = function(data, sharedScript) -{ - BaseAI.prototype.Deserialize.call(this, data); - - var ents = sharedScript.entities.filter(Filters.byOwner(PlayerID)); - var myKeyEntities = ents.filter(function(ent) { - return ent.hasClass("CivCentre"); - }); - - if (myKeyEntities.length == 0){ - myKeyEntities = sharedScript.entities.filter(Filters.byOwner(PlayerID)); - } - - var filter = Filters.byClass("CivCentre"); - var enemyKeyEntities = sharedScript.entities.filter(Filters.not(Filters.byOwner(PlayerID))).filter(filter); - - if (enemyKeyEntities.length == 0){ - enemyKeyEntities = sharedScript.entities.filter(Filters.not(Filters.byOwner(PlayerID))); - } - - this.terrainAnalyzer = sharedScript.terrainAnalyzer; - this.passabilityMap = sharedScript.passabilityMap; - - var fakeState = { "ai" : this, "sharedScript" : sharedScript }; - this.pathFinder = new aStarPath(fakeState, 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); - - 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; -}; - -// Override the default serializer -QBotAI.prototype.Serialize = function() -{ - //var ret = BaseAI.prototype.Serialize.call(this); - return {}; -}; - -function debug(output){ - if (Config.debug){ - if (typeof output === "string"){ - warn(output); - }else{ - warn(uneval(output)); - } - } -} - -function copyPrototype(descendant, parent) { - var sConstructor = parent.toString(); - var aMatch = sConstructor.match( /\s*function (.*)\(/ ); - if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } - for (var m in parent.prototype) { - descendant.prototype[m] = parent.prototype[m]; - } -} Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/qbot.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/config.js =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/config.js (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/config.js (nonexistent) @@ -1,123 +0,0 @@ -// Baseconfig is the highest difficulty. -var baseConfig = { - "Military" : { - "fortressLapseTime" : 540, // Time to wait between building 2 fortresses - "defenceBuildingTime" : 600, // Time to wait before building towers or fortresses - "attackPlansStartTime" : 0 // time to wait before attacking. Start as soon as possible (first barracks) - }, - "Economy" : { - "townPhase" : 180, // time to start trying to reach town phase (might be a while after. Still need the requirements + ress ) - "cityPhase" : 540, // time to start trying to reach city phase - "farmsteadStartTime" : 400, // Time to wait before building a farmstead. - "dockStartTime" : 240, // Time to wait before building the dock - "techStartTime" : 600, // time to wait before teching. - "targetNumBuilders" : 1.5, // Base number of builders per foundation. Later updated, but this remains a multiplier. - "femaleRatio" : 0.6 // percent of females among the workforce. - }, - - // Note: attack settings are set directly in attack_plan.js - - // defence - "Defence" : { - "defenceRatio" : 5, // see defence.js for more info. - "armyCompactSize" : 700, // squared. Half-diameter of an army. - "armyBreakawaySize" : 900 // squared. - }, - - // military - "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" ] - } - }, - - // qbot - "priorities" : { // Note these are dynamic, you are only setting the initial values - "house" : 200, - "citizenSoldier" : 70, - "villager" : 55, - "economicBuilding" : 70, - "dropsites" : 120, - "field" : 1000, - "militaryBuilding" : 90, - "defenceBuilding" : 70, - "majorTech" : 400, - "minorTech" : 40, - "civilCentre" : 10000 // will hog all resources - }, - "difficulty" : 2, // for now 2 is "hard", ie default. 1 is normal, 0 is easy. 3 is very hard - "debug" : false -}; - -var Config = { - "debug": false, - "difficulty" : 2, // overriden by the GUI - updateDifficulty: function(difficulty) - { - Config.difficulty = difficulty; - // changing settings based on difficulty. - if (Config.difficulty === 1 && 0) // deactivated for the time being. Medium is basic mode. - { - Config["Military"] = { - "fortressLapseTime" : 900, - "defenceBuildingTime" : 720, - "attackPlansStartTime" : 600 - }; - Config["Economy"] = { - "townPhase" : 360, - "cityPhase" : 900, - "farmsteadStartTime" : 600, - "dockStartTime" : 240, - "techStartTime" : 1320, - "targetNumBuilders" : 2, - "femaleRatio" : 0.5, - "targetNumWorkers" : 110 // should not make more than 2 barracks. - }; - Config["Defence"] = { - "defenceRatio" : 4.0, - "armyCompactSize" : 700, - "armyBreakawaySize" : 900 - }; - } else if (Config.difficulty === 0) - { - Config["Military"] = { - "fortressLapseTime" : 1000000, // never - "defenceBuildingTime" : 900, - "attackPlansStartTime" : 1200 // 20 minutes ought to give enough times for beginners - }; - Config["Economy"] = { - "townPhase" : 480, - "cityPhase" : 1200, - "farmsteadStartTime" : 1200, - "dockStartTime" : 240, - "techStartTime" : 600000, // never - "targetNumBuilders" : 1, - "femaleRatio" : 0.0, // makes us slower, but also less sucky at defending so it's still fun to attack it. - "targetNumWorkers" : 80 // we will make advanced buildings and a fortress (and a market), but nothing more. - }; - Config["Defence"] = { - "defenceRatio" : 2.0, - "armyCompactSize" : 700, - "armyBreakawaySize" : 900 - }; - } - } -}; - -Config.__proto__ = baseConfig; \ No newline at end of file Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/config.js ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Index: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/data.json =================================================================== --- ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/data.json (revision 13686) +++ ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/data.json (nonexistent) @@ -1,6 +0,0 @@ -{ - "name": "Aegis Bot", - "description": "Wraitii's improvement of qBot. It is more reliable and generally a better player. Note that it doesn't support saved games yet, and there may be other bugs. Please report issues to Wildfire Games (see the link in the main menu).", - "constructor": "QBotAI", - "useShared": true -} Property changes on: ps/trunk/binaries/data/mods/public/simulation/ai/qbot-wc/data.json ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property