Initial commit
[trapthecap.git] / run-ga.rb
1 #!/usr/bin/ruby -w
2
3 require 'src/play'
4 require 'src/selection'
5 # require 'systemu'
6
7 pop = Population.new(5, 20)
8 generation_count = 1
9 max_generations = 3
10
11 if File.file? 'player.log'
12 File.delete 'player.log'
13 end
14
15 puts "Generation number #{generation_count}"
16 pop.individuals.sort {|x, y| x.genome <=> y.genome}.each {|i| puts "#{i.genome}"}
17
18 while generation_count <= max_generations
19 start = Time.now
20 puts "Started at #{start}"
21
22 new_population = []
23 threads = []
24 1.upto(pop.individuals.length) do |i|
25 threads << Thread.new do
26 puts "Starting thread #{i}"
27 sleep 2
28 player_count = rand(5) + 2
29 pool_size = pop.individuals.length
30 players = []
31 1.upto(player_count) { players << pop.individuals[rand(pool_size)] }
32 IO.popen('ruby play-one-game.rb', 'r+') do |pipe|
33 players.each {|p| pipe << "#{p.genome}\n" ; puts "Game #{i}: putting player #{p.genome}"}
34 # players.each {|p| pipe << "#{p.genome}\n"}
35 pipe.close_write
36 new_population << Genome.new(pipe.readline.chomp.split(//).collect {|x| x.to_i})
37 puts "Got result #{new_population[-1].genome}"
38 end
39 # game_input = (players.collect {|p| p.genome.to_s}).join("\n")
40 # game_result = ''
41 # puts "Calling game #{i} with input #{game_input}"
42 # status, game_result, stderr = systemu 'ruby play-one-game.rb', 'stdin' => game_input
43 # puts "Game #{i} returned #{game_result}"
44 # new_population << Genome.new(game_result.chomp.split(//).collect {|x| x.to_i})
45 end
46 threads.each {|t| t.join}
47 end
48
49 pop.individuals = new_population
50
51 finish = Time.now
52 puts "Took #{finish - start} seconds"
53 pop1 = pop.crossover(0.7)
54 pop = pop1.mutation(0.05)
55 generation_count += 1
56 puts "Generation number #{generation_count}"
57 pop.individuals.sort {|x, y| x.genome <=> y.genome}.each {|i| puts "#{i.genome}"}
58 $stdout.flush
59 end