Flappy Bird в пигме "Птицы" не определена - PullRequest
0 голосов
/ 20 апреля 2020

После решения предыдущей проблемы с базой уровня я столкнулся с другой проблемой сразу после ее решения. Кажется, что та же самая проблема, ошибка все еще

NameError: name 'birds' is not defined

, но на этот раз птица фактически определена как список. В предыдущем вопросе я добавил слишком много ненужного кода в этот вопрос, и я извиняюсь за это, поэтому я старался изо всех сил поместить только необходимый код, чтобы найти проблему.

def draw_window(win, bird, pipes, base, score):
    win.blit(BG_IMG, (0, 0))

    for pipe in pipes:
        pipe.draw(win)

    text = STAT_FONT.render('Score: ' + str(score), 1, (255, 255, 255))
    win.blit(text, (WIN_WIDTH - 10 - text.get_width(), 10))

    base.draw(win)  

    for bird in birds:   # Here is the line where the error occurs
        bird.draw(win)

    pygame.display.update()

def main(genomes, config):
    nets = []
    ge = []
    birds = []      # Here it appears defined as a list
    base = Base(730)

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(Bird(230, 350))
        g.fitness = 0
        ge.append(g) 

    pipes = [Pipe(600)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    clock = pygame.time.Clock()

    score = 0

    run = True
    while run:
        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
        else:
            run = False
            break

        for x, bird in enumerate(birds):
            bird.move()
            ge[x].fitness += 0.1

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

            if output[0] > 0.5:
                bird.jump()

        #bird.move()
        add_pipe = False
        rem = []
        for pipe in pipes:
            for x, bird in enumerate(birds):
                if pipe.collide(bird):
                    ge[x].fitness -= 1
                    birds.pop(x)
                    nets.pop(x)
                    ge.pop(x)

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

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)

            pipe.move()

        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(Pipe(600))

        for r in rem:
            pipes.remove(r)

        for x, bird in enumerate(birds):
            if bird.y + bird.img.get_height() >= 730 or bird.y < 0:
                birds.pop(x)
                nets.pop(x)
                ge.pop(x)

        base.move()
        draw_window(win, birds, pipes, base, score)

1 Ответ

1 голос
/ 20 апреля 2020

проблема вызвана тем, что вы пытаетесь перебрать список birds в функции draw_window. Но переменная birds не определена в области действия draw_window:

for bird in birds:   # Here is the line where the error occurs
   bird.draw(win)

Имя аргумента в функции draw_window должно быть birds, а не bird:

def draw_window(win, bird, pipes, base, score):

def draw_window(win, birds, pipes, base, score):

Обратите внимание, что при вызове функции фактическим параметром является список birds:

draw_window(win, birds, pipes, base, score)
...