Class: TicTacToe::Board

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

Direct Known Subclasses

BoardState

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size: 3) ⇒ Board

Returns a new instance of Board.



4
5
6
7
# File 'lib/tic_tac_toe/board.rb', line 4

def initialize(size: 3)
	@board_array = 0.upto(size-1).map { 0.upto(size-1).map { nil } }
	@num_moves = 0
end

Instance Attribute Details

#board_arrayObject (readonly)

Returns the value of attribute board_array.



3
4
5
# File 'lib/tic_tac_toe/board.rb', line 3

def board_array
  @board_array
end

#last_moveObject (readonly)

Returns the value of attribute last_move.



3
4
5
# File 'lib/tic_tac_toe/board.rb', line 3

def last_move
  @last_move
end

#num_movesObject (readonly)

Returns the value of attribute num_moves.



3
4
5
# File 'lib/tic_tac_toe/board.rb', line 3

def num_moves
  @num_moves
end

Class Method Details

.createObject



9
10
11
# File 'lib/tic_tac_toe/board.rb', line 9

def self.create
	Board.new(size: Input.number(message: "how many rows and columns would you like the board to have?"))
end

Instance Method Details

#copyObject



13
14
15
# File 'lib/tic_tac_toe/board.rb', line 13

def copy
	BoardState.new(self)
end

#draw?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/tic_tac_toe/board.rb', line 17

def draw?
	num_moves == @board_array.size ** 2
end

#last_symbolObject



21
22
23
# File 'lib/tic_tac_toe/board.rb', line 21

def last_symbol
	last_move ? get(last_move[:x], last_move[:y]) : nil
end

#place_symbol(symbol:, x:, y:) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/tic_tac_toe/board.rb', line 25

def place_symbol(symbol:, x:, y:)
	raise InvalidInputException.new("that position is out of range") unless [x,y].all? { |p|  (0..board_array.size - 1) === p }
	raise InvalidInputException.new("theres already a piece there") unless get(x,y).nil?
	@last_move = {x: x, y: y}
	@num_moves += 1
	board_array[y][x] = symbol
end

#win?Boolean

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/tic_tac_toe/board.rb', line 33

def win?
	return false if num_moves < 5
	horizontal? || vertical? || diagonal?
end