class Tictactoe::State

Attributes

board[R]
marks[R]

Public Class Methods

new(board, marks=[nil] * board.locations.length) click to toggle source
# File lib/tictactoe/state.rb, line 5
def initialize(board, marks=[nil] * board.locations.length)
  @board = board
  @marks = marks
end

Public Instance Methods

available_moves() click to toggle source
# File lib/tictactoe/state.rb, line 10
def available_moves
  @available ||= board.locations.select{|location| marks[location].nil?}
end
is_finished?() click to toggle source
# File lib/tictactoe/state.rb, line 24
def is_finished?
  is_full? || has_winner?
end
make_move(location, mark) click to toggle source
# File lib/tictactoe/state.rb, line 18
def make_move(location, mark)
  new_marks = marks.clone
  new_marks[location] = mark
  self.class.new(board, new_marks)
end
played_moves() click to toggle source
# File lib/tictactoe/state.rb, line 14
def played_moves
  @played_moves ||= board.locations.length - available_moves.length
end
winner() click to toggle source
# File lib/tictactoe/state.rb, line 28
def winner
  @winner ||= find_winner
end

Private Instance Methods

find_winner() click to toggle source
# File lib/tictactoe/state.rb, line 41
def find_winner
  board.lines.each do |line|
    line_marks = line.map{|location| marks[location]}
    return line_marks.first if line_marks.all?{|mark| mark && mark == line_marks.first}
  end

  nil
end
has_winner?() click to toggle source
# File lib/tictactoe/state.rb, line 37
def has_winner?
  winner != nil
end
is_full?() click to toggle source
# File lib/tictactoe/state.rb, line 33
def is_full?
  available_moves.empty?
end