def gameInit(agentDQN, showGui=False): snakeML.newGameML() snakeML.startGameML(showGui=showGui) state_1 = np.reshape(snakeML.getInputLayer(), (1, SIZE_INPUT_LAYER)) action = 1 foodAte, gameEnded = snakeML.nextStep(1) state_2 = np.reshape(snakeML.getInputLayer(), (1, SIZE_INPUT_LAYER)) reward = agentDQN.setReward(foodAte, gameEnded) agentDQN.remember(state_1, action, reward, state_2, gameEnded) agentDQN.replay_memory()
def showSnake(modelName): model = tf.keras.models.load_model(modelName) snakeML.newGameML() snakeML.startGameML() game_ended = False num_steps = 0 while not game_ended: input_layer = snakeML.getInputLayer() output = model.predict(np.matrix(input_layer)) # predict output output = np.argmax(output) len, game_ended = snakeML.nextStep(output) num_steps += 1 snakeML.exit()
total_weights += hidden_layers_units[0] * output_layer_units # Genetic loop population = GeneticAlgo.generatePopulation( n_population, total_weights) # Change to total number of weights #population = getPopulationFromCsv() for i in range(1, num_of_gens): print(f"Generation {i}:") fitness = np.empty(n_population) len = np.empty(n_population) for j in range(0, n_population): weights = reshapeWeights(population[j], input_layer_units, hidden_layers_units, output_layer_units) model.set_weights(weights) snakeML.newGameML() snakeML.startGameML(showGui=False) game_ended = False num_steps = 0 while not game_ended and (num_steps < max_steps): input_layer = snakeML.getInputLayer() output = model.predict(np.matrix(input_layer)) # predict output output = np.argmax(output) len[j], game_ended = snakeML.nextStep(output) num_steps += 1 fitness[j] = calcFitness(len[j], num_steps) snakeML.exit() updateCanvas(txtbox_training_id, i, j, fitness[j], len[j]) best_person = np.argmax(fitness) print( f"Generation {i}, Top fitness = {fitness[best_person]}, Length = {len[j]}"
GAMES_PER_EPISODE = 10 # Change this boolean to true to display gui SHOW_GUI = False files = os.listdir(PATH) score_plot = [] episode_plot = [] for i in range(len(files)): weightsToUse = f"{PATH}{files[i]}" #model.load_model(weightsToUse) model = keras.models.load_model(weightsToUse) totalScore = 0 for j in range(GAMES_PER_EPISODE): score = 0 counter = 0 snakeML.newGameML() snakeML.startGameML(showGui=SHOW_GUI) while not snakeML.gameEnded and counter < 200: state = np.reshape(snakeML.getInputLayer(), (1, SIZE_INPUT_LAYER)) output = model.predict(state) action = np.argmax(output) snakeML.nextStep(action) if (score == snakeML.snake.length - 1): counter += 1 else: score = snakeML.snake.length - 1 counter = 0 totalScore += score snakeML.exit() score_plot.append(totalScore / GAMES_PER_EPISODE) episode_plot.append(i * 10) print(f"File={files[i]} Score={totalScore / GAMES_PER_EPISODE}")