-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
317 lines (261 loc) · 9.27 KB
/
main.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
import os
import pygame
import pickle
import neat
from point import Point, GetDistance
from spline import Spline
from math import sin, radians, degrees, copysign, sqrt
from pygame.math import Vector2
from car import Car
from utils import TrackTriangles, translate
from constants import *
from UI.setup import *
pygame.init()
# pygame.display.set_caption(" Self Driving Car")
screen = pygame.display.set_mode((Width, Height), vsync=True)
clock = pygame.time.Clock()
fps = 60
# load Assets
track_filename = "./map/new_track3"
current_directory = os.path.dirname(os.path.abspath(__file__))
carImage_path = os.path.join(current_directory, "./Assets/car2.png")
car_sprite = pygame.image.load(carImage_path)
sprite = pygame.transform.scale(car_sprite, CAR_SIZE)
# ---- Initiate New splines and lines ---
# track = Spline()
# trackTopBound = Spline()
# trackBottomBound = Spline()
# trackTopBound.pointRadius = 1
# trackBottomBound.pointRadius = 1
# track.CreatePoints(N_POINTS, False)
# trackBottomBound.CreatePoints(N_POINTS, False)
# trackTopBound.CreatePoints(N_POINTS, False)
# track.resolution = SPLINE_RESOLUTION
# trackBottomBound.resolution = SPLINE_RESOLUTION
# trackTopBound.resolution = SPLINE_RESOLUTION
# TrackLines = []
# -- OR --
# ---- load the Saved data ----
# if you load the tracks and it doesn't look like before (incomplete)
# check if the constants is the
# same as the saved data
filename = "./map/track4"
loadData = pickle.load(open(filename, 'rb'))
track = loadData['TRACK']
trackTopBound = loadData['TOP_TRACK']
trackBottomBound = loadData['BOTTOM_TRACK']
TrackLines = loadData['LINES']
# ---------
debug=False
editorMode = False
edit=False
wireframe=False
wireframeLine=False
updateLines = False
Lines = None
# set changed=True if you want to edit a track or create a new one
changed = False
saveChange = False
ThemeIndex = 3
generation = 0
showPanel = False
def Fitness(genomes, config):
global ThemeIndex, edit, debug, editorMode, wireframe, wireframeLine, updateLines
global changed, saveChange, showPanel, generation
global TRACK_WIDTH
nets = []
genes = []
cars = []
for index, genome in genomes:
genome.fitness = 0
nn = neat.nn.FeedForwardNetwork.create(genome, config)
nets.append(nn)
car = Car(4, 20)
car.sprite = sprite
car.angle = 90
cars.append(car)
genome.fitness = 0
genes.append(genome)
counter = 1
run = True
MouseClicked = False
generation += 1
GenerationText.text = "Generation : " + str(generation)
PopulationText.text = "Population size: " + str(len(cars))
survivors = len(cars)
while run:
screen.fill(Themes[ThemeIndex]["background"])
dt = clock.get_time()/1000
clock.tick(fps)
framerate = clock.get_fps()
pygame.display.set_caption("Self Driving Car AI - FrameRate(fps) : {}".format(int(framerate)))
if edit == True:
changed = True
# HANDLE EVENT
# q -> Switch themes , Esc -> to close window
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
run = False
pygame.quit()
if event.key == pygame.K_q:
ThemeIndex = (ThemeIndex + 1 ) % len(Themes)
if event.key == pygame.K_RETURN or event.key == pygame.K_p:
showPanel = not showPanel
if event.key == pygame.K_r:
debug = not debug
wireframeLine= not wireframeLine
if event.key == pygame.K_f:
wireframe = not wireframe
if event.type == pygame.MOUSEBUTTONDOWN:
MouseClicked = True
# --- CAR HANDLE INPUTS ------------
# keys = pygame.key.get_pressed()
# if keys[pygame.K_UP] or keys[pygame.K_w]:
# car.Forward(dt)
#
# elif keys[pygame.K_DOWN] or keys[pygame.K_s]:
# car.Backward(dt)
#
# elif keys[pygame.K_SPACE]:
# car.Brake(dt)
# else:
# car.fixed(dt)
#
# if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
# car.Right(dt)
# elif keys[pygame.K_LEFT] or keys[pygame.K_a]:
# car.Left(dt)
# else:
# car.resetSteering()
# ----------------------------------
for index, car in enumerate(cars):
car.Forward(dt)
genes[index].fitness += 0.1
output = nets[index].activate(
(
abs(car.intersections[0]["distance"]),
abs(car.intersections[1]["distance"]),
abs(car.intersections[2]["distance"]),
abs(car.intersections[3]["distance"]),
abs(car.intersections[4]["distance"]),
)
)
i = output.index(max(output))
if i == 0:
car.Left(dt)
else:
car.Right(dt)
# if output[0] > 0.6:
# car.Right(dt)
# elif output[1] > 0.6:
# car.Left(dt)
car.constrainSteering()
if changed == True:
for i in range(N_POINTS ):
p1 = track.GetSplinePoints(i * SPLINE_RESOLUTION, True)
g1 = track.GetSplineGradient(i * SPLINE_RESOLUTION, True)
glength = sqrt(g1[0] * g1[0] + g1[1] * g1[1])
trackTopBound.points[i].x = p1[0] - TRACK_WIDTH * (-g1[1]/glength)
trackTopBound.points[i].y = p1[1] - TRACK_WIDTH * (g1[0]/glength)
trackBottomBound.points[i].x = p1[0] + TRACK_WIDTH * (-g1[1]/glength)
trackBottomBound.points[i].y = p1[1] + TRACK_WIDTH * (g1[0]/glength)
# draw track triangles and extract the lines out of the track
Lines = TrackTriangles(
screen ,
Top=trackTopBound,
Bottom=trackBottomBound,
themeIndex=ThemeIndex,
updateLines=True,
Lines=TrackLines,
wireframe=wireframe,
wireframeLine=wireframeLine
)
if debug:
trackBottomBound.Draw(screen, False)
trackTopBound.Draw(screen, False)
if editorMode:
track.Draw(screen, MouseClicked, edit)
if len(cars) > 0:
for index, car in enumerate(cars):
car.update(screen, dt, TrackLines, debug)
car.Draw(screen, debug)
if car.crashed == True:
pygame.draw.circle(screen, Red, car.center, 8)
genes[index].fitness -= 1
cars.pop(index)
nets.pop(index)
genes.pop(index)
survivors -= 1
else:
run = False
# Render UI
if showPanel == True:
# might need to change the way i render ui for optimisation
panel.Render(screen)
quitSave.Render(screen)
editorModeText.Render(screen)
editText.Render(screen)
wireframeModeText.Render(screen)
showLineText.Render(screen)
editorMode = editorModeToggle.Render(screen, MouseClicked)
edit = editToggle.Render(screen, MouseClicked)
wireframe = wireframeToggle.Render(screen, MouseClicked)
debug = ShowlineToggle .Render(screen, MouseClicked)
wireframeLine = debug
if edit == True:
TrackWidthText.Render(screen)
TRACK_WIDTH = WidthSlider.Render(screen)
if quitSave.state == True:
saveChange = True
run = False
for gene in genes:
gene.fitness += 2
counter += 1
GenerationText.Render(screen)
PopulationText.Render(screen)
AgentAliveText.text = "Alive : " + str(survivors)
AgentAliveText.Render(screen)
MouseClicked = False
if editorMode:
changed = True
else:
changed = False
pygame.display.flip()
# save our edited track and the lines of the track
if saveChange == True:
data = {
"TRACK":track,
"TOP_TRACK": trackTopBound,
"BOTTOM_TRACK": trackBottomBound,
"LINES": TrackLines,
"VARIABLES": {
"N_POINTS": N_POINTS,
"RESOLUTION": SPLINE_RESOLUTION,
"TRACK_WIDTH": TRACK_WIDTH
}
}
pickle.dump(data, open(track_filename, 'wb'))
# main(genomes, configfiles)
# neat setup
def run(config_path):
config = neat.config.Config(
neat.DefaultGenome,
neat.DefaultReproduction,
neat.DefaultSpeciesSet,
neat.DefaultStagnation,
config_path
)
popul = neat.Population(config)
popul.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
popul.add_reporter(stats)
winner = popul.run(Fitness,1000)
# print("\n Best genome: \n{!s}".format(winner))
if __name__ == "__main__":
local_dir = os.path.dirname(__file__) # current directory
config_path = os.path.join(local_dir, "config-feedforward.txt")
run(config_path)