-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathmain.py
229 lines (181 loc) · 6.71 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
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
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():
global dinosaurs, game_speed, ge
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))
SCREEN.blit(text_1, (50, 450))
SCREEN.blit(text_2, (50, 480))
SCREEN.blit(text_3, (50, 510))
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()
SCREEN.fill((255, 255, 255))
for dinosaur in dinosaurs:
dinosaur.update()
dinosaur.draw(SCREEN)
if len(dinosaurs) == 0:
break
if len(obstacles) == 0:
rand_int = random.randint(0, 1)
if rand_int == 0:
obstacles.append(SmallCactus(SMALL_CACTUS, random.randint(0, 2)))
elif rand_int == 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)
for i, dinosaur in enumerate(dinosaurs):
output = nets[i].activate((dinosaur.rect.y,
distance((dinosaur.rect.x, dinosaur.rect.y),
obstacle.rect.midtop)))
if output[0] > 0.5 and dinosaur.rect.y == dinosaur.Y_POS:
dinosaur.dino_jump = True
dinosaur.dino_run = False
statistics()
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)
if __name__ == '__main__':
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'config.txt')
run(config_path)