-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcar.py
349 lines (289 loc) · 14.1 KB
/
car.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
import math
from copy import deepcopy
class Car:
@staticmethod
def decompose_vector(vector, line):
x1, y1 = line[0]
x2, y2 = line[1]
# calculate the unit vector of the line
line_vector = (x2 - x1, y2 - y1)
line_magnitude = math.sqrt(line_vector[0] ** 2 + line_vector[1] ** 2)
line_unit_vector = (line_vector[0] / line_magnitude, line_vector[1] / line_magnitude)
# calculate the projection of the vector onto the line
projection_magnitude = vector[0] * line_unit_vector[0] + vector[1] * line_unit_vector[1]
projection_vector = (projection_magnitude * line_unit_vector[0], projection_magnitude * line_unit_vector[1])
# calculate the perpendicular vector
perpendicular_vector = (vector[0] - projection_vector[0], vector[1] - projection_vector[1])
return projection_vector, perpendicular_vector
def _handle_collision(self, intersection_point, line, angle, contact_points):
# self.fitness -= 20
self.lifespan -= 40
# print(self.prev_frame_collision)
self.rotation_velocity = (2 / self._mass * math.dist(intersection_point, self.center) ** 2) * \
self._inertia * (self.velocity[0] ** 2 + self.velocity[1] ** 2) * \
math.sin(angle / 2) - self.rotation_velocity
velocity_parallel, velocity_perpendicular = self.decompose_vector(self.velocity, line)
# print(1, self.velocity)
if contact_points >= 2:
self.velocity = [velocity_parallel[0] - velocity_perpendicular[0],
velocity_parallel[1] - velocity_perpendicular[1]]
else:
self.velocity = [-velocity_parallel[0] - velocity_perpendicular[0],
-velocity_parallel[1] - velocity_perpendicular[1]]
if self.prev_frame_collision == 0:
# make the bounces less beneficial
self.velocity[0] *= 0.7
self.velocity[1] *= 0.7
# print(2, self.velocity)
# print(self.center)
if self.prev_frame_collision == 2:
# print("bum")
self.velocity = [0, 0]
self.acceleration = [0, 0]
self.rotation_velocity = 0
self.rotation_acceleration = 0
self.center, self.angle = deepcopy(self.p_position)
else:
self.center, self.angle = deepcopy(self.p_position)
self.prev_frame_collision = 3
def check_collisions(self, lines):
points = self.get_points()
for line in lines:
intersection_total = [0, 0]
intersection_angle = 0
intersection_number = 0
for i in range(4):
car_line = (points[i], points[(i + 1) % 4])
intersection, angle = self.line_intersection(car_line, line)
if intersection is not None:
intersection_total[0] += intersection[0]
intersection_total[1] += intersection[1]
intersection_angle += angle
intersection_number += 1
if intersection_number > 0:
intersection = [0, 0]
intersection[0] = intersection_total[0] / intersection_number
intersection[1] = intersection_total[1] / intersection_number
angle = intersection_angle / intersection_number
self._handle_collision(intersection, line, angle, intersection_number)
return
self.p_position = deepcopy((self.center, self.angle))
def check_checkpoints(self, lines):
points = self.get_points()
# print(1, self.next_checkpoint, len(lines))
if self.next_checkpoint >= len(lines):
self.finished_checkpoints = True
return
for i, checkpoint in enumerate(lines):
for j in range(4):
car_line = (points[j], points[(j + 1) % 4])
# print(2, self.next_checkpoint, len(lines))
intersection, angle = self.line_intersection(car_line, lines[i])
if intersection is not None:
if self.next_checkpoint == i:
self.next_checkpoint += 1
self.fitness += 200 * (self.next_checkpoint / self.lap_time * 200)
self.lifespan += 200
return
elif self.next_checkpoint - 1 != i:
self.lifespan -= 20
def check_finish(self, finish):
if not self.finished_checkpoints:
return False
points = self.get_points()
for i in range(4):
car_line = (points[i], points[(i + 1) % 4])
intersection, angle = self.line_intersection(car_line, finish)
if intersection is not None:
self.next_checkpoint = 0
self.finished_checkpoints = False
self.fitness += 1000 * (2000 / self.lap_time)
self.lifespan += 1000
return True
return False
def ray_cast(self, angle, lines):
angle += self.angle
ray = [[0 + self.center[0], 0 + self.center[1]],
[10 * math.cos(angle) + self.center[0], -10 * math.sin(angle) + self.center[1]]]
end_point = [10 * math.cos(angle) + self.center[0], -10 * math.sin(angle) + self.center[1]]
for line in lines:
intersection, angle = self.line_intersection(ray, line)
if intersection is not None:
if end_point is None or math.dist(self.center, intersection) < math.dist(self.center, end_point):
end_point = intersection
ray[1] = end_point
return ray
@staticmethod
def line_intersection(line1, line2):
x1, y1 = line1[0]
x2, y2 = line1[1]
x3, y3 = line2[0]
x4, y4 = line2[1]
# calculate the denominator
denominator = ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1))
# check if the lines are parallel
if denominator == 0:
return None, None
# calculate the numerators
numerator1 = ((x4 - x3) * (y1 - y3)) - ((y4 - y3) * (x1 - x3))
numerator2 = ((x2 - x1) * (y1 - y3)) - ((y2 - y1) * (x1 - x3))
# calculate the values of t1 and t2
t1 = numerator1 / denominator
t2 = numerator2 / denominator
# check if the intersection point is within the range of the line segments
if 0 <= t1 <= 1 and 0 <= t2 <= 1:
intersection_x = x1 + (t1 * (x2 - x1))
intersection_y = y1 + (t1 * (y2 - y1))
angle_radians = math.atan2(y4 - y3, x4 - x3) - math.atan2(y2 - y1, x2 - x1)
return (intersection_x, intersection_y), angle_radians
else:
return None, None
# overcomplicated function for updating car physics
def update(self, dt, tire_change, is_accelerating, breaking, reverse):
# update ai stuff
self.lifespan -= 1
self.lap_time += 1
if self.prev_frame_collision > 0:
self.prev_frame_collision -= 1
# print(self.center)
if is_accelerating:
# assuming front-wheel drive
self.acceleration = [self._engine_force / self._mass * math.cos(self.angle + self.tire_angle),
self._engine_force / self._mass * -math.sin(self.angle + self.tire_angle)]
# assuming rear-wheel drive
# self.acceleration = [self.engine_force / self.mass * math.cos(self.angle),
# self.engine_force / self.mass * -math.sin(self.angle)]
# distance of center of mass to the axis of rotation
if self.tire_angle:
axis_distance = self._length * math.sqrt(1 / 4 + 1 / (math.tan(self.tire_angle) * math.tan(self.tire_angle)))
self.rotation_acceleration = self._engine_force * math.sin(self.tire_angle) / \
(self._inertia + self._mass * axis_distance * axis_distance) * 1.5
else:
self.rotation_acceleration = 0
else:
self.acceleration = [0.0, 0.0]
self.rotation_acceleration = 0.0
# calculate velocity angle
self.velocity_direction = math.atan2(-self.velocity[1], self.velocity[0])
# calculate drag
velocity_mag_sq = self.velocity[0] ** 2 + self.velocity[1] ** 2
drag_force = self._mass * self._friction_coefficient + velocity_mag_sq * self._drag_coefficient + \
self._break_force * breaking
# make it turn naturally
force = self._wheel_max_force * math.sin(self.tire_angle)
self.rotation_acceleration += force * self._length / self._inertia * (velocity_mag_sq ** 0.7)
# introduce friction and drag
if velocity_mag_sq > 0.001:
self.acceleration[0] -= drag_force / self._mass * math.cos(self.velocity_direction)
self.acceleration[1] -= drag_force / self._mass * -math.sin(self.velocity_direction)
# stop the car completely when it's really slow (to avoid back and forth)
elif breaking or (abs(self.acceleration[0]) < 0.01 and abs(self.acceleration[1]) < 0.01):
self.velocity = [0.0, 0.0]
# print(self.rotation_velocity)
# introduce rotation friction
# scale it with speed, tire_angle and rotation velocity
if self.rotation_velocity > 0.001:
self.rotation_acceleration -= drag_force / self._mass * (math.cos(self.tire_angle) + 1) * 1.2 * \
abs(self.rotation_velocity)
elif self.rotation_velocity < -0.001:
self.rotation_acceleration += drag_force / self._mass * (math.cos(self.tire_angle) + 1) * 1.2 * \
abs(self.rotation_velocity)
# stop rotation completely if it's too slow
else:
if abs(self.rotation_acceleration) < 0.999:
self.rotation_velocity = 0
if reverse:
self.acceleration[0] *= -0.1
self.acceleration[1] *= -0.1
# apply the movement
self.center[0] += self.velocity[0] * dt
self.center[1] += self.velocity[1] * dt
# REWARD
self.fitness += math.dist([0, 0], [self.velocity[0] * dt, self.velocity[1] * dt])
if math.dist([0, 0], [self.velocity[0] * dt, self.velocity[1] * dt]) < 0.001:
self.lifespan -= 10
# print(math.dist([0, 0], [self.velocity[0] * dt, self.velocity[1] * dt]))
self.velocity[0] += self.acceleration[0] * dt
self.velocity[1] += self.acceleration[1] * dt
self.angle += self.rotation_velocity * dt
self.rotation_velocity += self.rotation_acceleration * dt
# update angle of tires
if tire_change == 0:
if self.tire_angle > 0:
self.tire_angle -= self._steer * dt
self.tire_angle = max(self.tire_angle, 0)
if self.tire_angle < 0:
self.tire_angle += self._steer * dt
self.tire_angle = min(self.tire_angle, 0)
else:
self.tire_angle += tire_change * self._steer * dt
# cap rotation of tires at 60 deg
self.tire_angle = max(-math.pi / 3, min(math.pi / 3, self.tire_angle))
def get_vel(self):
return math.sqrt(self.velocity[0] ** 2 + self.velocity[1] ** 2)
def get_points(self):
points = [(self._length / 2.0, self._width / 2.0),
(-self._length / 2.0, self._width / 2.0),
(-self._length / 2.0, -self._width / 2.0),
(self._length / 2.0, -self._width / 2.0)]
for i in range(len(points)):
translation = (points[i][0] * math.cos(self.angle) + points[i][1] * math.sin(self.angle) + self.center[0],
-points[i][0] * math.sin(self.angle) + points[i][1] * math.cos(self.angle) + self.center[1])
points[i] = translation
return points
def get_data(self, boundaries, checkpoints, finish):
ray_angles = [-math.pi / 3, -math.pi / 6, 0, math.pi / 6, math.pi / 3]
inputs = []
for angle in ray_angles:
line = self.ray_cast(angle, boundaries)
inputs.append(math.dist(line[0], line[1]))
# inputs.append(self.rotation_velocity)
# inputs.append(self.velocity[0])
# inputs.append(self.velocity[1])
# inputs.append(self.center[0])
# inputs.append(self.center[1])
cp_angles = [-math.pi / 3, -math.pi / 6, 0, math.pi / 6, math.pi / 3]
if self.finished_checkpoints or self.next_checkpoint >= len(checkpoints):
for angle in cp_angles:
line = self.ray_cast(angle, [finish])
inputs.append(math.dist(line[0], line[1]))
else:
for angle in cp_angles:
line = self.ray_cast(angle, [checkpoints[self.next_checkpoint]])
inputs.append(math.dist(line[0], line[1]))
return inputs
def __init__(self, center, angle):
self._length = 1.0 / 2.5 # tiles
self._width = 1.0 / 5.0 # tiles
# movement constants
self._engine_force = 4000 # Nm
self._break_force = 3000 # N
self._friction_coefficient = 1.2
self._drag_coefficient = 100
self._wheel_max_force = 5000
self._mass = 2000
magic_constant = 20
self._inertia = self._mass / 12 * (self._length * self._length + self._width * self._width) * magic_constant
# controls constants
self._steer = 5
# position and movement variables
self.center = center
self.p_position = (center, 0)
self.angle = angle
self.tire_angle = 0.0
self.velocity = [0.0, 0.0]
self.acceleration = [0.0, 0.0]
self.rotation_velocity = 0.0
self.rotation_acceleration = 0.0
# collision helper variable
self.prev_frame_collision = 0
# gui variable
self.velocity_direction = 0.0
# track variables
self.next_checkpoint = 0
self.lap_time = 0
self.finished_checkpoints = False
# ai variables
self.lifespan = 3000
self.fitness = 0
self.dead = False