class TicTacToe::Computer
Public Instance Methods
next_move()
click to toggle source
# File lib/tic_tac_toe_mchliakh/players/computer.rb, line 3 def next_move line = any_winning_line || any_losing_line if line line.squares.empty.sample else fork_squares.sample || fork_safe_square || @board.squares.empty.max_by(&:line_count) end end
Private Instance Methods
any_losing_line()
click to toggle source
# File lib/tic_tac_toe_mchliakh/players/computer.rb, line 19 def any_losing_line @board.lines.can_lose(@number).sample end
any_winning_line()
click to toggle source
# File lib/tic_tac_toe_mchliakh/players/computer.rb, line 15 def any_winning_line @board.lines.can_win(@number).sample end
fork_safe_square()
click to toggle source
# File lib/tic_tac_toe_mchliakh/players/computer.rb, line 27 def fork_safe_square _opponent_forks = opponent_forks if opponent_forks.size > 1 @board.lines.could_win(@number).each do |l| non_fork = (l.squares.empty - (l.squares & _opponent_forks)).first return (l.squares.empty - [non_fork]).first end else opponent_forks.first end end
fork_squares()
click to toggle source
# File lib/tic_tac_toe_mchliakh/players/computer.rb, line 23 def fork_squares @board.lines.squares_that_can_fork(@number).empty end
opponent_forks()
click to toggle source
# File lib/tic_tac_toe_mchliakh/players/computer.rb, line 40 def opponent_forks @board.lines.squares_that_can_be_forked(@number).empty end