def play_best_game(best_individual): """ Play the game with the best individual obtained from the genetic algorithm. best_individual: Best individual after the GA has finished. return game score (int) """ game = DinoGame(fps=60) state_matrix = np.zeros((3, N_ATTRIBUTES)) while not game.game_over: state_matrix = update_state_matrix(game, state_matrix) action = np.argmax(best_individual @ state_matrix.T) game.step(action) return game.get_score()
for ger in range(num_geracoes): # Crie uma lista `fitness` com o fitness de cada indivíduo da população # (usando a função calcular_fitness e um `for` loop). fitness = [] for ind in populacao: fitness.append(calcular_fitness(jogo, ind)) # Atualize a população usando a função próxima_geração. populacao = proxima_geracao(populacao, fitness) print('{:3} |'.format(ger), ' '.join('{:4d}'.format(s) for s in sorted(fitness, reverse=True))) # Opcional: parar se o fitness estiver acima de algum valor (p.ex. 300) # if max(fitness) > 300: # break # Calcule a lista de fitness para a última geração fitness = [] for ind in populacao: fitness.append(calcular_fitness(jogo, ind)) # Mostre o melhor indivíduo jogo.fps = 100 ordenados = ordenar_lista(populacao, fitness) melhor = ordenados[0] print('Melhor individuo:', melhor) fit = calcular_fitness(jogo, melhor) print('Fitness: {:4.1f}'.format(jogo.get_score()))