@anonymous/

BlankIdolizedNortherncardinals

Ruby

No description

fork
loading
Files
  • main.rb
main.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/ruby

def calculate_score(board)
  winning = [
    [0,1,2],[3,4,5],[6,7,8],  # Rows.
    [0,3,6],[1,4,7],[2,5,8],  # Columns.
    [0,4,8],[2,4,6]           # Diagonals.
  ]
  lines = winning.map{|line| line.map{|position| board[position]}}
  (lines.include?([:x,:x,:x]) ? 1 : 0) + 
    (lines.include?([:o,:o,:o]) ? -1 : 0)
end

def playout
  available = (0..8).to_a.shuffle  # Random permutation of [0..8]
  board = [nil]*9
  current_player, next_player = :x, :o
  score = 0
  while available.size > 0 and score == 0 do
    position = available.shift
    board[position] = current_player
    current_player, next_player = next_player, current_player
    score = calculate_score(board)
  end
  score_map = {:x => score, :o => -score, nil => 0}
  board.map{|x| score_map[x]}
end

def main
  board = [0.0]*9
  n = 200  # Number of playouts.
  n.times do
    result = playout
    result.each_with_index{|value, ii| board[ii] += value}
  end
 
  # Printing. 
  prn = board.map{|x| " %+0.4f" % (x.to_f/n)}
  print prn[0..2].join,"\n",prn[3..5].join,"\n",prn[6..8].join,"\n"
  
  print [board[4].to_f/n,                                      # Center.
      (board[0]+board[2]+board[6]+board[8]).to_f/n/4,          # Corner.
      (board[1]+board[3]+board[5]+board[7]).to_f/n/4].inspect  # Middle.
end

# if __FILE__ == $0
#   main
# end
main
ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]