genetic

genetic algorithm framework
git clone [email protected]:dracuxan/genetic.git
Log | Files | Refs | README

tetris.exs (1169B)


      1 defmodule TetrisInterface do
      2   use Agent
      3 
      4   def start_link(path_to_tetris_rom) do
      5     int = Alex.new()
      6 
      7     game =
      8       int
      9       |> Alex.set_option(:display_screen, true)
     10       |> Alex.set_option(:sound, true)
     11       |> Alex.set_option(:random_seed, 123)
     12       |> Alex.load(path_to_tetris_rom)
     13 
     14     Agent.start_link(fn -> game end, name: __MODULE__)
     15   end
     16 end
     17 
     18 defmodule Tetris do
     19   alias Types.Chromosome
     20   @behaviour Problem
     21 
     22   @impl true
     23   def genotype do
     24     game = Agent.get(TetrisInterface, & &1)
     25     genes = Enum.map(1..1000, fn _ -> Enum.random(game.legal_actions) end)
     26     %Chromosome{genes: genes, size: 1000}
     27   end
     28 
     29   @impl true
     30   def fitness_function(chromosome) do
     31     game = Agent.get(TetrisInterface, & &1)
     32     actions = chromosome.genes
     33 
     34     game =
     35       actions
     36       |> Enum.reduce(game, fn act, game -> Alex.step(game, act) end)
     37 
     38     reward = game.reward
     39     Alex.reset(game)
     40     reward
     41   end
     42 
     43   @impl true
     44   def terminate?(_population, generation), do: generation == 5
     45 end
     46 
     47 TetrisInterface.start_link("/home/dracuxan/Projects/elixir/src/genetic/games/tetris.bin")
     48 soln = Genetic.run(Tetris, population_size: 10)
     49 IO.puts("\nbest: #{inspect(soln)}")