Giter VIP home page Giter VIP logo

neat-flappy-bird's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

neat-flappy-bird's Issues

Small error

Hi Tim,

I was going through your code and realized a small formatting error. I don't know if you still keep up with this repo but I though I'd point it out.
In your file "Flappy_bird.py", you wrote this starting on line 368

for pipe in pipes:
    ...
    for bird in birds:
        ...

    if not pipe.passed and pipe.x < bird.x:
        pipe.passed = True
        add_pipe = True

The problem on line 381 is that bird.x cannot be referenced because it is not inside the birds for loop. I do not know if this was meant on purpose or if this error even occurs. I would suggest changing it to

if not pipe.passed and pipe.x < birds[0].x:

Thank you for your time and thanks for the videos!

AttributeError:

WIDTH = BASE_IMG.get_width()
AttributeError: 'list' object has no attribute 'get_width

no visualize in neat anymore

Hi, i believe that NEAT doesn,t have a visualize module anymore in it, does someone know where i can download that?
this is the error
File "/Users/m/PycharmProjects/FlappyBirdML/Flappy2?.py", line 13, in
import visualize
ModuleNotFoundError: No module named 'visualize'

Weird TypeError

Ok so I am at the end of the second video, and I try running the sript with ctrl+ b, but the window opens and closes immediately.

So I went to my terminal to run it, and got a Type error, saying 'TypeError: argument 1 must be pygame.Surface, not list'

Any clue how to fix this?
Edit: here is my code: https://pastebin.com/ugMudCNt

Pipes wont appear.

I have finished the tutorial but keep getting the error message,

AttributeError: 'str' object has no attribute 'stagnation_type'

which says it occurs in the file

File "/usr/local/lib/python3.7/dist-packages/neat/population.py

Any help on why this might happen would be great!

Project dependencies may have API risk issues

Hi, In NEAT-Flappy-Bird, inappropriate dependency versioning constraints can cause risks.

Below are the dependencies and version constraints that the project is using

numpy
pygame
neat-python
graphviz
matplotlib

The version constraint == will introduce the risk of dependency conflicts because the scope of dependencies is too strict.
The version constraint No Upper Bound and * will introduce the risk of the missing API Error because the latest version of the dependencies may remove some APIs.

After further analysis, in this project,
The version constraint of dependency graphviz can be changed to >=0.3,<=0.20.

The above modification suggestions can reduce the dependency conflicts as much as possible,
and introduce the latest version as much as possible without calling Error in the projects.

The invocation of the current project includes all the following methods.

The calling methods from the graphviz
graphviz.Digraph
The calling methods from the all methods
bird.jump
len
matplotlib.pyplot.grid
pipe.move
matplotlib.pyplot.figure
pygame.font.init
set.add
format
neat.Population.add_reporter
abs
birds.pop
pipe_ind.pipes.PIPE_TOP.get_width
statistics.get_species_sizes
statistics.get_fitness_mean
matplotlib.pyplot.subplot
round
draw_window
pipe.PIPE_TOP.get_width
str
bird.get_mask.overlap
os.path.join.pygame.image.load.convert_alpha
neat.Population.run
Pipe.remove
birds.index
neat.nn.FeedForwardNetwork.create
matplotlib.pyplot.savefig
ax.stackplot
set
bird.img.get_width
pygame.time.Clock.tick
matplotlib.pyplot.title
enumerate
pygame.display.set_mode
Bird
self.PIPE_TOP.get_height
blitRotateCenter
pipes.PIPE_TOP.get_width
pygame.image.load
matplotlib.pyplot.close
pygame.time.Clock
pygame.event.get
statistics.get_fitness_stdev
pygame.display.set_caption
pygame.display.update
os.path.dirname
os.path.join
neat.Population
range
bird.move
pipe.collide
matplotlib.pyplot.xlabel
pipe_ind.pipes.PIPE_BOTTOM.get_width
matplotlib.pyplot.ylabel
matplotlib.pyplot.legend
birds.append
pygame.quit
genome.connections.values
ge.pop
node_colors.get
matplotlib.pyplot.plot
pipe.draw
random.randrange
type
bird.img.get_height
Pipe
matplotlib.pyplot.subplots
surf.blit
Base
warnings.warn
quit
bird.get_mask
bird.birds.index.nets.activate
copy.copy
Pipe.append
win.blit
pygame.draw.line
nets.pop
matplotlib.pyplot.show
graphviz.Digraph.edge
pygame.transform.scale
run
node_names.get
nets.append
neat.StatisticsReporter
pygame.transform.scale2x
rem.append
self.set_height
neat.config.Config
Base.move
ge.append
print
matplotlib.pyplot.gca.set_yscale
pygame.font.SysFont
graphviz.Digraph
graphviz.Digraph.node
numpy.array
pygame.mask.from_surface
pygame.font.SysFont.render
STAT_FONT.render.get_width
pygame.transform.rotate
pygame.transform.rotate.get_rect
neat.StdOutReporter
Base.draw
graphviz.Digraph.render
pygame.transform.flip
bird.draw
image.get_rect
genome.nodes.keys
pygame.transform.scale2x.get_width
matplotlib.pyplot.gca

@developer
Could please help me check this issue?
May I pull a request to fix it?
Thank you very much.

Bird doesn't seem to rotate

new_rect = rotated_image.get_rect(center = image.get_rect(topleft = topleft).center)
DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using int is deprecated, and may be removed in a future version of Python.

Neat Runtime Error

When passing these 3 arguments to the activate function it throws a runtime error. It seems like the package has changes this function to no longer support more then 2 inputs, because when I run this activate function with 2 arguments it runs but the bird immediately die.

output = nets[birds.index(bird)].activate(
    (
        bird.y,
        abs(bird.y - pipes[pipe_ind].height),
        abs(bird.y - pipes[pipe_ind].bottom),
    )
)

File "path/to/tensor/lib/python3.10/site-packages/neat/nn/feed_forward.py", line 14, in activate
raise RuntimeError("Expected {0:n} inputs, got {1:n}".format(len(self.input_nodes), len(inputs)))
RuntimeError: Expected 2 inputs, got 3

Can't install pygame in gitpod

I can't run the project in gitpod because of this installation error:

gitpod /workspace/NEAT-Flappy-Bird $  HISTFILE=/workspace/.gitpod/cmd-0 history -r; {
> pip3 install -r requirements.txt
> } && {
> python3 flappy_bird.py
> }
Collecting numpy
  Downloading numpy-1.19.0-cp38-cp38-manylinux2010_x86_64.whl (14.6 MB)
     |████████████████████████████████| 14.6 MB 4.5 MB/s 
Collecting pygame
  Downloading pygame-1.9.6.tar.gz (3.2 MB)
     |████████████████████████████████| 3.2 MB 25.1 MB/s 
    ERROR: Command errored out with exit status 1:
     command: /home/gitpod/.pyenv/versions/3.8.3/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-69qddxjx/pygame/setup.py'"'"'; __file__='"'"'/tmp/pip-install-69qddxjx/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-xy9_mix1
         cwd: /tmp/pip-install-69qddxjx/pygame/
    Complete output (12 lines):
    
    
    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using UNIX configuration...
    
    /bin/sh: 1: sdl-config: not found
    /bin/sh: 1: sdl-config: not found
    /bin/sh: 1: sdl-config: not found
    
    Hunting dependencies...
    WARNING: "sdl-config" failed!
    Unable to run "sdl-config". Please make sure a development version of SDL is installed.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Quoting this Stack Exchange answer:

The currently official pygame 1.9.6 is not compatible with Python 3.8

config

for some reason i keep getting this error.

/Users/banginpadr/Desktop/coders/ai/venv/bin/python /Users/banginpadr/Desktop/coders/ai/neuton.py pygame 1.9.6 Hello from the pygame community. https://www.pygame.org/contribute.html Traceback (most recent call last): File "/Users/banginpadr/Desktop/coders/ai/neuton.py", line 440, in <module> run(config_path) File "/Users/banginpadr/Desktop/coders/ai/neuton.py", line 414, in run config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, AttributeError: module 'neat' has no attribute config

pygame.error: Couldn't open imgs\pipe.png (imgs folder is still there) python 3.7.6

ts/NEAT-Flappy-Bird/flappy_bird.py
pygame 2.0.0.dev6 (SDL 2.0.10, python 3.7.6)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "c:/Users/osty2/Documents/programing_projects/NEAT-Flappy-Bird/flappy_bird.py", line 28, in
pipe_img = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs","pipe.png")).convert_alpha())
pygame.error: Couldn't open imgs\pipe.png
PS C:\Users\osty2\Documents\programing_projects>

VScode - direct clone.

Screenshot (342)
Screenshot (343)

winner = p.run(eval_genomes,50)

So, I've been using this tutorial to make a game of my own.
however, when using NEAT, I cannot make the program do more than one generation and I have no idea why.

import math
import pygame
import random
import os
import neat
import pickle
import time

pygame.init()
screenwidth = 1000
screenheight = 750

screen = pygame.display.set_mode((screenwidth,screenheight))

LunarLanderImage = pygame.image.load("LunarLanderImage.jpg")

class Lander(object):

    def __init__(self, x_pos, y_pos, angle, gravity):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.angle = angle
        self.gravity = gravity
        self.initial_mass = 1000
        self.fuel = 500
        self.mass = self.initial_mass + self.fuel
        self.thrust = 0
        self.weight = self.mass * self.gravity
        self.x_vel = 0
        self.y_vel = 0
        self.y_acceleration = 0
        self.x_acceleration = 0
        self.img = pygame.image.load("Lander.png")
        self.img = pygame.transform.scale(self.img, (50,50))
        self.img2 = pygame.image.load("Lander2.png")
        self.img2 = pygame.transform.scale(self.img2, (50,50))
        self.thrust_on = False
        self.rotatedImage = self.img
        self.rotatedImage2 = self.img2
        self.death = False
        self.score = 0
        self.start_time = time.time()
    def move(self):
        keys = pygame.key.get_pressed()
        
        if  keys[pygame.K_RIGHT] == True:
            self.angle -= 0.5
        elif keys[pygame.K_LEFT] == True:
            self.angle += 0.5
        elif keys[pygame.K_UP] == True:
            if self.fuel >0:
                self.fuel -= 0.5
                self.thrust = 1800
                self.thrust_on = True
        else:
            self.thrust = 0
            self.thrust_on = False

    def moveLeft(self):
        self.angle += 0.5
    def  moveRight(self):
        self.angle -= 0.5
    def thruster(self):
        if self.fuel >0:
            self.fuel -= 10
            self.thrust = 1800
            self.thrust_on = True

    def draw(self, screen):
        if self.thrust_on == False:
            self.rotatedImage = pygame.transform.rotate(self.img, self.angle)
            new_rect = self.rotatedImage.get_rect(center = self.img.get_rect(center = (self.x_pos,self.y_pos)).center)
            screen.blit(self.rotatedImage, new_rect)
        else:
            self.rotatedImage2 = pygame.transform.rotate(self.img2, self.angle)
            new_rect2 = self.rotatedImage2.get_rect(center = self.img.get_rect(center = (self.x_pos,self.y_pos)).center)
            screen.blit(self.rotatedImage2, new_rect2)

    def calculate(self):
        self.y_acceleration = ((self.weight - ((self.thrust*math.cos((self.angle%360)*( 3.1416/180)))))/self.mass)/50
        
        self.x_acceleration = ((self.thrust*math.sin(((self.angle%360)*(-1))*( 3.1416/180)))/self.mass)/50
        
        self.x_vel += self.x_acceleration
        self.y_vel += self.y_acceleration

        self.x_pos += self.x_vel
        self.y_pos += self.y_vel
        self.score +=1

        self.current_time = time.time()
        #print(self.current_time - self.start_time)
        
        if self.y_pos > 750:
            self.death = True
            self.y_pos = 0
            self.y_acceleration = 0
            self.y_vel = 0
            self.x_pos = 325
            self.x_acceleration = 0
            self.x_vel = 0
            self.fuel = 500
            self.angle = 0
        if self.x_pos > 750 or self.x_pos <0:
            self.death = True
            self.x_pos = 325
            self.x_acceleration = 0
            self.x_vel = 0
            self.y_pos = 0
            self.y_acceleration = 0
            self.y_vel = 0
            self.fuel = 500
            self.angle = 0

    def collision(self):
        self.momentum = self.mass * (math.sqrt((self.x_vel**2)+(self.y_vel**2)))
        if self.momentum > 750:
            self.death = True
        else:
            self.score = 100
        self.x_vel = 0
        self.y_vel = 0
        self.x_acceleration = 0
        self.y_acceletation = 0

class Planet (object):

    def __init__(self, backgroundImg,terrainImg, gravity, end_goal, atmosphere):
        self.backgroundImg = backgroundImg
        self.terrainImg = terrainImg
        self.gravity = gravity
        self.end_goal = end_goal
        self.atmosphere = atmosphere

    def draw(self, screen):
        screen.blit(self.backgroundImg, (0,0))
        screen.blit(self.terrainImg, (0, 420))

def collision(lander, terrain):
    
    if lander.thrust_on == False:
        lander_mask = pygame.mask.from_surface(lander.rotatedImage)
    else:
        lander_mask = pygame.mask.from_surface(lander.rotatedImage2)
    terrain_mask = pygame.mask.from_surface(terrain)

    offset = (int(lander.x_pos-5), int(lander.y_pos - 450))

    
    if terrain_mask.overlap(lander_mask, offset):
        #print("True")
        lander.collision()
        


def deathScreen(lander):
    pass


moon = Planet(pygame.image.load("MoonBackground.png"), pygame.image.load("MoonTerrain1.png"),0.8, [], False)
#lander = Lander(400,100, 0, 0.8)


def redraw():
    
    screen.fill((0,0,0))
    moon.draw(screen)
    font = pygame.font.SysFont('comicsans', 50)
    if len(landers) > 0:
        x_vel_text = font.render(("X Velocity:" + str(round(landers[0].x_vel,3))), 1, (255,255,255))
        y_vel_text = font.render(("Y Velocity:" + str(round(landers[0].y_vel,3))), 1, (255,255,255))
    ##    angle_text = font.render(("Angle:" + str(round(lander.angle))), 1, (255,255,255))
        screen.blit(x_vel_text, (600, 25))
        screen.blit(y_vel_text, (600, 75))
##    screen.blit(angle_text, (600, 125))
    for lander in landers:
        lander.draw(screen)
    pygame.display.update()


gen = 0
def eval_genomes(genomes,config):
    global landers, gen
    gen +=1
    run = True
    nets = []
    ge = []
    landers = []

    for genome_id,g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g,config)
        nets.append(net)
        landers.append(Lander(random.randint(100,900),100, 0, 0.8))
        g.fitness = 0
        ge.append(g)

    clock = pygame.time.Clock()
    while run == True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
        for x, lander in enumerate(landers):
            lander.calculate()
            ge[x].fitness += 0.1
            output = nets[x].activate((lander.x_pos, lander.y_pos, lander.angle, lander.x_vel, lander.y_vel))
            #print(output)

            if output[0] > 0.5 and lander.fuel > 0:
                lander.thruster()
            if output[1]>0.5:
                lander.moveLeft()
            if output[2] > 0.5:
                lander.moveRight()


        for x,lander in enumerate(landers):
            if lander.death == False:
                #lander.move()
                #lander.calculate()
                
                
                collision(lander, moon.terrainImg)
                for g in ge:
                    g.fitness += 1
            else:
                ge[x].fitness -=1
                landers.pop(x)
                nets.pop(x)
                ge.pop(x)

        redraw()

##        if len(landers) <= 0:
##            run = False
##            break

        



def run(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))

        
        #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("LunarConfigFile.txt")
    run(config_path)

#pygame.quit()

module neat

line 407

AttributeError: module 'neat' has no attribute 'config'

unsure of how to move to the next generation

hello,
I worked with your code but tried to implement it online using pyautogui. however I have a issue with it not moving to the next generation and I don't have any idea how to do that. this is done on flappy bird.io by the way

import neat
import pyautogui
import os
import time
import numpy
'''

distance between top pipe and bottom pipe is pipe y- bird y if two y's then closest to bird # location of gap

fitness function is time since starting

for fitness function

a = time.time() called when starting
b = time .time() called when dead
(b-a) = time of flight for bird
'''

5 seconds to first pipe

just needs a if bird y = on bottom of screen

def main(genomes, config):
for x in range(0,1):

            try:
            
                    bird = pyautogui.locateOnScreen("fpb.png",  confidence=0.2, grayscale=True,  region=(850, 145, 975, 706))
                    nets = []
                    ge = []
                    birds = []

                    for genome_id, genome in genomes: # gnomes
                            net = neat.nn.FeedForwardNetwork.create(genome, config)
                            nets.append(net)
                            birds.append(bird)
                               
                            genome.fitness = 0
                            ge.append(genome)
                    

                    
                            
                    
                    a = 1
                    b = 1
                            

                    for x, bird in enumerate(birds):
                            a = 1
                            c = 1
                            start_time = time.time()
                            while a == c:
                                    h = pyautogui.locateCenterOnScreen("fpb.png",  confidence=0.4, grayscale=True,  region=(850, 145, 975, 706))
                                    g = pyautogui.locateOnScreen("top_pipe.png",  confidence=0.8, grayscale=True, region=(850, 0, 1191, 685)) # region contains tuple showing where to look
                                    l = pyautogui.locateOnScreen("fpb.png",  confidence=0.2, grayscale=True,  region=(850, 145, 975, 706))
                                    b = pyautogui.locateOnScreen("bottom_pipe.png",  confidence=0.8, grayscale=True,  region=(850, 0, 1191, 200))
                                    print(g,l)
                                    try:
                                            print('printing k...')
                                            k = g[0] - l[0]
                                            print(k)
                                    except TypeError:
                                            k = 0
                                            print('k = 0')
                                    
                                    
                                    
                                    
                                    try: 
                                            m = l[2]-b[0]
                                            print(l[2])
                                            print(b[0])
                                            print(m)
                                            if m <= -1:
                                                    m = 0
                                                    print(m)
                                    except TypeError:
                                            m = 0
                                    p = pyautogui.locateCenterOnScreen("fpb.png",  confidence=0.2, grayscale=True,  region=(850, 145, 975, 706))
                                    output = net.activate(((p[1]), (k), (m)))
                                    print(output)
                                    q = [0.5]
                                    if output >= q:
                                            pyautogui.click(l)
                                    if output == [-1.0]:
                                            end_time = time.time()
                                            ge[x].fitness -= 1 # reduces fitness score for birds that hit a pipe
                                            birds.pop(x)
                                            nets.pop(x)
                                            ge.pop(x)
                                    
                                    
                                              

                                    if pyautogui.locateCenterOnScreen("fpb.png",  confidence=0.4, grayscale=True,  region=(850, 145, 975, 706)) == None:
                                    
                                            print('dead bird')
                                            end_time = time.time()
                                                    

                                            if pyautogui.locateOnScreen("pipedeath.png", confidence=0.5, grayscale=True) != None:
                                                                            
                                                    ge[x].fitness = (start_time-end_time)
                                                    ge[x].fitness -= 1 # reduces fitness score for birds that hit a pipe
                                                    birds.pop(x)
                                                    nets.pop(x)
                                                    ge.pop(x)
                                                            
                                            elif pyautogui.locateOnScreen('pipedeath.png', confidence=0.5, grayscale=True) == None:
                                                    ge[x].fitness = (start_time-end_time)
                                                    birds.pop(x)
                                                    nets.pop(x)
                                                    ge.pop(x)
                                            pyautogui.click(864, 516)
                                    try:

                                            if g[1] >= [665]:
                                    
                                                    print('dead bird')
                                                    end_time = time.time()
                                                    

                                                    if pyautogui.locateOnScreen("pipedeath.png", confidence=0.5, grayscale=True) != None:
                                                                            
                                                            ge[x].fitness = (start_time-end_time)
                                                            ge[x].fitness -= 1 # reduces fitness score for birds that hit a pipe
                                                            birds.pop(x)
                                                            nets.pop(x)
                                                            ge.pop(x)
                                                            
                                                    elif pyautogui.locateOnScreen('pipedeath.png', confidence=0.5, grayscale=True) == None:
                                                            ge[x].fitness = (start_time-end_time)
                                                            birds.pop(x)
                                                            nets.pop(x)
                                                            ge.pop(x)
                                    except TypeError:
                                            pass
                                            
                                            pyautogui.click(864, 516)

            except IndexError:
                    neat.generation +=1
            
                                    
                                            


                                            # gets location of birdif bird.y + pyautogui.locateOnscreen('fpb.png', confidence=0.5, grayscale=True) >= # y of dead bird
                            
                                                    
                                            
                            
                    

		# create an array that keeps the current total of pipes passed as an array if pyautogui.locateOnScreen # add one for each number seen for above 10 do one and 10 minus current number and 20 minus and thirty minus

def run(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)
    gen = 0
    if gen <=50:
            gen += 1
            winner = p.run(main)

if name == "main":
local_dir = os.path.dirname(file)
config_path = os.path.join(local_dir, 'neat-config.txt')
run(config_path)

issue running the program

that what it show in terminal:
multiple errors with the configparser

Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 788, in get
value = d[option]
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/collections/init.py", line 916, in getitem
return self.missing(key) # support subclasses that define missing
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/collections/init.py", line 908, in missing
raise KeyError(key)
KeyError: 'max_fitness_threshold'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/pablolopezrodriguez/Downloads/Comprimidos/NEAT-Flappy-Bird-master/flappy_bird.py", line 441, in
run(config_path)
File "/Users/pablolopezrodriguez/Downloads/Comprimidos/NEAT-Flappy-Bird-master/flappy_bird.py", line 417, in run
config_file)
File "/usr/local/lib/python3.7/site-packages/neat/config.py", line 103, in init
setattr(self, p.name, p.parse('NEAT', parameters))
File "/usr/local/lib/python3.7/site-packages/neat/config.py", line 23, in parse
return config_parser.getfloat(section, self.name)
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 823, in getfloat
fallback=fallback, **kwargs)
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 808, in _get_conv
**kwargs)
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 802, in _get
return conv(self.get(section, option, **kwargs))
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 791, in get
raise NoOptionError(option, section)
configparser.NoOptionError: No option 'max_fitness_threshold' in section: 'NEAT'

load pickle

Tim thanks, your lessons are great! Could you explain how to load pickle winner object in flappy B?

How to use this to play flappy bird game on webpage?

If I want to play the game on a webpage. Which means I would get the info about the game by opencv and more important I can just has one bird a time. So I have to set the pop in the config file to 1.

But I get some division zero error. So I check this link below:
CodeReclaimers/neat-python#214
And make the means related function return 0, when the length of values is 0.

But now seems the train is not working. Since I run for 50 generation, and at final the ai still do noting even failed for 49 times.

So how to fix this problem?

Nothing is shown in Pygame Window

Installed all the requirements and the game seems to be running but I don't see anything in the PyGame window. The terminal is showing the following:

python3 flappy_bird.py 
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html

 ****** Running generation 0 ****** 

Population's average fitness: 4.24400 stdev: 2.38639
Best fitness: 14.50000 - size: (1, 3) - species 1 - id 24
Average adjusted fitness: 0.152
Mean genetic distance 1.641, standard deviation 0.562
Population of 50 members in 2 species:
   ID   age  size  fitness  adj fit  stag
  ====  ===  ====  =======  =======  ====
     1    0    49     14.5    0.152     0
     2    0     1       --       --     0
Total extinctions: 0
Generation time: 9.507 sec

 ****** Running generation 1 ****** 

Iterations are very slow, CPU is at 100%, running on MacOS 10.15.1

  Model Name:	MacBook Pro
  Model Identifier:	MacBookPro15,1
  Processor Name:	6-Core Intel Core i9
  Processor Speed:	2.9 GHz
  Number of Processors:	1
  Total Number of Cores:	6
  L2 Cache (per Core):	256 KB
  L3 Cache:	12 MB
  Hyper-Threading Technology:	Enabled
  Memory:	32 GB

No other errors are shown.

pygame 1.9.6 Hello from the pygame community. https://www.pygame.org/contribute.html Traceback (most recent call last): File "c:/Users/ahmad/Desktop/Python/NEAT-Flappy-Bird-master/flappy_bird.py", line 441, in <module> run(config_path) File "c:/Users/ahmad/Desktop/Python/NEAT-Flappy-Bird-master/flappy_bird.py", line 415, in run config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, AttributeError: module 'neat' has no attribute 'Config'

i fixed some of the other errors i had but now i get this pygame 1.9.6 Hello from the pygame community. https://www.pygame.org/contribute.html Traceback (most recent call last): File "c:/Users/ahmad/Desktop/Python/NEAT-Flappy-Bird-master/flappy_bird.py", line 441, in <module> run(config_path) File "c:/Users/ahmad/Desktop/Python/NEAT-Flappy-Bird-master/flappy_bird.py", line 415, in run config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, AttributeError: module 'neat' has no attribute 'Config'

module neat has no attribute config

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Matplotlib is building the font cache; this may take a moment.
Traceback (most recent call last):
File "flappy_bird.py", line 441, in
run(config_path)
File "flappy_bird.py", line 415, in run
config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
AttributeError: module 'neat' has no attribute 'config'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.