-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMyBot.py
1614 lines (1354 loc) · 53.2 KB
/
MyBot.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##########################
### Last submitted bot ###
##########################
#!/usr/bin/env python3
# Python 3.6
# Import the Halite SDK, which will let you interact with the game.
import hlt
import numpy as np
import scipy.stats as st
# This library contains constant values.
from hlt import constants, entity
from heapq import heappop, heappush
# This library contains direction metadata to better interface with the game.
from hlt.positionals import Direction
# This library allows you to generate random numbers.
import random
# Logging allows you to save messages for yourself. This is required because the regular STDOUT
# (print statements) are reserved for the engine-bot communication.
import logging
import math
from hlt import Direction, Position
""" <<<Game Begin>>> """
# This game object contains the initial game state.
game = hlt.Game()
# At this point "game" variable is populated with initial map data.
# This is a good place to do computationally expensive start-up pre-processing.
# As soon as you call "ready" function below, the 2 second per turn timer will start.
game.ready("MyBot")
# Now that your bot is initialized, save a message to yourself in the log file with some important information.
# Here, you log here your id, which you can always fetch from the game object by using my_id.
logging.info("Successfully created bot! My Player ID is {}.".format(game.my_id))
""" <<<Game Loop>>> """
def in_enemy_area(position):
if len(enemies_ships):
return game_map.calculate_distance(
min(
enemies_ships,
key=lambda s: game_map.calculate_distance(s.position, position)
).position
,
position
) <= 1
return False
def maze2graph(maze):
height = len(maze)
width = len(maze[0]) if height else 0
graph = {
(i, j): [] for j in range(width) for i in range(height) if not maze[i][j]
}
for row, col in graph.keys():
if (
row < height - 1
and
not maze[row + 1][col]
):
graph[(row, col)].append(
(
"s",
(row + 1, col)
)
)
graph[(row + 1, col)].append(
(
"n",
(row, col)
)
)
if (
col < width - 1
and
not maze[row][col + 1]
):
graph[(row, col)].append(
(
"e",
(row, col + 1)
)
)
graph[(row, col + 1)].append(
(
"w",
(row, col)
)
)
return graph
def heuristic(cell, goal):
return abs(cell[0] - goal[0]) + abs(cell[1] - goal[1])
def find_path_astar(maze, start, goal):
pr_queue = []
heappush(
pr_queue,
(
0 + heuristic(start, goal),
0,
"",
start
)
)
visited = set()
graph = maze2graph(maze)
while pr_queue:
_, cost, path, current = heappop(pr_queue)
if current == goal:
return path
if current in visited:
continue
visited.add(current)
for direction, neighbour in graph[current]:
heappush(
pr_queue,
(
cost + heuristic(neighbour, goal),
cost + 1,
path + direction, neighbour
)
)
return "o"
def get_direction_from_waze_recursive(maze, maze_width, maze_height, origin, start, goal, start_position):
# update parameters for the next loop
new_maze_width = maze_width + 2
new_maze_height = maze_height + 2
new_origin = origin - Position(1, 1)
new_start = (start[0] + 1, start[1] + 1)
new_goal = (goal[0] + 1, goal[1] + 1)
new_maze = np.append(
maze,
[[0]] * maze_height,
axis=1
)
new_maze = np.insert(
new_maze,
0,
0,
axis=1
)
new_maze = np.append(
new_maze,
[[0] * new_maze_width],
axis=0
)
new_maze = np.insert(
new_maze,
0,
0,
axis=0
)
impossible = True
# the top line and the bottom line
for i in range(0, new_maze_width):
position_tmp1 = game_map.normalize(Position(new_origin.x + i, new_origin.y))
if (
game_map[position_tmp1].is_occupied
or
(
game_map.calculate_distance(start_position, position_tmp1) == 1
and
in_enemy_area(position_tmp1)
)
):
impossible = False
new_maze[0][i] = 1
position_tmp2 = game_map.normalize(Position(new_origin.x + i, new_origin.y + new_maze_height - 1))
if (
game_map[position_tmp2].is_occupied
or
(
game_map.calculate_distance(start_position, position_tmp2) == 1
and
in_enemy_area(position_tmp2)
)
):
impossible = False
new_maze[new_maze_height - 1][i] = 1
# the rest of the left column the right column
for j in range(1, new_maze_height - 1):
position_tmp1 = game_map.normalize(Position(new_origin.x, new_origin.y + j))
if (
game_map[position_tmp1].is_occupied
or
(
game_map.calculate_distance(start_position, position_tmp1) == 1
and
in_enemy_area(position_tmp1)
)
):
impossible = False
new_maze[j][0] = 1
position_tmp2 = game_map.normalize(Position(new_origin.x + new_maze_width - 1, new_origin.y + j))
if (
game_map[position_tmp2].is_occupied
or
(
game_map.calculate_distance(start_position, position_tmp2) == 1
and
in_enemy_area(position_tmp2)
)
):
impossible = False
new_maze[j][new_maze_width - 1] = 1
path = find_path_astar(
new_maze,
new_start,
new_goal
)
if (
path == "o"
and
(
new_maze_width < WIDTH / 3
or
new_maze_height < WIDTH / 3
)
):
if impossible:
return "o"
return get_direction_from_waze_recursive(new_maze, new_maze_width, new_maze_height, new_origin, new_start, new_goal, start_position)
else:
return path
def get_direction_from_waze(start_position, goal_position):
if (
game_map[goal_position].is_occupied
or
start_position == goal_position
):
return "o"
resulting_position = abs(start_position - goal_position)
maze_width = min(
resulting_position.x,
WIDTH - resulting_position.x
) + 1
maze_height = min(
resulting_position.y,
WIDTH - resulting_position.y
) + 1
direction_to_position = {
"w" : {
"start" : (0, maze_width - 1),
"goal" : (maze_height - 1, 0)
},
"sw" : {
"start" : (0, maze_width - 1),
"goal" : (maze_height - 1, 0)
},
"s" : {
"start" : (0, 0),
"goal" : (maze_height - 1, maze_width - 1)
},
"e" : {
"start" : (0, 0),
"goal" : (maze_height - 1, maze_width - 1)
},
"es" : {
"start" : (0, 0),
"goal" : (maze_height - 1, maze_width - 1)
},
"n" : {
"start" : (maze_height - 1, 0),
"goal" : (0, maze_width - 1)
},
"en" : {
"start" : (maze_height - 1, 0),
"goal" : (0, maze_width - 1)
},
"nw" : {
"start" : (maze_height - 1, maze_width - 1),
"goal" : (0, 0)
}
}
# initialize the matrix
maze = [0] * maze_height
for i in range(0, maze_height):
maze[i] = [0] * maze_width
start_to_goal_direction = ''.join(
sorted(
list(
map(
lambda d: Direction.convert(d),
game_map.get_unsafe_moves(start_position, goal_position)
)
)
)
)
start = direction_to_position[start_to_goal_direction]["start"]
goal = direction_to_position[start_to_goal_direction]["goal"]
origin = start_position - Position(start[1], start[0])
# set 1 if the there is a ship
for i in range(0, maze_width):
for j in range(0, maze_height):
position_tmp = game_map.normalize(Position(origin.x + i, origin.y + j))
if (
game_map[position_tmp].is_occupied
and
not (j, i) in [start, goal]
or
(
game_map.calculate_distance(start_position, position_tmp) == 1
and
in_enemy_area(position_tmp)
)
):
maze[j][i] = 1
path = find_path_astar(
maze,
start,
goal
)
if path == "o":
return get_direction_from_waze_recursive(maze, maze_width, maze_height, origin, start, goal, start_position)
else:
return path
def get_ships_around(from_position, count_enemies = False, count_allies = False , area = None):
if area is None:
area = constants.INSPIRATION_RADIUS
count = dict()
if count_enemies:
count["enemies"] = len(
list(
filter(
lambda ship: (
game_map.calculate_distance(ship.position, from_position)
<=
area
),
enemies_ships
)
)
)
if count_allies:
count["allies"] = len(
list(
filter(
lambda ship: (
game_map.calculate_distance(ship.position, from_position)
<=
area
),
me.get_ships()
)
)
)
return count
def get_extraction(from_position = None, with_inspiration = True):
if from_position is None:
return max(1, int(math.ceil(min_halite_to_stay * (1 / constants.EXTRACT_RATIO))))
# extracted halite per default without inspiration
extracted_halite = int(math.ceil(game_map[from_position].halite_amount * (1 / constants.EXTRACT_RATIO)))
if (
with_inspiration
and
constants.INSPIRATION_ENABLED
and
get_ships_around(from_position, True)["enemies"]
>=
constants.INSPIRATION_SHIP_COUNT
):
extracted_halite *= int((constants.INSPIRED_BONUS_MULTIPLIER + 1))
return extracted_halite
def numerical_superiority(from_position, area = 3):
coeff = 1.5 if len(me.get_ships()) < len(enemies_ships) * 1.2 else 1
ships_around = get_ships_around(from_position, True, True, area)
return (ships_around["allies"] - 1) > (ships_around["enemies"] - 1) * coeff
def get_best_dropoff(from_position):
shipyard_and_dropoffs = [me.shipyard] + me.get_dropoffs()
closest_dropoff = get_closest_shipyard_or_dropoff(from_position)
# filters the dropoffs whose cost of travel is close to that of the nearest dropoff
filtered_shipyard_and_dropoffs = list(
filter(
lambda i: (
game_map.calculate_distance(from_position, closest_dropoff.position) * 1.5
>=
game_map.calculate_distance(i.position, from_position)
),
shipyard_and_dropoffs
)
)
return max(
filtered_shipyard_and_dropoffs,
key=lambda i: get_halite_around(i.position, 5)
)
def get_halite_around(from_position, area):
total_halite_around = 0
for i in range(from_position.x - area, from_position.x + area + 1):
for j in range(from_position.y - area, from_position.y + area + 1):
total_halite_around += game_map[Position(i, j)].halite_amount
return total_halite_around
def count_available_halite():
total_halite = 0
for x in range(0, WIDTH):
for y in range(0, WIDTH):
total_halite += game.game_map[Position(x, y)].halite_amount
return total_halite
def update_halite_collected_ratio():
return 1 - (count_available_halite() / HALITE_AT_THE_BEGINNING)
def get_closest_shipyard_or_dropoff(from_position, take_into_account_other_players = False, without_position = None):
shipyard_and_dropoffs = [me.shipyard] + me.get_dropoffs()
if take_into_account_other_players:
for player_id, player_object in game.players.items():
if not player_object == me:
shipyard_and_dropoffs += [player_object.shipyard]
return min(
# remove the entity at without_position
filter(
lambda i: True if without_position is None else not i.position == without_position,
shipyard_and_dropoffs
),
key=lambda j: game_map.calculate_distance(j.position, from_position)
)
def can_spawn_dropoff(area = 5):
if not (
halite_collected_ratio < 0.65
and
len(me.get_dropoffs()) < MAX_DROPOFFS[WIDTH][NB_PLAYERS]
and
(game.turn_number / constants.MAX_TURNS) <= 0.7
and
len(me.get_ships()) >= 15
):
return False
shipyard_and_dropoffs = [me.shipyard] + me.get_dropoffs()
for s in shipyard_and_dropoffs:
halite_around = get_halite_around(s.position, area)
average_halite_around = halite_around / ((area + 1) * (area + 1))
if (
average_halite_around / 3.5
>
count_available_halite() / (WIDTH * WIDTH)
):
return False
global stop_spending_halite
stop_spending_halite = False
anticipated_dropoffs.clear()
return True
def apply_movement(ship, command):
command_queue.append(command)
# indicates that the ship has played
ship.has_already_played = True
# save the next positions of allied ships
# if this it a "move" command
if command[0] == "m":
direction = COMMAND_TO_DIRECTION[
str(command[-1:])
]
next_position = game_map.normalize(ship.position.directional_offset(direction))
next_positions.append(game_map.normalize(next_position))
# if this is a "construct" command
elif command[0] == "c":
next_positions.append(game_map.normalize(ship.position))
if not swapping:
# if this it a "move" command
if command[0] == "m":
# mark the former position as safe for other allied ships
direction = COMMAND_TO_DIRECTION[
str(command[-1:])
]
next_position = game_map.normalize(ship.position.directional_offset(direction))
# if the ship move on another position
if not next_position == game_map.normalize(ship.position):
game_map[ship.position].mark_unsafe(None)
# if this is a "construct" command
elif command[0] == "c":
game_map[ship.position].mark_unsafe(None)
def gaussian_kernel(gaussian_len=3, sigma=3):
"""
Returns a 2D Gaussian kernel array.
:param gaussian_len: The kernel length. Only an odd number
:param sigma: Sigma, the strength of the blur.
:return: A 2D Gaussian kernel array.
"""
interval = (2*sigma+1.)/(gaussian_len)
x = np.linspace(-sigma-interval/2., sigma+interval/2., gaussian_len+1)
kern1d = np.diff(st.norm.cdf(x))
kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
kernel = kernel_raw/kernel_raw.sum()
return kernel
def blur(gaussian_len=10, sigma=3):
# get the gaussian_kernel
kernel = gaussian_kernel(gaussian_len, sigma)
offset = int((gaussian_len - 1) / 2)
total_width = WIDTH + 2 * offset
blurred_matrix = [0] * total_width
# fill the outside
for x in range(0, total_width):
blurred_matrix[x] = [0] * total_width
for y in range(0, total_width):
# if it's the left
if x < offset:
blurred_matrix[x][y] = float(game_map[Position(total_width - x - 1, y)].halite_amount)
# if it's the right
elif x > offset + WIDTH:
blurred_matrix[x][y] = float(game_map[Position(x - offset - WIDTH, y)].halite_amount)
# if it's the up
elif y < offset:
blurred_matrix[x][y] = float(game_map[Position(x, total_width - y - 1)].halite_amount)
# if it's the down
elif y > offset + WIDTH:
blurred_matrix[x][y] = float(game_map[Position(x, y - offset - WIDTH)].halite_amount)
# else, it's the center
else:
blurred_matrix[x][y] = float(game_map[Position(x, y)].halite_amount)
arraylist = []
for y in range(gaussian_len):
temparray = np.copy(blurred_matrix)
temparray = np.roll(temparray, y - 1, axis=0)
for x in range(gaussian_len):
temparray_X = np.copy(temparray)
temparray_X = np.roll(temparray_X, x - 1, axis=1)*kernel[y,x]
arraylist.append(temparray_X)
arraylist = np.array(arraylist)
arraylist_sum = np.sum(arraylist, axis=0)
# remove offsets
final_blurred_matrix = arraylist_sum[
offset:offset + WIDTH,
offset:offset + WIDTH
]
return final_blurred_matrix
def custom_naive_navigate(ship, destination, crash_into_shipyard, simulate, position_to_match):
"""
Returns a singular safe move towards the destination.
:param ship: The ship to move.
:param destination: Ending position
:param crash_into_shipyard: True if the ship must crash into the shipyard, False otherwise
:param simulate: True if should mark the cell as unsafe for the next ships, False otherwise
:param position_to_match: if we have to see if this position is attainable in 1 movement (to swap with another boat)
:return: A direction.
"""
available_positions = []
blocked_positions_because_of_an_enemy = []
for direction in game_map.get_unsafe_moves(ship.position, destination):
target_pos = game_map.normalize(ship.position.directional_offset(direction))
close_enemies_ships = [
a for a in enemies_ships
if game_map.calculate_distance(a.position, target_pos) <= 1
]
close_allied_ships = [
a for a in me.get_ships()
if game_map.calculate_distance(a.position, target_pos) <= 1
]
close_allied_ships.remove(ship)
# if the ship must crash into the shipyard and if the ship is 1 displacement of the shipyard
if (
crash_into_shipyard
and
game_map.calculate_distance(ship.position, destination) == 1
):
available_positions.append([target_pos, direction])
else:
# save positions blocked by an enemy
# if this position is in the area of an enemy
# and that an allied ship has not already moved to that position
if (
len(close_enemies_ships)
and
not target_pos in next_positions
):
blocked_positions_because_of_an_enemy.append(target_pos)
# else, if the position isn't occupied and not close to the enemy
elif not game_map[target_pos].is_occupied:
available_positions.append([target_pos, direction])
# else, we check if the position is occupied by an allied ship
else:
for allied_ship in close_allied_ships:
# if the ship has not already played and if it's at this position
if (
not allied_ship.has_already_played
and
allied_ship.position == target_pos
):
if (
not position_to_match is None
and
position_to_match == allied_ship.position
and
simulate
):
return direction
elif not simulate:
# get the next movement of the allied ship in a simulate turn
allied_command = get_next_movement(allied_ship, True, game_map.normalize(ship.position))
allied_direction = COMMAND_TO_DIRECTION[
str(allied_command[-1:])
]
next_simulated_allied_position = game_map.normalize(target_pos.directional_offset(allied_direction))
# if these ships can swap their position
if next_simulated_allied_position == ship.position:
global swapping
swapping = True
# mark these position as unsafe
game_map[ship.position].mark_unsafe(allied_ship)
game_map[target_pos].mark_unsafe(ship)
# apply the movement of the allied ship
apply_movement(
allied_ship,
allied_ship.move(allied_direction)
)
# and returns that of the current ship
return direction
# if the allied ship will move by releasing the position
elif next_simulated_allied_position != allied_ship.position:
game_map[next_simulated_allied_position].mark_unsafe(allied_ship)
# apply the movement of the allied ship
apply_movement(
allied_ship,
allied_ship.move(allied_direction)
)
# important to mark unsafe AFTER applying the movement of the allied ship
game_map[target_pos].mark_unsafe(ship)
return direction
if len(available_positions):
sorted_positions_by_ascending_halite = sorted(
available_positions,
key=lambda p: game_map[p[0]].halite_amount,
reverse=False
)
cheapest_positions = [sorted_positions_by_ascending_halite[0]]
# if the 2nd position with the least halite costs the same cost
if (
len(available_positions) == 2
and
int(game_map[sorted_positions_by_ascending_halite[0][0]].halite_amount * (1 / constants.MOVE_COST_RATIO))
==
int(game_map[sorted_positions_by_ascending_halite[1][0]].halite_amount * (1 / constants.MOVE_COST_RATIO))
):
cheapest_positions.append(sorted_positions_by_ascending_halite[1])
chosen_position = random.choice(cheapest_positions)
if not simulate:
game_map[chosen_position[0]].mark_unsafe(ship)
return chosen_position[1]
for blocked_position in blocked_positions_because_of_an_enemy:
if (
numerical_superiority(blocked_position)
and
not (
game_map[blocked_position].ship in me.get_ships()
and
not game_map[blocked_position].ship.has_already_played
)
):
direction = game_map.get_unsafe_moves(ship.position, blocked_position)[0]
if not simulate:
game_map[blocked_position].mark_unsafe(ship)
return direction
if (
not position_to_match is None
and
# the ship refuse if it's in ships_constructing_dropoff
not game_map[position_to_match].ship.id in ships_constructing_dropoff
and
# the ship refuse if it's in ships_coming_back and if the other ship is not is ships_constructing_dropoff
(
not ship in ships_coming_back
or
game_map[position_to_match].ship.id in ships_constructing_dropoff
)
):
direction = game_map.get_unsafe_moves(ship.position, position_to_match)[0]
return direction
waze_direction = get_direction_from_waze(
game_map.normalize(ship.position),
game_map.normalize(destination)
)[0]
direction = COMMAND_TO_DIRECTION[
waze_direction
]
if not simulate:
game_map[game_map.normalize(ship.position.directional_offset(direction))].mark_unsafe(ship)
return direction
def scan_area(area, position, find_one = None):
"""
Recursive function. Returns the position with the maximum of halite around a given position
:param area: the area of the zone to scope
:return: the Position object
"""
# the most recent shipyard
try:
most_recent_shipyard = dropoffs_history[
min(
dropoffs_history.keys(),
key=lambda k: dropoffs_history[k]["turns_ago"]
)
]
ship_id = game_map[position].ship.id
if (
most_recent_shipyard["turns_ago"] < 30
and
len(most_recent_shipyard["ships_in_area"]) < 5
and
not ship_id in most_recent_shipyard["ships_in_area"]
):
distance_from_the_nearest_dropoff = game_map.calculate_distance(
get_closest_shipyard_or_dropoff(
position,
False,
most_recent_shipyard["position"]
).position,
most_recent_shipyard["position"]
)
distance_from_the_ship = game_map.calculate_distance(
position,
most_recent_shipyard["position"]
)
if distance_from_the_nearest_dropoff >= distance_from_the_ship:
# if the ship is now in the area
if distance_from_the_ship <= 5:
most_recent_shipyard["ships_in_area"].append(ship_id)
return most_recent_shipyard["position"]
except ValueError:
pass
if (
not find_one is None
and
area - find_one["area"] > 5
):
return find_one["position"]
all_options = [];
##########################################################################
# example for area = 3
# with <X> : position at the right distance from <o>
# x 0 1 2 3 4 5 6
# y
# 0 . . . X . . .
# 1 . . X . X . .
# 2 . X . . . X .
# 3 X . . o . . X
# 4 . X . . . X .
# 5 . . X . X . .
# 6 . . . X . . .
# if like the example, add Position(0, 3) and Position(6, 3) because <offset_y> would be 0
all_options.append(game_map.normalize(Position(position.x - area, position.y)))
all_options.append(game_map.normalize(Position(position.x + area, position.y)))
offset_y = 1
# for each x, add the 2 positions that are at the right distance
for i in range(position.x - area + 1, position.x + area):
all_options.append(game_map.normalize(Position(i, position.y - offset_y)))
all_options.append(game_map.normalize(Position(i, position.y + offset_y)))
if offset_y < area:
offset_y += 1
else:
offset_y -= 1
# remove if is_occupied and no enough halite
# and sort by halite
sorted_filtered_options = sorted(
list(
filter(
lambda opt: (
not game_map[opt].is_occupied
and
int(game_map[opt].halite_amount * (1 / constants.EXTRACT_RATIO))
>=
int(get_extraction())
),
all_options
)
),
key=lambda opt2: game_map[opt2].halite_amount,
# key=lambda opt2: get_halite_around(opt2, 3),
reverse=True
)
if len(sorted_filtered_options):
if find_one is None:
return scan_area(
area + 1,
position,
{
"position" : sorted_filtered_options[0],
"area" : area,
"extraction" : int(game_map[sorted_filtered_options[0]].halite_amount * (1 / constants.EXTRACT_RATIO))
}
)
else:
# if the new position is better
if int(game_map[sorted_filtered_options[0]].halite_amount * (1 / constants.EXTRACT_RATIO)) > find_one["extraction"] * 50:
return scan_area(
area + 1,
position,
{
"position" : sorted_filtered_options[0],
"area" : find_one["area"],
"extraction" : int(game_map[sorted_filtered_options[0]].halite_amount * (1 / constants.EXTRACT_RATIO))
}
)
else:
return scan_area(
area + 1,
position,
# [position, distance, extraction]
find_one
)
else:
# recall scan_area with area + 1
if area < WIDTH:
return scan_area(area + 1, position, find_one)
else:
return position
def have_enough_halite_to_move(ship):
return (
ship.halite_amount
>=
int(game_map[ship.position].halite_amount * (1 / constants.MOVE_COST_RATIO))
)
def get_next_movement(current_ship, simulate, position_to_match = None):
"""
Returns the next movement of the current ship
:return: a move to move this ship
"""
# if the ship have no enough halite to move
if not have_enough_halite_to_move(current_ship):
return current_ship.stay_still()
# if the ship must move towards an anticipated dropoff
if (
stop_spending_halite
and
current_ship.id in anticipated_dropoffs
):
if (
game_map.calculate_distance(
current_ship.position,
anticipated_dropoffs[current_ship.id]
) == 1
):
return current_ship.stay_still()
max_pos = anticipated_dropoffs[current_ship.id]
direction = custom_naive_navigate(current_ship, max_pos, False, simulate, position_to_match)
movement = current_ship.move(direction)
return current_ship.stay_still()
# if the ship is at 1 displacement of the shipyard
elif (
farthest_ship_coming_back_because_of_the_time
and
game_map.calculate_distance(current_ship.position, get_closest_shipyard_or_dropoff(current_ship.position).position) == 1