-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRefactoredBot.py
More file actions
284 lines (230 loc) · 10.1 KB
/
RefactoredBot.py
File metadata and controls
284 lines (230 loc) · 10.1 KB
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
from hlt2 import *
import utils2
import logging
import random
import math
random.seed(0)
logging.basicConfig(filename='last_run.log',level=logging.DEBUG)
def attractiveness(square,my_id):
if square.owner == my_id:
return 0.
return ((255.-square.strength)/255 + square.production/30.)**2
def attractiveness_start(square,my_id):
return square.production/float(square.strength)
def cost(square):
return square.strength/float(square.production+1)
def get_smart_decay(my_id,stats):
return 1.
my_territory = stats['n_owners'][my_id]
decay = 1/math.sqrt(my_territory)
return decay
def get_smart_enemy_attr(my_id,enemy_id,stats):
enemy_strength = stats['strength_owners'][enemy_id]
my_strength = stats['strength_owners'][my_id]
return (enemy_strength/(my_strength+1.))
def adjust_frontier_potential(frontier,my_id,attr_map,gamemap,stats,enemy_attr=1.,exploration_factor=1.,radius=5,enemy_attr_far=2.):
adjusted_attr = {k:v for k,v in attr_map.items()}
for square in frontier:
sum_attr = 0
region = [neighbor for neighbor in gamemap.neighbors(square,n=radius) if neighbor.owner != my_id]
len_region = 0.
for neighbor in region:
if neighbor in frontier:
continue
len_region += 1.
attr = attr_map[neighbor]
if neighbor.owner not in (0,my_id):
attr += enemy_attr_far*get_smart_enemy_attr(my_id,neighbor.owner,stats) - 0.0
sum_attr += attr
average_attr = sum_attr/len_region if len_region else 0
adjusted_attr[square] += exploration_factor*average_attr
for square in frontier:
for neighbor in gamemap.neighbors(square):
if neighbor.owner not in (0,my_id):
adjusted_attr[neighbor] += enemy_attr*get_smart_enemy_attr(my_id,neighbor.owner,stats)
return adjusted_attr
def map_potential(inner,frontier,attr_map,gamemap,decay):
new_attr_map = {k:v for k,v in attr_map.items()}
inner_set = set(inner)
frontier_set = set(frontier)
total_set = inner_set.union(frontier_set)
visited = set()
sorted_nodes = [(f,new_attr_map[f]) for f in frontier]
sorted_nodes.sort(key=lambda x:x[1])
# potentials = {square:None for square in inner}
# for square in frontier:
# potentials[square] = attr_map[square]
while len(sorted_nodes)>0:
current,value = sorted_nodes.pop()
for neighbor in gamemap.neighbors(current):
if not neighbor in inner_set or neighbor in visited:
continue
# potentials[neighbor] = potentials[current] - decay
new_attr_map[neighbor] = new_attr_map[current] - decay
sorted_nodes.append((neighbor,new_attr_map[neighbor]))
sorted_nodes.sort(key=lambda x:x[1])
visited.add(neighbor)
# for square in inner:
# new_attr_map[square] = potentials[square]
return new_attr_map
def shouldMove(square,new_square,map_uptodate,my_id):
if square.strength <= 3*square.production:
#if strength <= 5*production
return False
if map_uptodate[new_square].strength > square.strength and map_uptodate[new_square].owner != my_id:
#if foreign tile of superior strength
return False
if map_uptodate[new_square].strength + square.strength > 255 and map_uptodate[new_square].owner == my_id:
#if friendly tile and sum>255
return False
return True
def map_directions(my_id,attr_map,gamemap,momentum_map,directions_dict=None):
directions_map = {}
wanted_directions_map = {}
moves_list = []
map_uptodate = {square:Square(
square.x,
square.y,
square.owner,
square.strength if square.owner!=my_id else 0.,
square.production) for square in gamemap}
for square in gamemap:
if square.owner!=my_id:
directions_map[square] = None
wanted_directions_map[square] = None
continue
if directions_dict is None or directions_dict.get(square) is None:
candidate_directions = [(d,n) for d,n in enumerate(gamemap.neighbors(square)) if d != opp_cardinal[momentum_map[(square.x,square.y)]]]
# candidate_directions = [(d,n) for d,n in enumerate(gamemap.neighbors(square))]
potential_direction,new_square = max(candidate_directions,key=lambda dsq:attr_map[dsq[1]])
else:
potential_direction = directions_dict.get(square,STILL)
new_square = gamemap.get_target(square,potential_direction)
wanted_directions_map[square] = potential_direction
if shouldMove(square,new_square,map_uptodate,my_id):
directions_map[square] = potential_direction
new_strength = square.strength + map_uptodate[new_square].strength if map_uptodate[new_square].owner==my_id else square.strength-map_uptodate[new_square].strength
#updating mapping
map_uptodate[new_square]._replace(strength=new_strength)
map_uptodate[new_square]._replace(owner = my_id)
map_uptodate[square]._replace(strength = 0)
else:
directions_map[square] = STILL
moves_list.append((square,directions_map[square]))
return moves_list,directions_map,wanted_directions_map
def process_movelist(movelist,moves,momentum_map,gamemap):
for square,d in movelist:
moves.append(Move(square, d))
if d == STILL:
momentum_map[(square.x,square.y)] = STILL
else:
new_square = gamemap.get_target(square,d)
momentum_map[(new_square.x,new_square.y)] = d
def process_directions(moves,directions_map,momentum_map,gamemap):
sorted_squares = sorted(gamemap,key=lambda sq:sq.strength)
for square in sorted_squares:
if directions_map[square] is None:
continue
d = directions_map[square]
moves.append(Move(square,d))
if d == STILL:
momentum_map[(square.x,square.y)] = STILL
else:
new_square = gamemap.get_target(square,d)
momentum_map[(new_square.x,new_square.y)] = d
if __name__ == "__main__":
target_reached = False
momentum_map = {}
my_id,gamemap = get_init()
gamemap_stats = utils2.get_gamemap_stats(my_id,gamemap)
logging.debug("Computed map stats")
frontier = utils2.find_frontier(my_id,gamemap)
logging.debug("Found frontier")
start = utils2.find_start(my_id,gamemap)
momentum_map[(start.x,start.y)] = STILL
others_start = [utils2.find_start(player_id,gamemap) for player_id in range(gamemap.starting_player_count+1) if player_id not in (0,my_id)]
logging.debug("Found Starting Positions")
logging.debug(start)
logging.debug(others_start)
min_distance_to_others = utils2.get_min_distance(start,others_start,gamemap)
logging.debug("Found Minimum Distance")
logging.debug(min_distance_to_others)
attr_map = utils2.map_attractiveness(my_id,gamemap,attractiveness_start)
logging.debug("Mapped Attractiveness")
smoothed_attr_map = utils2.smooth_map(attr_map,gamemap,kernel=[1.,1.5])
logging.debug("Mapped Smoothed Attractiveness")
target = utils2.find_local_max(start,int(min_distance_to_others/2),smoothed_attr_map,gamemap)
logging.debug("Found Target")
logging.debug(target)
directions_dict,path = utils2.a_star(target,start,gamemap,cost)
logging.debug("Found Path")
send_init("RefactoredBot")
logging.debug("Init sent")
decay_factor = 0.05
momentumTerm = 1000.
enemy_attr = 0.2 #0.5 works well too
enemy_attr_far = 0.01
radius = 6
turn = 0
time_tracker = utils2.TimeTracker(logging)
game_dumper = utils2.Dumper('gameMap','refactored',on=True)
while True:
moves = []
gamemap.get_frame()
logging.debug("TURN: {}".format(turn))
time_tracker.track()
gamemap_stats = utils2.get_gamemap_stats(my_id,gamemap)
time_tracker.track("Computing map stats")
decay = get_smart_decay(my_id,gamemap_stats)*decay_factor
logging.debug("Decay: {:.2f}".format(decay))
frontier,frontier_map = utils2.track_frontier(frontier,my_id,gamemap)
time_tracker.track("Tracking frontier")
inner = utils2.find_inner(my_id,gamemap)
time_tracker.track("Finding inner")
attr_map = utils2.map_attractiveness(my_id,gamemap,attractiveness)
time_tracker.track("Mapping Attractiveness")
adjusted_attr_map = adjust_frontier_potential(
frontier,
my_id,
attr_map,
gamemap,
gamemap_stats,
enemy_attr=enemy_attr,
enemy_attr_far=enemy_attr_far,
radius=radius)
time_tracker.track("Adjusting Frontier Potential Attr")
final_attr_map = map_potential(inner,frontier,adjusted_attr_map,gamemap,decay=decay)
time_tracker.track("Map Potential Attr")
movelist,directions_map,wanted_directions_map = map_directions(
my_id,
final_attr_map,
gamemap,
momentum_map,
directions_dict if not target_reached else None)
time_tracker.track("Map Directions")
#process_movelist(movelist,moves,momentum_map,gamemap)
process_directions(moves,directions_map,momentum_map,gamemap)
game_state_dict = {
'my_id':my_id,
'gamemap':gamemap,
'attr_map':attr_map,
'adjusted_attr_map':adjusted_attr_map,
'final_attr_map':final_attr_map,
'directions_map':directions_map,
'wanted_directions_map':wanted_directions_map,
'momentum_map':momentum_map,
'smoothed_attr_map':smoothed_attr_map,
'inner':inner,
'frontier':frontier,
'frontier_map':frontier_map,
'target_reached':target_reached,
'directions_dict':directions_dict,
'target':target,
'start':start
}
game_dumper.dump(game_state_dict,turn)
if gamemap.get_target(target,4).owner!=0:
target_reached = True
send_frame(moves)
time_tracker.log()
turn += 1