-
Notifications
You must be signed in to change notification settings - Fork 0
/
AI.py
384 lines (296 loc) · 8.73 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
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
from PriorityQueue import *
import numpy as np
from math import *
"""
These functions are to make like easier
"""
def tupleAdd(t0, t1):
r = []
i = 0
while i < len(t0):
r.append(t0[i] + t1[i])
i += 1
return tuple(r)
def tupleSubtract(t0, t1):
r = []
i = 0
while i < len(t0):
r.append(t0[i] - t1[i])
i += 1
return tuple(r)
def genMoveArray(start, end):
"""
Creates a array that maps a move from start to end
:param start: Start pos
:param end: End pos
:return: Array of positions the car enters during the move
"""
def numSplit(num, parts):
"""
Divides a number into a list of n parts that when summed equal num
:param num: number to split into ~equal parts
:param parts: length of list
:return: A list of length parts of ~equal values that sum to num
"""
div = num // parts
return_array = [div] * parts
rem = num % parts
for i in range(rem):
return_array[i] += 1
return return_array
move = tupleSubtract(end, start)
currPos = list(start)
if abs(move[0]) > abs(move[1]):
p = (0, 1)
else:
p = (1, 0)
arr = numSplit(abs(move[p[0]]), abs(move[p[1]]) + 1)
retArr = [start]
i = 0
while True:
# Do
for increment in range(arr[i]):
currPos[p[0]] += move[p[0]] / abs(move[p[0]])
retArr.append((currPos[0], currPos[1]))
# While
if i > (len(arr) - 2):
break
currPos[p[1]] += move[p[1]] / abs(move[p[1]])
retArr.append((currPos[0], currPos[1]))
i += 1
return retArr
def genPossMoves(state, referenceArray):
"""
Generates the array of all valid next moves for the input car state
:param state: {'h': heuristic, 'g': moves to this position, 'f': g(n) + h(n),
'state': ((position tuple), velocity, angle), 'parent': state}
:param moveArray: Passed in reference array of possible moves at each speed
:return: An array of possible next moves
"""
position, velocity, angle = state['state']
# all velocity = 1 moves valid for stopped car
if velocity == 0:
return referenceArray[1]
# when velocity > 0
positionRatio = angle / (2 * pi)
possibleMoves = []
# adjacent distances
for i in (0, -1, 1):
# If the new velocity is invalid
if velocity + i < 0 or velocity + i > 6:
continue
if velocity + i == 0:
possibleMoves.append((0, 0))
continue
# Find the most closely representative square at this speed and angle
currentAlignment = round(positionRatio * len(referenceArray[velocity + i]))
# adjacent turns
for j in (0, -1, 1):
# If end of list is reached wrap to first item
if currentAlignment + j == len(referenceArray[velocity + i]):
j = 0
elif currentAlignment + j < 0:
j = len(referenceArray[velocity + i]) - 1
possibleMoves.append(referenceArray[velocity + i][currentAlignment + j])
return possibleMoves
def genMoveReferenceArray(type):
"""
Generates the array that contains all move offsets for a specific velocity
:param type: Dictates the function used to calculate the integer value (round, ceil, floor)
:return: A reference array to be used to calculate successors
"""
def mergeSortDict(arr):
"""
Recursive function to do a merge sort
! Very unnecessary optimization !
:param arr: The array to sort
:return: The sorted array
"""
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
mergeSortDict(L)
mergeSortDict(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if list(L[i].keys())[0] < list(R[j].keys())[0]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
moveArr = [[] for i in range(7)]
if type == 0:
for x in range(13):
for y in range(13):
adjPos = np.array([6, 6]) - np.array([x, y])
if (round(hypot(adjPos[1], adjPos[0])) < 7):
d = round(hypot(adjPos[1], adjPos[0]))
a = round(atan2(adjPos[0], adjPos[1]), 2)
if a < 0:
a = a + 2 * pi
moveArr[d].append({a: tuple(adjPos)})
if type == 1:
for x in range(13):
for y in range(13):
adjPos = np.array([6, 6]) - np.array([x, y])
if (ceil(hypot(adjPos[1], adjPos[0])) < 7):
d = round(hypot(adjPos[1], adjPos[0]))
a = round(atan2(adjPos[0], adjPos[1]), 2)
if a < 0:
a = a + 2 * pi
moveArr[d].append({a: tuple(adjPos)})
if type == 2:
for x in range(13):
for y in range(13):
adjPos = np.array([6, 6]) - np.array([x, y])
if (floor(hypot(adjPos[1], adjPos[0]), 0) < 7):
d = round(hypot(adjPos[1], adjPos[0]))
a = round(atan2(adjPos[0], adjPos[1]), 2)
if a < 0:
a = a + 2 * pi
moveArr[d].append({a: tuple(adjPos)})
for d in range(7):
mergeSortDict(moveArr[d])
moveArr[d] = [innerDict.popitem()[1] for innerDict in moveArr[d]]
return moveArr
def calcF(g, h):
"""
Calculate the f value of this state
:param g: The g value
:param h: The h value
:return: The f value
"""
return g + h
def calcG(parentG):
"""
Calculate the g value for this state
:param parentG: The parent state
:return: The new states g value
"""
return parentG + 1
def calcH(state, goal):
"""
Calculate the heuristic value of the current state
:param state: The given car state
:param goal: The location of the goal
:return: The heuristic value
"""
currentPosition = state[0]
moveVector = tupleSubtract(goal, currentPosition)
distanceFromGoal = hypot(*moveVector)
minimumMoves = distanceFromGoal / 6.5
return minimumMoves
def hitsWall(currentPosition, parentPosition, track):
"""
Check if during the move from the parent to the current position a wall is present
:param currentPosition: The current position
:param parentPosition: The previous position
:param track: The array that contains the wall locations
:return: True if it hits a wall, else false
"""
# Generate the spaces this move will occupy
moveArray = genMoveArray(parentPosition, currentPosition)
# Iterate through spaces moved through and check if a wall occupies it
hitWall = False
for pos in moveArray:
if (pos[0] < 0 or pos[0] >= track.size) or (pos[1] < 0 or pos[1] >= track.size):
hitWall = True
break
if track.track[int(pos[0])][int(pos[1])] == 1:
hitWall = True
break
return hitWall
def findSuccessorStates(track, state, moveArr):
"""
Finds all states that can follow the input
:param state: {'h': heuristic, 'g': moves to this position, 'f': g(n) + h(n),
'state': np.array(), 'parent': state}
:return: All states that can succeed this one
"""
possMoves = genPossMoves(state, moveArr)
# Generate all of the possible successor states
succStates = []
for move in possMoves:
parentPosition = state['state'][0]
currentPosition = tupleAdd(state['state'][0], move)
if not hitsWall(currentPosition, parentPosition, track):
v = round(hypot(*move))
a = round(atan2(move[0], move[1]), 2)
# Make sure that the angle is positive
if a < 0:
a = a + 2 * pi
stateTuple = (tuple(currentPosition), v, a)
if state['parent'] is None:
g = 0
else:
g = calcG(state['parent']['g'])
h = calcH(stateTuple, track.goal)
f = calcF(g, h)
succStates.append(
{
'state': stateTuple,
'h': h,
'g': g,
'f': f,
'parent': state
}
)
return succStates
def getSolution(goalState):
"""
Traces the path of the given state from the goal back to the start
:param goalState: The state that ends the optimal path
:return: An array of arrays were each inner array represents the tile moves in one piece of time
"""
moveList = []
while goalState['parent'] != None:
moveList.append(genMoveArray(goalState["parent"]['state'][0], goalState['state'][0]))
goalState = goalState["parent"]
print("Solution is ", len(moveList), " steps long!")
return list(reversed(moveList))
def AStar(track):
"""
Uses A* search to find a path for the car
:param track: the track data
:return: An array of moves for the car to make to reach the goal
"""
# Pre-Generate the move reference array
referenceArray = genMoveReferenceArray(0)
openQueue = PriorityQueue()
closed = {}
goal = track.goal
openQueue.enqueue({
'state': (track.start, 0, 0),
'parent': None,
'f': 0 + calcH((track.start, 0, 0), track.goal),
'g': 0,
'h': calcH((track.start, 0, 0), track.goal)
})
while (not openQueue.isEmpty()):
currentState = openQueue.pop()
closed[currentState['state']] = currentState
if (currentState['state'][0] == goal):
return getSolution(currentState)
else:
succStates = findSuccessorStates(track, currentState, referenceArray)
for state in succStates:
if state['state'] in closed:
if closed[state['state']]['g'] > state['g']:
del closed[state['state']]
openQueue.enqueue(state)
else:
openQueue.enqueue(state)
raise Exception("Error: No Path Found")