如何使用neatpython在pygame中同时运行多个基因组?

2024-09-27 21:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个脚本,在pygame中用整洁的python玩一个简单的游戏,但是它一次只能运行一个基因组,速度非常慢。有人知道我怎么能在pygame中同时运行多个基因组吗?你知道吗

脚本运行游戏,每一帧的整洁算法决定的基础上,国家什么方向的字符应该移动。你知道吗

我试过用

pe = neat.ParallelEvaluator(4, run)
winner = p.run(pe.evaluate,10)

但它没有打开任何pygame窗口,并且停留在第0代。你知道吗

def eval_genomes(genomes, config):


    for genome_id, genome in genomes:

        net = neat.nn.recurrent.RecurrentNetwork.create(genome, config)

        current_max_fitness = 0
        fitness_current = 0

        state = [random.randint(0,100),random.randint(0,100),random.randint(0,100),0,0]
        for x in range(100):
            nnOutput = net.activate(state)
            state, rew = takeAction(nnOutput.index(max(nnOutput)),state,x,genome_id)
            fitness_current += rew

            if fitness_current > current_max_fitness:
                current_max_fitness = fitness_current                
            genome.fitness = fitness_current


def run(genomes,config):

    for genome_id, genome in genomes:

        net = neat.nn.recurrent.RecurrentNetwork.create(genome, config)
        current_max_fitness = 0
        fitness_current = 0

        pygame.init()

        screen = pygame.display.set_mode((800, 600))
        allFood = []

        player = Player(100,20)
        for x in range(10):
            x = Food(random.randint(0,800),random.randint(0,600))
            allFood.append(x)


        allSprites = [player]

        clock = pygame.time.Clock()
        running = True


        for x in range(200):
            pygame.event.get()



            screen.fill((255, 255, 255))

            for entity in allSprites+allFood:
                entity.draw(screen)

            allFood, reward = player.hitObject(allFood)

            start = player.closest(allFood)[2]

            state = [player.getPosition()[0],player.getPosition()[1], player.closest(allFood)[0], player.closest(allFood)[1], player.closest(allFood)[2]]
            nnOutput = net.activate(state)

            player.takeAction(nnOutput.index(max(nnOutput)))

            end = player.closest(allFood)[2]

            fitness_current += start-end + reward

            if fitness_current > current_max_fitness:
                current_max_fitness = fitness_current                
            genome.fitness = fitness_current

            pygame.display.update()

            clock.tick(60)

            if player.getPosition()[0] < 0 or player.getPosition()[1] < 0:
                break




config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                         neat.DefaultSpeciesSet, neat.DefaultStagnation,
                         'config-feedforward')


p = neat.Population(config)

p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)
p.add_reporter(neat.Checkpointer(100))

winner = p.run(run,1000)

Tags: runinconfigforgenomecurrentneatpygame

热门问题