Class: RubyGo::Board

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ Board

Returns a new instance of Board.



5
6
7
8
# File 'lib/ruby-go/board.rb', line 5

def initialize(size)
  @rows = Array.new(size) { Array.new(size) { Liberty.new } }
  @size = size
end

Instance Attribute Details

#rowsObject (readonly)

Returns the value of attribute rows.



3
4
5
# File 'lib/ruby-go/board.rb', line 3

def rows
  @rows
end

#sizeObject (readonly)

Returns the value of attribute size.



3
4
5
# File 'lib/ruby-go/board.rb', line 3

def size
  @size
end

Instance Method Details

#around(x, y) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/ruby-go/board.rb', line 18

def around(x, y)
  intersections = []

  intersections << at(x-1, y) unless x == 0
  intersections << at(x+1, y) unless x == (size - 1)
  intersections << at(x, y-1) unless y == 0
  intersections << at(x, y+1) unless y == (size - 1)
  intersections
end

#at(x, y) ⇒ Object



14
15
16
# File 'lib/ruby-go/board.rb', line 14

def at(x, y)
  rows[y][x]
end

#empty?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/ruby-go/board.rb', line 10

def empty?
  rows.flatten.all?(&:empty?)
end

#group_of(stone, stones = []) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ruby-go/board.rb', line 52

def group_of(stone, stones = [])
  return stones if stones.include?(stone)

  stones << stone

  around(*stone.to_coord).each do |intersection|
    next if intersection.empty?

    group_of(intersection, stones) if intersection.color == stone.color
  end

  stones
end

#liberties(stone) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/ruby-go/board.rb', line 42

def liberties(stone)
  libs = []

  group_of(stone).each do |stn|
    libs += around(*stn.to_coord).select(&:empty?)
  end

  libs.uniq.length
end

#place(stone) ⇒ Object



36
37
38
39
40
# File 'lib/ruby-go/board.rb', line 36

def place(stone)
  x, y = stone.to_coord

  rows[y][x] = stone
end

#remove(stone) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/ruby-go/board.rb', line 28

def remove(stone)
  return if stone.empty?

  x, y = stone.to_coord

  rows[y][x] = Liberty.new
end