Class: KnightsTour::Knight

Inherits:
Object
  • Object
show all
Defined in:
lib/knights_tour.rb

Constant Summary collapse

[ [-2,  1], [-1,  2], [ 1,  2], [ 2,  1],
[ 2, -1], [ 1, -2], [-1, -2], [-2, -1] ]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(board_size, start_at) ⇒ Knight

Returns a new instance of Knight.



76
77
78
79
80
# File 'lib/knights_tour.rb', line 76

def initialize(board_size, start_at)
  @board = Array.new(board_size[0]) { Array.new(board_size[1], 0) }
  @steps_taken = 0
  traverse_to(start_at)
end

Instance Attribute Details

#boardObject (readonly)

Returns the value of attribute board.



74
75
76
# File 'lib/knights_tour.rb', line 74

def board
  @board
end

#current_positionObject (readonly)

Returns the value of attribute current_position.



74
75
76
# File 'lib/knights_tour.rb', line 74

def current_position
  @current_position
end

#steps_takenObject (readonly)

Returns the value of attribute steps_taken.



74
75
76
# File 'lib/knights_tour.rb', line 74

def steps_taken
  @steps_taken
end

Instance Method Details

#find_next_positionsObject



99
100
101
# File 'lib/knights_tour.rb', line 99

def find_next_positions
  sort_by_warnsdorffs_heuristics(find_next_positions_at(@current_position))
end

#initialize_copy(other) ⇒ Object



82
83
84
85
# File 'lib/knights_tour.rb', line 82

def initialize_copy(other)
  @board = Marshal.load(Marshal.dump(other.board))
  @steps_taken = other.steps_taken
end

#traverse_to(new_position) ⇒ Object



92
93
94
95
96
97
# File 'lib/knights_tour.rb', line 92

def traverse_to(new_position)
  @steps_taken += 1
  @current_position = new_position
  @board[@current_position[0]][@current_position[1]] = @steps_taken
  self
end

#traversed?Boolean

Returns:

  • (Boolean)


87
88
89
90
# File 'lib/knights_tour.rb', line 87

def traversed?
  last_step = @board.size * @board[0].size
  @steps_taken == last_step
end