-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
180 lines (139 loc) · 5.13 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
import pygame
import neat
import os
import pickle
from bird import Bird
from base import Base
from pipe import Pipe
pygame.font.init()
draw_lines = False
floor = 730
win_width = 600
win_height = 800
win = pygame.display.set_mode((win_width, win_height))
bg_img = pygame.transform.scale(pygame.image.load(os.path.join("assets","bg.png")).convert_alpha(), (600, 900))
stat_font = pygame.font.SysFont("comicsans", 50)
end_font = pygame.font.SysFont("comicsans", 70)
pygame.display.set_caption("Flappy Bird")
gen = 0
def draw_window(win, birds, pipes, base, score, gen, pipe_ind):
"""
draws the windows for the main game loop
:param win: pygame window surface
:param bird: a Bird object
:param pipes: List of pipes
:param score: score of the game (int)
:param gen: current generation
:param pipe_ind: index of closest pipe
"""
if gen == 0:
gen = 1
win.blit(bg_img, (0,0))
for pipe in pipes:
pipe.draw(win)
base.draw(win)
for bird in birds:
if draw_lines:
try:
pygame.draw.line(win, (255,0,0), (bird.x+bird.img.get_width()/2, bird.y + bird.img.get_height()/2), (pipes[pipe_ind].x + pipes[pipe_ind].PIPE_TOP.get_width()/2, pipes[pipe_ind].height), 5)
pygame.draw.line(win, (255,0,0), (bird.x+bird.img.get_width()/2, bird.y + bird.img.get_height()/2), (pipes[pipe_ind].x + pipes[pipe_ind].PIPE_BOTTOM.get_width()/2, pipes[pipe_ind].bottom), 5)
except:
pass
bird.draw(win)
score_label = stat_font.render("Score: " + str(score),1,(255,255,255))
win.blit(score_label, (win_width - score_label.get_width() - 15, 10))
score_label = stat_font.render("Gens: " + str(gen-1),1,(255,255,255))
win.blit(score_label, (10, 10))
score_label = stat_font.render("Alive: " + str(len(birds)),1,(255,255,255))
win.blit(score_label, (10, 50))
pygame.display.update()
def eval_genomes(genomes, config):
"""
runs the simulation of the current population of
birds and sets their fitness based on the distance they
reach in the game.
"""
global win, gen
win = win
gen += 1
nets = []
birds = []
ge = []
for genome_id, genome in genomes:
genome.fitness = 0
net = neat.nn.FeedForwardNetwork.create(genome, config)
nets.append(net)
birds.append(Bird(230,350))
ge.append(genome)
base = Base(floor)
pipes = [Pipe(700)]
score = 0
clock = pygame.time.Clock()
run = True
while run and len(birds) > 0:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
quit()
pipe_ind = 0
if len(birds) > 0:
if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].pipe_top.get_width():
pipe_ind = 1
for x, bird in enumerate(birds):
ge[x].fitness += 0.1
bird.move()
output = nets[birds.index(bird)].activate((bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom)))
if output[0] > 0.5:
bird.jump()
base.move()
rem = []
add_pipe = False
for pipe in pipes:
pipe.move()
for bird in birds:
if pipe.collide(bird, win):
ge[birds.index(bird)].fitness -= 1
nets.pop(birds.index(bird))
ge.pop(birds.index(bird))
birds.pop(birds.index(bird))
if pipe.x + pipe.pipe_top.get_width() < 0:
rem.append(pipe)
if not pipe.passed and pipe.x < bird.x:
pipe.passed = True
add_pipe = True
if add_pipe:
score += 1
for genome in ge:
genome.fitness += 5
pipes.append(Pipe(win_width))
for r in rem:
pipes.remove(r)
for bird in birds:
if bird.y + bird.img.get_height() - 10 >= floor or bird.y < -50:
nets.pop(birds.index(bird))
ge.pop(birds.index(bird))
birds.pop(birds.index(bird))
draw_window(win, birds, pipes, base, score, gen, pipe_ind)
if score == 100:
pickle.dump(nets[0],open("best.pickle", "wb"))
break
def run(config_file):
"""
runs the NEAT algorithm to train a neural network to play flappy bird.
:param config_file: location of config file
"""
config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation,
config_file)
p = neat.Population(config)
p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)
winner = p.run(eval_genomes, 50)
print('\nBest genome:\n{!s}'.format(winner))
if __name__ == '__main__':
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'config.txt')
run(config_path)