Class: Board

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

Constant Summary collapse

Colors =
{black: 'x', white: 'o', empty: '_'}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ Board

Returns a new instance of Board.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/board.rb', line 5

def initialize(size)
  @board = []
  size -= 1

  0.upto(size) do |y|
    row = []
    0.upto(size) do |x| 
      row << Liberty.new(x, y) 
    end
    @board << row
  end
end

Instance Attribute Details

#boardObject

Returns the value of attribute board.



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

def board
  @board
end

Instance Method Details

#around(x, y = :y_not_given) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/board.rb', line 32

def around(x, y = :y_not_given)
  x, y = x.to_coord if x.kind_of?(Stone)
  stones = [] 
  stones << at(x-1, y) unless x == 0 
  stones << at(x+1, y) unless x == (@board.length - 1) 
  stones << at(x, y-1) unless y == 0 
  stones << at(x, y+1) unless y == (@board.length - 1)
  stones
end

#at(x, y) ⇒ Object



28
29
30
# File 'lib/board.rb', line 28

def at(x, y)
  @board[y][x]
end

#empty?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/board.rb', line 22

def empty?
  !@board.flatten.any? do |s| 
    !s.empty?
  end
end

#group_of(stone) ⇒ Object



56
57
58
# File 'lib/board.rb', line 56

def group_of(stone)
  stone.group(self)
end

#liberties(stone) ⇒ Object



50
51
52
53
54
# File 'lib/board.rb', line 50

def liberties(stone)
  group_of(stone).inject(0) do |libs, stn|
    libs + stn.liberties(self).count
  end
end

#place(stone) ⇒ Object



46
47
48
# File 'lib/board.rb', line 46

def place(stone)
  stone.place_on_board(self)
end

#remove(stone) ⇒ Object



42
43
44
# File 'lib/board.rb', line 42

def remove(stone)
  stone.remove_from_board(self)
end

#sizeObject



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

def size
  @board.length
end

#to_sObject



78
79
80
# File 'lib/board.rb', line 78

def to_s 
  to_str
end

#to_strObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/board.rb', line 60

def to_str
  out = ""
  if @board.length < 11
    out << "\s\s\s#{(0..@board.length - 1).to_a.join(' ')}\n" 
  else
    out                                << 
      "\s\s\s#{(0..10).to_a.join(' ')}" <<
      "#{(11..@board.length - 1).to_a.join('')}\n"
  end

  @board.each_with_index do |row, i|
    i = "\s#{i}" if i < 10
    out << "#{i}\s#{(row.collect {|stn| stn.to_s}).join(' ')}\n"
  end

  out
end