/
ai.py
188 lines (147 loc) · 5.27 KB
/
ai.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
from flask import Flask, request
from structs import Player, PlayerInfo, Tile, TileContent, Point
import json
from Queue import Queue
# from search import Search
# import numpy as np
import networkx as nx
app = Flask(__name__)
def print_map(m):
# for i in range(len(m)):
# print([(tile.x, tile.y) for tile in m[i]])
for i in range(len(m)):
print([tile.content.name[0] for tile in m[i]])
def manhattan_dist(start, end):
sx, sy = start
ex, ey = end
return abs(ex - sx) + abs(ey - sy)
def bfs(m, g, start, tile):
frontier = Queue()
frontier.put(start)
visited = {}
visited[start] = True
while not frontier.empty():
current = frontier.get()
for n in g.neighbors(current):
if n not in visited:
if m[n[1]][n[0]].content == tile:
return n
frontier.put(n)
visited[n] = True
def do_something(p, m, g):
# print(p.__dict__)
# print_map(m)
# print(g.nodes())
goal_tile = None
if p.CarriedRessources < p.CarryingCapacity:
goal_tile = TileContent.Resource
else:
goal_tile = TileContent.House
player_pos = (p.Position.to_tuple()[0] - m[0][0].x, p.Position.to_tuple()[1] - m[0][0].y)
dest_pos = bfs(m, g, player_pos, goal_tile)
if dest_pos is None:
goal_tile = TileContent.Wall
g = create_graph(m, True)
dest_pos = bfs(m, g, player_pos, goal_tile)
next_pos = nx.astar_path(g, player_pos, dest_pos)[1]
# print(player_pos)
# print(dest_pos)
# print(next_pos)
if next_pos == dest_pos:
if (goal_tile == TileContent.Resource):
return p.collect(Point(next_pos[0] + m[0][0].x, next_pos[1] + m[0][0].y))
elif (goal_tile == TileContent.Wall):
return p.attack(Point(next_pos[0] + m[0][0].x, next_pos[1] + m[0][0].y))
return p.move(Point(next_pos[0] + m[0][0].x, next_pos[1] + m[0][0].y))
def create_graph(tiles, withWalls):
graph = nx.grid_graph([20, 20])
for i in range(20):
for j in range(20):
if tiles[i][j].content == TileContent.Lava:
graph.remove_node((j, i))
elif not withWalls and tiles[i][j].content == TileContent.Wall:
graph.remove_node((j, i))
# elif tiles[i][j].content == TileContent.Player:
# graph.remove_node((j, i))
return graph
def deserialize_map(serialized_map):
"""
Fonction utilitaire pour comprendre la map
"""
serialized_map = serialized_map[1:]
rows = serialized_map.split('[')
column = rows[0].split('{')
deserialized_map = [[Tile() for x in range(20)] for y in range(20)]
for i in range(len(rows) - 1):
column = rows[i + 1].split('{')
for j in range(len(column) - 1):
infos = column[j + 1].split(',')
end_index = infos[2].find('}')
x = int(infos[1])
y = int(infos[2][:end_index])
content = int(infos[0])
deserialized_map[j][i] = Tile(x, y, content)
return deserialized_map
def bot():
"""
Main de votre bot.
"""
map_json = request.form["map"]
# Player info
encoded_map = map_json.encode()
map_json = json.loads(encoded_map.decode('utf-8'))
p = map_json["Player"]
pos = p["Position"]
x = pos["X"]
y = pos["Y"]
house = p["HouseLocation"]
player = Player(p["Health"], p["MaxHealth"], Point(x,y),
Point(house["X"], house["Y"]), p["Score"],
p["CarriedResources"], p["CarryingCapacity"])
# print(player.__dict__)
# print("MY POSITION", player.Position)
# print(player.__dict__)
# Map
serialized_map = map_json["CustomSerializedMap"]
deserialized_map = deserialize_map(serialized_map)
graph = create_graph(deserialized_map, False)
# print(deserialized_map)
# print(player.__dict__)
# print(player.Position)
# print_map(deserialized_map)
# print(graph.nodes())
otherPlayers = []
for player_dict in map_json["OtherPlayers"]:
for player_name in player_dict.keys():
player_info = player_dict[player_name]
if player_info == "notAPlayer":
continue
p_pos = player_info["Position"]
# print("\n\n\n", p_pos)
player_info = PlayerInfo(player_info["Health"],
player_info["MaxHealth"],
Point(p_pos["X"], p_pos["Y"]))
otherPlayers.append({player_name: player_info })
return do_something(player, deserialized_map, graph)
# s = Search(graph, deserialized_map, player)
# print(s.find_best_decision())
### BOT EXECUTION
# cherche prochaine action si path est vide
# if len(path) == 0 and len(lastaction) == 0:
# s = Search(graph, deserialized_map, player)
# path, action = s.find_best_decision()
# if len(path) == 0:
# return eval(lastaction)
# move to tile adjacent to last action
#target = path.pop(0)
#return player.move(target)
@app.route("/", methods=["POST"])
def reponse():
"""
Point d'entree appelle par le GameServer
"""
return bot()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
path = []
lastaction = []