-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
286 lines (235 loc) · 8.74 KB
/
Copy pathmain.py
File metadata and controls
286 lines (235 loc) · 8.74 KB
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
import pygame
import os
import random
import math
import sys
import neat
pygame.init()
# Global Constants
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 1100
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
RUNNING = [pygame.image.load(os.path.join("Assets/Dino", "DinoRun1.png")),
pygame.image.load(os.path.join("Assets/Dino", "DinoRun2.png"))]
JUMPING = pygame.image.load(os.path.join("Assets/Dino", "DinoJump.png"))
SMALL_CACTUS = [pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus1.png")),
pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus2.png")),
pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus3.png"))]
LARGE_CACTUS = [pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus1.png")),
pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus2.png")),
pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus3.png"))]
BG = pygame.image.load(os.path.join("Assets/Other", "Track.png"))
FONT = pygame.font.Font('freesansbold.ttf', 20)
class Dinosaur:
X_POS = 80
Y_POS = 310
JUMP_VEL = 8.5
def __init__(self, img=RUNNING[0]):
self.image = img
self.dino_run = True
self.dino_jump = False
self.jump_vel = self.JUMP_VEL
self.rect = pygame.Rect(self.X_POS, self.Y_POS, img.get_width(), img.get_height())
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.step_index = 0
def update(self):
if self.dino_run:
self.run()
if self.dino_jump:
self.jump()
if self.step_index >= 10:
self.step_index = 0
def jump(self):
self.image = JUMPING
if self.dino_jump:
self.rect.y -= self.jump_vel * 4
self.jump_vel -= 0.8
if self.jump_vel <= -self.JUMP_VEL:
self.dino_jump = False
self.dino_run = True
self.jump_vel = self.JUMP_VEL
def run(self):
self.image = RUNNING[self.step_index // 5]
self.rect.x = self.X_POS
self.rect.y = self.Y_POS
self.step_index += 1
def draw(self, SCREEN):
SCREEN.blit(self.image, (self.rect.x, self.rect.y))
pygame.draw.rect(SCREEN, self.color, (self.rect.x, self.rect.y, self.rect.width, self.rect.height), 2)
for obstacle in obstacles:
pygame.draw.line(SCREEN, self.color, (self.rect.x + 54, self.rect.y + 12), obstacle.rect.center, 2)
class Obstacle:
def __init__(self, image, number_of_cacti):
self.image = image
self.type = number_of_cacti
self.rect = self.image[self.type].get_rect()
self.rect.x = SCREEN_WIDTH
def update(self):
self.rect.x -= game_speed
if self.rect.x < -self.rect.width:
obstacles.pop()
def draw(self, SCREEN):
SCREEN.blit(self.image[self.type], self.rect)
class SmallCactus(Obstacle):
def __init__(self, image, number_of_cacti):
super().__init__(image, number_of_cacti)
self.rect.y = 325
class LargeCactus(Obstacle):
def __init__(self, image, number_of_cacti):
super().__init__(image, number_of_cacti)
self.rect.y = 300
def remove(index):
dinosaurs.pop(index)
ge.pop(index)
nets.pop(index)
def distance(pos_a, pos_b):
dx = pos_a[0]-pos_b[0]
dy = pos_a[1]-pos_b[1]
return math.sqrt(dx**2+dy**2)
def eval_genomes(genomes, config):
global game_speed, x_pos_bg, y_pos_bg, obstacles, dinosaurs, ge, nets, points
clock = pygame.time.Clock()
points = 0
obstacles = []
dinosaurs = []
ge = []
nets = []
x_pos_bg = 0
y_pos_bg = 380
game_speed = 20
text_y_position = 50
for genome_id, genome in genomes:
dinosaurs.append(Dinosaur())
ge.append(genome)
net = neat.nn.FeedForwardNetwork.create(genome, config)
nets.append(net)
genome.fitness = 0
def score():
global points, game_speed
points += 1
if points % 100 == 0:
game_speed += 1
text = FONT.render(f'Points: {str(points)}', True, (0, 0, 0))
SCREEN.blit(text, (950, 50))
def statistics(outputs):
global dinosaurs, game_speed, ge
output_total = 0
for output in outputs:
output_total += output[0]
if len(outputs) <= 0: output_average = 0
else: output_average = output_total / len(outputs)
total_dino_y = 0
total_jump_vel = 0
for dinosaur in dinosaurs:
total_dino_y += dinosaur.rect.y
total_jump_vel += dinosaur.jump_vel
if len(dinosaurs) <= 0:
average_jump_vel = 0
average_dino_y = 0
else:
average_jump_vel = total_jump_vel / len(dinosaurs)
average_dino_y = total_dino_y / len(dinosaurs)
average_dino_y = abs(average_dino_y - 310)
text_1 = FONT.render(f'Dinosaurs Alive: {str(len(dinosaurs))}', True, (0, 0, 0))
text_2 = FONT.render(f'Generation: {pop.generation+1}', True, (0, 0, 0))
text_3 = FONT.render(f'Game Speed: {str(game_speed)}', True, (0, 0, 0))
text_4 = FONT.render(f'Average Decision Value: {output_average}', True, (0, 0, 0))
text_5 = FONT.render(f'Average Jump Velocity: {average_jump_vel}', True, (0, 0, 0))
text_6 = FONT.render(f'Average Dino Height: {average_dino_y}', True, (0, 0, 0))
SCREEN.blit(text_1, (text_y_position, 420))
SCREEN.blit(text_2, (text_y_position, 450))
SCREEN.blit(text_3, (text_y_position, 480))
SCREEN.blit(text_4, (text_y_position, 510))
SCREEN.blit(text_5, (text_y_position, 540))
SCREEN.blit(text_6, (text_y_position, 570))
def background():
global x_pos_bg, y_pos_bg
image_width = BG.get_width()
SCREEN.blit(BG, (x_pos_bg, y_pos_bg))
SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
if x_pos_bg <= -image_width:
x_pos_bg = 0
x_pos_bg -= game_speed
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print('space')
for i, dinosaur in enumerate(dinosaurs):
remove(i)
elif event.key == pygame.K_UP:
print('up')
game_speed += 1
elif event.key == pygame.K_DOWN:
print('down')
game_speed -= 1
elif event.key == pygame.K_r:
print('r')
main()
SCREEN.fill((255, 255, 255))
for dinosaur in dinosaurs:
dinosaur.update()
dinosaur.draw(SCREEN)
if len(dinosaurs) == 0:
break
if len(obstacles) == 0:
cactus_type = random.randint(0, 1)
if cactus_type == 0:
obstacles.append(SmallCactus(SMALL_CACTUS, random.randint(0, 2)))
elif cactus_type == 1:
obstacles.append(LargeCactus(LARGE_CACTUS, random.randint(0, 2)))
for obstacle in obstacles:
obstacle.draw(SCREEN)
obstacle.update()
for i, dinosaur in enumerate(dinosaurs):
if dinosaur.rect.colliderect(obstacle.rect):
#ge[i].fitness -= 1
remove(i)
else:
ge[i].fitness = points
outputs = []
for i, dinosaur in enumerate(dinosaurs):
output = nets[i].activate((
dinosaur.rect.y,
dinosaur.jump_vel,
distance((dinosaur.rect.x, dinosaur.rect.y), obstacle.rect.midtop),
points,
game_speed,
cactus_type,
len(obstacles)
))
if output[0] > 0.5 and dinosaur.rect.y == dinosaur.Y_POS:
dinosaur.dino_jump = True
dinosaur.dino_run = False
outputs.append(output)
statistics(outputs)
score()
background()
clock.tick(30)
pygame.display.update()
# Setup the NEAT Neural Network
def run(config_path):
global pop
config = neat.config.Config(
neat.DefaultGenome,
neat.DefaultReproduction,
neat.DefaultSpeciesSet,
neat.DefaultStagnation,
config_path
)
pop = neat.Population(config)
pop.run(eval_genomes, 50)
def main():
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'config.txt')
run(config_path)
if __name__ == '__main__':
try:
main()
except Exception as e:
print(e)
main()