Class: Board
- Inherits:
-
Object
show all
- Defined in:
- lib/command_four/board.rb
Defined Under Namespace
Classes: ConnectNChecker, GameState, PieceDropError
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(width = 7, height = 6, connect_n = 4) ⇒ Board
Returns a new instance of Board.
4
5
6
7
8
9
10
11
12
|
# File 'lib/command_four/board.rb', line 4
def initialize(width = 7, height = 6, connect_n = 4)
@width = width
@height = height
@connect_n = connect_n
@state = GameState.new(false, [])
@board = Array.new(@width) {Array.new(@height, :empty)}
@completed_moves = 0
@max_moves = width * height
end
|
Instance Attribute Details
#height ⇒ Object
Returns the value of attribute height.
2
3
4
|
# File 'lib/command_four/board.rb', line 2
def height
@height
end
|
#width ⇒ Object
Returns the value of attribute width.
2
3
4
|
# File 'lib/command_four/board.rb', line 2
def width
@width
end
|
Class Method Details
.from_a(arr, connect_n = 4) ⇒ Object
50
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/command_four/board.rb', line 50
def self.from_a(arr, connect_n = 4)
board = Board.new(arr.length, arr[0].length, connect_n)
for i in 0...arr[0].length
for j in 0...arr.length
if arr[j][i] != :empty
board.drop_piece(j, arr[j][i])
end
end
end
board
end
|
Instance Method Details
#drop_piece(column, color) ⇒ Object
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
# File 'lib/command_four/board.rb', line 14
def drop_piece(column, color)
if game_over?()
raise PieceDropError.new("Game is already over")
elsif invalid_index?(column)
raise PieceDropError.new("Invalid column index: #{column}")
elsif full?(column)
raise PieceDropError.new("Column #{column} is already full")
else
first_empty_cell_index = @board[column].index {|cell| cell == :empty}
@board[column][first_empty_cell_index] = color
@completed_moves += 1
@state = ConnectNChecker.new(@board, @connect_n, column, first_empty_cell_index).check
if @completed_moves >= @max_moves && !game_over?()
@state = GameState.new(true, [])
end
end
end
|
#game_over? ⇒ Boolean
32
33
34
|
# File 'lib/command_four/board.rb', line 32
def game_over?
@state.game_over?
end
|
#to_a ⇒ Object
62
63
64
|
# File 'lib/command_four/board.rb', line 62
def to_a
@board
end
|
#winning_cells ⇒ Object
36
37
38
|
# File 'lib/command_four/board.rb', line 36
def winning_cells
@state.winning_cells
end
|
#winning_color ⇒ Object
40
41
42
43
44
45
46
47
48
|
# File 'lib/command_four/board.rb', line 40
def winning_color
if @state.winning_cells.length > 0
col_idx = @state.winning_cells[0][0]
row_idx = @state.winning_cells[0][1]
@board[col_idx][row_idx]
else
nil
end
end
|