From 2f4321361698c0946f66a877bd1c27ce2fe03664 Mon Sep 17 00:00:00 2001 From: Yair Morgenstern Date: Fri, 22 May 2020 11:08:39 +0300 Subject: [PATCH] Resolved #2647 - Automated workers run away from enemy military units --- .../logic/automation/WorkerAutomation.kt | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/core/src/com/unciv/logic/automation/WorkerAutomation.kt b/core/src/com/unciv/logic/automation/WorkerAutomation.kt index b2623f93..7f17dfe8 100644 --- a/core/src/com/unciv/logic/automation/WorkerAutomation.kt +++ b/core/src/com/unciv/logic/automation/WorkerAutomation.kt @@ -11,13 +11,14 @@ import com.unciv.models.ruleset.tile.TileImprovement class WorkerAutomation(val unit: MapUnit) { + fun containsEnemyMilitaryUnit(tileInfo: TileInfo) = tileInfo.militaryUnit != null + && tileInfo.militaryUnit!!.civInfo.isAtWarWith(unit.civInfo) + fun automateWorkerAction() { val enemyUnitsInWalkingDistance = unit.movement.getDistanceToTiles().keys - .filter { - it.militaryUnit != null && it.militaryUnit!!.civInfo.isAtWarWith(unit.civInfo) - } + .filter(this::containsEnemyMilitaryUnit) - if (enemyUnitsInWalkingDistance.isNotEmpty()) return // Don't you dare move. + if (enemyUnitsInWalkingDistance.isNotEmpty()) return runAway() val currentTile = unit.getTile() val tileToWork = findTileToWork() @@ -61,6 +62,25 @@ class WorkerAutomation(val unit: MapUnit) { } + fun countDistanceToClosestEnemy(tile: TileInfo): Int { + for(i in 1..3) + if(tile.getTilesAtDistance(i).any(this::containsEnemyMilitaryUnit)) + return i + return 4 + } + + private fun runAway() { + val reachableTiles = unit.movement.getDistanceToTiles() + val enterableCity = reachableTiles.keys.firstOrNull { it.isCityCenter() && unit.movement.canMoveTo(it) } + if(enterableCity!=null) { + unit.movement.moveToTile(enterableCity) + return + } + val tileFurthestFromEnemy = reachableTiles.keys.filter { unit.movement.canMoveTo(it) } + .maxBy(this::countDistanceToClosestEnemy)!! + unit.movement.moveToTile(tileFurthestFromEnemy) + } + private fun tryConnectingCities(unit: MapUnit):Boolean { // returns whether we actually did anything //Player can choose not to auto-build roads & railroads.