fork download
  1. require 'matrix'
  2.  
  3. class Board
  4. def initialize(pc_turn)
  5. @board_matrix = Matrix.build(3,3){0}
  6. @identity = Matrix.identity(3)
  7. @permutation_matrix = Matrix.rows(@identity.to_a.reverse)
  8. @row_vec = Matrix.row_vector([1,1,1])
  9. @markers = { 1 => "X", 0 => " ", -1 => "O" }
  10. @pc_turn = pc_turn
  11. end
  12. def move(x,y)
  13. return false if @board_matrix[x,y] != 0
  14. tmp = @board_matrix.to_a
  15. tmp[x][y] = pc_turn ? -1 : 1
  16. @board_matrix = Matrix[tmp]
  17. @pc_turn != @pc_turn
  18. true
  19. end
  20. def win
  21. # fancy matrix stuff 1 player wins, 0 draw, -1 pc wins
  22. [@identity.column_vectors.map{ |vec| (@row_vec * @board_matrix * vec)[0]}.max_by{ |n| n.abs },
  23. @identity.column_vectors.map{ |vec| (@row_vec * @board_matrix.t * vec)[0]}.max_by{ |n| n.abs },
  24. @board_matrix.tr, (@permutation_matrix * @board_matrix).tr].max_by{ |n| n.abs} / 3
  25. end
  26. def to_str()
  27. "+---+---+---+\n"+
  28. @board_matrix.to_a.map do |row|
  29. "| %s | %s | %s |\n+---+---+---+\n" % row.map{ |val| @markers[val]}
  30. end.join
  31. end
  32. end
  33.  
Success #stdin #stdout 0.02s 6864KB
stdin
Standard input is empty
stdout
Standard output is empty