我创建了一个脚本,该脚本在pygame中使用纯Python玩一个简单的游戏,但当时只能运行一个基因组,这非常慢。有谁知道我如何在pygame中同时运行多个基因组?
脚本运行游戏,NEAT算法根据状态决定角色应向哪个方向移动。
我尝试使用
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)