Exemple #1
0
class SnakeEnv(Env):
    def __init__(self):
        self.action_space = Discrete(3) # 0 = turn left, 1 = do nothing, 2 = turn right
        self.state = [0, 0, 1, 0]
        self.game = Game()
        self.reward = 0
        self.done = False

    def step(self, action):
        
        offset = (action - 1)
        translated_action = offset + self.game.snake.direction
        if translated_action < 0:
            translated_action = 3
        if translated_action > 3:
            translated_action = 0

        self.reward, self.done = self.game.run(1, translated_action)

        diff = (self.game.food.position[0] - self.game.snake.snake[0][0], self.game.food.position[1] - self.game.snake.snake[0][1])
        
        self.state[0] = int(diff[0] < 0)
        self.state[2] = int(diff[0] > 1)

        self.state[1] = int(diff[1] < 0)
        self.state[3] = int(diff[1] > 0)

        return self.state, self.reward, self.done, {}

    def render(self):
        self.game.render()

    def reset(self):
        self.game.reset()
Exemple #2
0
            # average fitness of a population
            lstr(sum(n.fitness for n in networks) / len(networks)),
        ])
        if generation >= max_generation:
            break
        # select for the next generation
        networks = select_networks(networks)
        # crossover for the next generation
        networks = crossover_networks(networks)

    # save data for the performance graph
    with open("snake_data.csv", 'w') as file:
        writer = csv.writer(file, delimiter=';')  # delimit with semicolons
        writer.writerows(snake_data)
    # restore the best network
    best_net = Network(net_args)
    best_net.fitness = best_net_data[0]
    best_net.import_data(best_net_data[1])
    # run it
    print(f"\nRunning best network: {best_net.fitness} fitness")
    # attach the controller
    game.external = partial(controller, best_net)
    game.fps = 6
    while not game.window.has_exit:
        # reset the game
        game.reset()
        # run the game
        game.run()
        print(f"Score: {game.score}")
        sleep(1)
Exemple #3
0
from snake import Game

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    snake = Game()
    snake.run()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Exemple #4
0
from snake import Game


if __name__ == "__main__":
    a = Game('snake', 1280, 640, 10)
    a.run()