-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBot.py
335 lines (280 loc) · 14 KB
/
Bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
from Map import Map
from Aliases import positionTuple
import math
import random
from Events.Events import TankAddedEvent
from Tanks.Tank import Tank
from Events.EventManager import EventManager
from Tanks.AT_SPG import AT_SPG
from Tanks.HEAVY_TANK import HEAVY_TANK
from Tanks.LIGHT_TANK import LIGHT_TANK
from Tanks.MEDIUM_TANK import MEDIUM_TANK
from Tanks.SPG import SPG
from copy import deepcopy
from collections import deque
from Constants import HexTypes
import itertools
import heapq
class Bot:
settings = {
"HealthPercentLossMultiplier": 0.1,
# new postion
"RepairPositionBonus": 0.5,
"CatapultPositionBonus": 1,
}
def __init__(self, map: Map, eventManager: EventManager, movementSystem, shootingSystem,
entityManagementSystem):
"""
Initializes the bot.
:param map: An instance of the Map that holds static game information.
"""
self.__map = map
self.__canMoveTo = {HexTypes.EMPTY.value, HexTypes.BASE.value, HexTypes.CATAPULT.value,
HexTypes.LIGHT_REPAIR.value, HexTypes.HARD_REPAIR.value}
self.__mapSize = self.__map.getSize()
self.__baseMap = {}
self.__catapultMap = {}
self.__hexPermutations = list(itertools.permutations([-1, 0, 1], 3))
self.__teams = {}
self.__initializeMap()
self.__movementSystem = movementSystem
self.__shootingSystem = shootingSystem
self.__tanks = {}
self.__eventManager = eventManager
self.__eventManager.addHandler(TankAddedEvent, self.onTankAdded)
self.__entityManagementSystem = entityManagementSystem
self.__turnOrder = [SPG, LIGHT_TANK, HEAVY_TANK, MEDIUM_TANK, AT_SPG]
self.__player = entityManagementSystem.getOurPlayer()
def getTanks(self) -> dict[Tank]:
return self.__tanks
def __initializeMap(self):
"""
Initializes each positions value based on distance from a base
"""
for position, obj in self.__map:
if obj == HexTypes.BASE.value:
self.__path(position, self.__baseMap)
def __distance(self, position1: positionTuple, position2: positionTuple) -> int:
"""
Returns the distance between two positions.
:param position1: The first position.
:param position2: The second position.
:return: The distance between the two positions.
"""
return (abs(position1[0] - position2[0]) + abs(position1[1] - position2[1]) + abs(
position1[2] - position2[2])) // 2
def onTankAdded(self, tankId: str, tankEntity: Tank) -> None:
"""
Event handler. Adds the tank to the bot
:param tankId: The ID of the added tank.
:param tankEntity: The Tank entity that was added.
"""
self.__tanks[tankId] = tankEntity
ownerId = tankEntity.getComponent("owner").ownerId
self.__teams.setdefault(ownerId, []).append(tankId)
def __path(self, position: positionTuple, valueMap):
visited = set() # Set to store visited offsets
valueMap[position] = max(2, valueMap.get(position, -math.inf))
queue = deque()
queue.append((position, 0))
visited.add(position)
# Perform breadth-first search to find all possible moves
while len(queue) > 0:
currentPosition, currentDistance = queue.popleft()
currentPositionObject = self.__map.objectAt(currentPosition)
if not (currentPositionObject in self.__canMoveTo):
continue
currentValue = valueMap.get(currentPosition)
if currentDistance == 0:
value = 2
else:
value = 1 / currentDistance
if currentValue:
valueMap[currentPosition] = max(value, currentValue * value)
else:
valueMap[currentPosition] = value
for permutation in self.__hexPermutations:
newPosition = tuple(x + y for x, y in zip(currentPosition, permutation))
if all(abs(pos) < self.__mapSize for pos in newPosition) and newPosition not in visited:
visited.add(newPosition)
queue.append((newPosition, currentDistance + 1))
def __getEnemyTanks(self, allyOwnerId: int, damagedEnemies):
enemyTanks = []
for ownerId, tanks in self.__teams.items():
if ownerId != allyOwnerId:
enemyList = []
for tankId in tanks:
if tankId in damagedEnemies:
if damagedEnemies[tankId] > 0:
enemyList.append(tankId)
else:
enemyList.append(tankId)
if len(damagedEnemies) == 0:
enemyTanks.append(enemyList)
elif len(enemyTanks) > 0:
enemyTanks[0].extend(enemyList)
else:
enemyTanks.append(enemyList)
return enemyTanks
def __getPositions(self, tanks: list[int]):
positions = []
for tankId in tanks:
positions.append(self.__tanks[tankId].getComponent("position").position)
return positions
def __getTotalDamages(self, tanks: list[int]):
totalDamages = {}
for tankId in tanks:
targetablePositions = self.__shootingSystem.getShootablePositions(tankId)
damage = self.__tanks[tankId].getComponent("shooting").damage
for position in targetablePositions:
totalDamages[position] = totalDamages.get(position, 0) + damage
return totalDamages
def __buildHeuristicMap(self, tank, tankId, movementOptions, currentPosition, damagedEnemies):
tank = self.__tanks[tankId]
center = (0, 0, 0)
valueMap = {position: self.__baseMap.get(position, self.__distance(position, center)) for position in
movementOptions}
valueMap[currentPosition] = self.__baseMap.get(currentPosition, self.__distance(currentPosition, center))
ownerId = tank.getComponent("owner").ownerId
healthComponent = tank.getComponent("health")
selfDestructionReward = tank.getComponent("destructionReward").destructionReward
hasCatapult = tank.getComponent("shooting").rangeBonusEnabled
maxHP = healthComponent.maxHealth
currentHP = healthComponent.currentHealth
enemyTanks = self.__getEnemyTanks(ownerId, damagedEnemies)
# adjust values based on potential enemy targets that are capturing
for position in valueMap.keys():
totalValue = 0
obj = self.__map.objectAt(position)
if obj == HexTypes.LIGHT_REPAIR.value:
if isinstance(tank, MEDIUM_TANK):
totalValue += (Bot.settings["RepairPositionBonus"] * (maxHP - currentHP))
elif obj == HexTypes.HARD_REPAIR.value:
if isinstance(tank, (AT_SPG, HEAVY_TANK)):
totalValue += (Bot.settings["RepairPositionBonus"] * (maxHP - currentHP))
elif obj == HexTypes.CATAPULT.value and self.__shootingSystem.catapultAvailable(
position) and not hasCatapult:
totalValue += Bot.settings["CatapultPositionBonus"]
valueMap[position] += totalValue
# adjust values based on potential damage taken
damageValues = []
for enemyTankList in enemyTanks:
currentIndex = len(damageValues)
damageValues.append({})
totalDamages = self.__getTotalDamages(enemyTankList)
for position, totalDamage in totalDamages.items():
if position in valueMap:
healthPartLeft = ((currentHP - totalDamage) / currentHP)
if healthPartLeft <= 0:
obj = self.__map.objectAt(position)
if (obj == "LightRepair" and isinstance(tank, MEDIUM_TANK)) or (
obj == "HardRepair" and isinstance(tank, (AT_SPG, HEAVY_TANK))):
continue
damageValues[currentIndex][position] = -selfDestructionReward
else:
healthValueLost = (1 - healthPartLeft) * Bot.settings["HealthPercentLossMultiplier"]
damageValues[currentIndex][position] = (1 - healthValueLost)
if len(damageValues) > 1:
for position, value in damageValues[1].items():
if value < damageValues[0].get(position, math.inf):
damageValues[0][position] = value
if len(damageValues) > 0:
for key, value in damageValues[0].items():
valueMap[key] *= value
return valueMap
def __getBestMove(self, moves: list[positionTuple], tankId: int, damagedEnemies) -> list[positionTuple]:
tank = self.__tanks[tankId]
currentPosition = tank.getComponent("position").position
heuristicMap = self.__buildHeuristicMap(tank, tankId, moves, currentPosition, damagedEnemies)
heuristicMap.pop(currentPosition)
return [k for k, v in heapq.nlargest(1, heuristicMap.items(), key=lambda item: item[1])]
def __getTileTypesInRange(self, movementOptions: list[positionTuple]) -> set:
"""
Returns list of all tile types in movement range
"""
tileTypes = set()
for position in movementOptions:
tileTypes.add(self.__map.objectAt(position))
return tileTypes
@staticmethod
def __isHealingPossible(allyTank: Tank, allTileTypes: set[str]) -> bool:
"""
:param: allyTank Tank object
:param: allTileTypes tile types that are reachable
:return: true if healing is possible in one move, false otherwise
"""
return (type(allyTank).__name__ == "MEDIUM_TANK" and HexTypes.LIGHT_REPAIR.value in allTileTypes) \
or (type(allyTank).__name__ in ("HEAVY_TANK", "AT_SPG") and HexTypes.HARD_REPAIR.value in allTileTypes)
# TODO: Improve evaluation
def __evaluateCurrentActions(self, currentActions, movement, damagedEnemies):
positionValue = 0
for tankId, positionChange in movement.items():
positionValue += \
self.__buildHeuristicMap(self.__tanks[tankId], tankId, [], positionChange[1], damagedEnemies)[
positionChange[1]]
capturePointsDenied = 0
destructionPoints = 0
totalDamage = 0
for damagedEnemyId, health in damagedEnemies.items():
targetHealth = self.__tanks[damagedEnemyId].getComponent("health").currentHealth
totalDamage += targetHealth - health
if health <= 0:
capturePointsDenied += self.__tanks[damagedEnemyId].getComponent("capture").capturePoints
destructionPoints += self.__tanks[damagedEnemyId].getComponent("destructionReward").destructionReward
return positionValue + 3 ** (capturePointsDenied - 1) + destructionPoints * 1.3 + totalDamage * 0.05
def __findBestActionCombination(self):
bestScore = -math.inf
bestActions = []
totalCombos = 0
def backtrack(currentActions, currentTankIndex, movement, damagedEnemies):
nonlocal bestScore, bestActions, totalCombos
if currentTankIndex == 5:
totalCombos += 1
# Evaluate the current move combination and update the best score and moves
score = self.__evaluateCurrentActions(currentActions, movement, damagedEnemies)
if score > bestScore:
bestScore = score
bestActions = deepcopy(currentActions)
return
currentTankId = self.__player.getPlayerTanks()[currentTankIndex]
possibleMovement = self.__movementSystem.getMovementOptions(currentTankId)
possibleShoting = self.__shootingSystem.getShootingOptions(currentTankId)
currentPosition = self.__tanks[currentTankId].getComponent("position").position
targetPositions = self.__getBestMove(possibleMovement, currentTankId, damagedEnemies)
for targetPosition in targetPositions:
currentActions.append(("move", currentTankId, targetPosition))
self.__movementSystem.move(currentTankId, targetPosition)
movement[currentTankId] = [currentPosition, targetPosition]
backtrack(currentActions, currentTankIndex + 1, movement, damagedEnemies)
self.__movementSystem.move(currentTankId, currentPosition)
del movement[currentTankId]
currentActions.pop()
currentDamage = self.__tanks[currentTankId].getComponent("shooting").damage
for targetPosition, targets in possibleShoting:
shot = False
damagedEnemiesBacktrack = deepcopy(damagedEnemies)
for target in targets:
if target in damagedEnemiesBacktrack:
targetHealth = damagedEnemiesBacktrack[target]
else:
targetHealth = self.__tanks[target].getComponent("health").currentHealth
if targetHealth > 0:
shot = True
damagedEnemiesBacktrack[target] = targetHealth - currentDamage
if shot:
currentActions.append(("shoot", currentTankId, targetPosition))
backtrack(currentActions, currentTankIndex + 1, movement, damagedEnemiesBacktrack)
currentActions.pop()
backtrack(currentActions, currentTankIndex + 1, movement, damagedEnemies)
backtrack([], 0, {}, {})
return bestActions
def getActions(self) -> tuple[str, positionTuple]:
return self.__findBestActionCombination()
# either shooting chosen and no shooting options, or move chosen and no move options
return "none", (-1, -1, -1)
def reset(self) -> None:
"""
Resets the bot it's initial state.
"""
self.__tanks.clear()
self.__teams.clear()