Class: XO::Grid

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

Constant Summary collapse

ROWS =
3
COLS =
3

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGrid

Returns a new instance of Grid.



12
13
14
# File 'lib/xo/grid.rb', line 12

def initialize
  @grid = Array.new(ROWS * COLS, :e)
end

Class Method Details

.contains?(r, c) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/xo/grid.rb', line 8

def self.contains?(r, c)
  r.between?(1, ROWS) && c.between?(1, COLS)
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



66
67
68
69
# File 'lib/xo/grid.rb', line 66

def ==(other)
  return false unless other.instance_of?(self.class)
  grid == other.instance_variable_get(:@grid)
end

#[](r, c) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/xo/grid.rb', line 28

def [](r, c)
  if self.class.contains?(r, c)
    grid[idx(r, c)]
  else
    raise IndexError, "position (#{r}, #{c}) is off the grid"
  end
end

#[]=(r, c, val) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/xo/grid.rb', line 20

def []=(r, c, val)
  if self.class.contains?(r, c)
    grid[idx(r, c)] = val
  else
    raise IndexError, "position (#{r}, #{c}) is off the grid"
  end
end

#clearObject



48
49
50
# File 'lib/xo/grid.rb', line 48

def clear
  grid.fill(:e)
end

#eachObject



52
53
54
55
56
57
58
59
60
# File 'lib/xo/grid.rb', line 52

def each
  (1..ROWS).each do |r|
    (1..COLS).each do |c|
      yield(r, c, self[r, c])
    end
  end

  self
end

#each_freeObject



62
63
64
# File 'lib/xo/grid.rb', line 62

def each_free
  self.each { |r, c, _| yield(r, c) if free?(r, c) }
end

#empty?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/xo/grid.rb', line 36

def empty?
  grid.all? { |val| !XO.is_token?(val) }
end

#free?(r, c) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/xo/grid.rb', line 44

def free?(r, c)
  !XO.is_token?(self[r, c])
end

#full?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/xo/grid.rb', line 40

def full?
  grid.all? { |val| XO.is_token?(val) }
end

#hashObject



72
73
74
# File 'lib/xo/grid.rb', line 72

def hash
  grid.hash
end

#initialize_copy(orig) ⇒ Object



16
17
18
# File 'lib/xo/grid.rb', line 16

def initialize_copy(orig)
  @grid = orig.instance_variable_get(:@grid).dup
end