forked from TomasBrezina/NeuralNetworkRacing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
403 lines (339 loc) · 13 KB
/
app.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
# -*- coding: utf-8 -*-
import json
import os
from pyglet.gl import (
GL_MODELVIEW,
GL_PROGRAM_POINT_SIZE_EXT,
GL_PROJECTION,
glBlendFunc,
glEnable,
glLineWidth,
glLoadIdentity,
glMatrixMode,
glPopMatrix,
glPushMatrix,
glViewport,
pyglet,
)
from pyglet.window import key
from constants import ASSETS_PATH, CARS_PATH, FONTS_PATH, TILES_PATH
from game.core import Simulation, Track
from game.graphics import Graphics
from game.messages import ask_save_nn_as, show_error, show_message
from game.tiles import TileManager
from models.evolution import Entity, Evolution
# load .json file
def load_json(directory):
try:
with open(directory) as json_file:
file = json.load(json_file)
return file
except Exception as e:
print(f"Failed to load: {directory} (Raised exception: {e})")
return False
# save .json file
def save_json(directory, data):
with open(directory, "w") as json_file:
json.dump(data, json_file)
# save nn as a .json file
def save_neural_network(name, weights, settings, folder="saves"):
# get name
savefiles = os.listdir(folder)
savename = name
name_count = 0
while savename + ".json" in savefiles:
name_count += 1
savename = "%s(%s)" % (name, name_count)
savefile = {
"settings": settings,
"weights": [np_arr.tolist() for np_arr in weights],
}
with open(folder + "/" + savename + ".json", "w") as json_file:
json.dump(savefile, json_file)
print("Saved ", savename)
"""
Window management.
"""
class App:
def __init__(self, settings):
### NAME OF SAVE ###
self.settings = settings
### INIT WINDOW ###
self.window = pyglet.window.Window(fullscreen=False, resizable=True)
self.window.set_caption("Racing AI")
if not self.window.fullscreen:
self.window.set_size(settings["width"], settings["height"])
self.window.set_minimum_size(400, 200)
self.init_gl()
### LOAD ICON ###
try:
icon = pyglet.image.load(os.path.join(ASSETS_PATH, "icon.ico"))
self.window.set_icon(icon)
except Exception as e:
print(f"Error >>> Loading icon (Raised exception: {e})")
### MODULES ###
self.entity = None
self.simulation = Simulation()
self.evolution = Evolution()
self.evolution.mutation_rate = self.settings["mutation_rate"]
self.graphics = Graphics(
self.window.width, self.window.height, CARS_PATH, FONTS_PATH
)
### TRACK MANAGER ###
self.tile_manager = TileManager()
self.tile_manager.load_tiles(root_dir=TILES_PATH)
### LABELS ###
self.graphics.hud.labels["name"].text = ""
### USER GUI ###
self.camera_free = False
self.camera_selected_car = None
### VARIABLES ###
self.debugging_mode = False # show track, cps, etc.
self.label_show_mode = False
self.training_mode = False
self.pause = False # pause the simulation
self.timer = 0 # number of ticks
self.timer_limit = (
self.settings["timeout_seconds"] // self.settings["render_timestep"]
) # max ticks
### CONSTANTS ###
self.CAR_SELECTION_RADIUS = 100 # max dist between car and click
### BIND EVENTS ###
self.window.event(self.on_key_press)
self.window.event(self.on_close)
self.window.event(self.on_resize)
self.window.event(self.on_draw)
self.window.event(self.on_mouse_drag)
self.window.event(self.on_mouse_scroll)
self.window.event(self.on_mouse_press)
def init_gl(self):
glViewport(0, 0, self.window.width, self.window.height)
glEnable(pyglet.gl.GL_BLEND)
glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
glLineWidth(5)
glEnable(GL_PROGRAM_POINT_SIZE_EXT)
def on_mouse_press(self, x, y, button, modifiers):
if not self.camera_free:
car, dist = self.simulation.get_closest_car_to(
*self.graphics.camera.translate_onscreen_point(x, y)
)
if dist < self.CAR_SELECTION_RADIUS:
self.camera_selected_car = car
# when key is released
def on_key_press(self, symbol, modifiers):
# save the nn
if symbol == key.S:
self.window.set_fullscreen(False)
if self.evolution.best_result.nn:
directory = "saves"
filename = ask_save_nn_as()
if filename:
filename = filename.split("/")[-1] # filename and ext
self.entity.save_file(save_name=filename, folder=directory)
show_message(f"Succesfully saved {filename} to /{directory}")
else:
show_error("No neural network to save yet.")
print("Cannot save.")
# TODO: load file
if symbol == key.T:
self.change_track(track=self.tile_manager.generate_track(shape=(5, 3)))
elif symbol == key.DELETE:
self.end_simulation()
# fullscreen on/off
elif symbol == key.F:
# self.window.maximize()
self.window.set_fullscreen(not self.window.fullscreen)
if not self.window.fullscreen:
self.window.set_size(self.settings["width"], self.settings["height"])
# pause on/off
elif symbol == key.P:
self.pause = not self.pause
# show on/off
elif symbol == key.D:
self.debugging_mode = not self.debugging_mode
elif symbol == key.L:
self.label_show_mode = not self.label_show_mode
elif symbol == key.N:
self.training_mode = not self.training_mode
# control camera
elif symbol == key.C:
self.camera_free = not self.camera_free
elif symbol == key.LEFT:
self.camera_switch_cars(-1)
elif symbol == key.RIGHT:
self.camera_switch_cars(1)
elif symbol == key.UP:
self.camera_selected_car = self.simulation.get_leader()
elif symbol == key.DOWN:
self.camera_selected_car = self.simulation.get_leader()
elif symbol == key.NUM_ADD:
self.graphics.camera.set_target_zoom_center(1.4)
elif symbol == key.NUM_SUBTRACT:
self.graphics.camera.set_target_zoom_center(0.6)
def on_mouse_drag(self, x, y, dx, dy, buttons, modif):
if self.camera_free:
# left
if buttons == 1:
self.graphics.camera.drag(-dx, -dy)
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
if scroll_y > 0:
self.graphics.camera.set_target_zoom(x, y, 1.4)
else:
self.graphics.camera.set_target_zoom(x, y, 0.6)
# switch cars
def camera_switch_cars(self, step):
if self.camera_selected_car:
new_ind = self.simulation.cars.index(self.camera_selected_car)
while True:
new_ind -= step
self.camera_selected_car = self.simulation.cars[
new_ind % len(self.simulation.cars)
]
if self.camera_selected_car.active:
break
# when closed (unnecessary)
def on_close(self):
pyglet.clock.unschedule(self.update)
# when resized
def on_resize(self, width, height):
self.graphics.on_resize(width, height)
# every frame
def on_draw(self):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glPushMatrix()
self.graphics.clear()
if self.training_mode:
glPopMatrix()
self.graphics.draw_hud()
return
self.graphics.set_camera_view()
self.simulation.track.bg.blit(0, 0)
# draw cars
self.graphics.car_batch.draw()
# CAR LABELS - F1
if self.label_show_mode:
count = 1
for car in self.simulation.get_cars_sorted():
car.label.labels["order"].text = str(count)
count += 1
self.graphics.draw_car_labels(self.simulation.cars)
# draw hidden details
if self.debugging_mode:
self.graphics.draw_grid()
# draw edge of the track
for vl in self.simulation.track.vertex_lists:
self.graphics.draw_vertex_list(vl)
self.graphics.draw_cps(self.simulation.track.cps_arr)
# selected car
self.camera_selected_car.update_info()
self.graphics.highligh_car(self.camera_selected_car)
self.graphics.draw_car_info(self.camera_selected_car)
self.graphics.draw_car_sensors(self.camera_selected_car)
# draw checked lines
lines_arr = self.simulation.get_car_cp_lines(self.camera_selected_car)
for i in lines_arr:
for j in i:
self.graphics.draw_line(j, (0.5, 1, 1, 1))
glPopMatrix()
self.graphics.draw_hud()
# create new generation from best nns
def new_generation(self):
self.graphics.clear_batch()
results = self.simulation.get_nns_results()
self.simulation.generate_cars_from_nns(
nns=self.evolution.get_new_generation_from_results(
results, self.settings["population"]
),
parameters=self.entity.get_car_parameters(),
images=self.graphics.car_images,
batch=self.graphics.car_batch,
labels_batch=self.graphics.car_labels_batch,
)
self.entity.set_nn_from_result(self.evolution.find_best_result(results))
self.entity.increment_gen_count()
self.update_labels(self.entity)
self.camera_selected_car = self.simulation.cars[0]
self.graphics.update_sprites(self.simulation.cars)
# every frame
def update(self, dt):
if not self.pause:
# car behaviour
active = self.simulation.behave(dt)
if not active:
self.timer = 0
self.new_generation()
self.simulation.update(dt)
# CAMERA
if not self.camera_free:
if self.camera_selected_car:
if not self.camera_selected_car.active:
self.camera_selected_car = self.simulation.get_leader()
self.graphics.camera.set_target(
self.camera_selected_car.xpos, self.camera_selected_car.ypos
)
self.graphics.camera.update_movement()
self.graphics.camera.update_zoom()
# update sprites position and rotation
self.graphics.update_sprites(self.simulation.cars)
self.update_timelimit()
# each tick
def update_timelimit(self):
self.timer += 1
if self.timer >= self.timer_limit:
self.timer = 0
self.new_generation()
seconds = int(self.timer * self.settings["render_timestep"])
self.graphics.hud.labels["time"].text = (
"Time: " + str(seconds) + " / " + str(self.settings["timeout_seconds"])
)
# update labels from self entity
def update_labels(self, entity: Entity):
self.graphics.hud.labels["name"].text = self.entity.name[
:10
] # first 10 characters to fit screen
self.graphics.hud.labels["gen"].text = "Generation: " + str(
int(self.entity.gen_count)
)
self.graphics.hud.labels["max"].text = "Best score: " + str(
self.entity.max_score
)
def change_track(self, track):
self.timer = 0
self.simulation.track = track
self.new_generation()
# start of simulation
def start_simulation(self, entity: Entity, track: Track = None):
# entity
self.entity = entity
self.entity.increment_gen_count()
# set track or generate random
self.simulation.track = (
track
if track is not None
else self.tile_manager.generate_track(shape=(5, 3))
)
# set labels
self.update_labels(self.entity)
self.simulation.generate_cars_from_nns(
nns=self.evolution.get_new_generation(
[self.entity.get_nn()], self.settings["population"]
),
parameters=self.entity.get_car_parameters(),
images=self.graphics.car_images,
batch=self.graphics.car_batch,
labels_batch=self.graphics.car_labels_batch,
)
self.camera_selected_car = self.simulation.get_leader()
self.graphics.update_sprites(self.simulation.cars)
self.on_resize(self.window.width, self.window.height)
pyglet.clock.schedule_interval(self.update, self.settings["render_timestep"])
pyglet.app.run()
def end_simulation(self):
pyglet.clock.unschedule(self.update)
self.simulation = False
# end
def exit(self):
pyglet.app.exit()