Class: RbSnake::Models::Food

Inherits:
Object
  • Object
show all
Defined in:
lib/rb_snake/models/food.rb

Defined Under Namespace

Classes: RenderedElement

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(row:, col:) ⇒ Food

Returns a new instance of Food.



12
13
14
# File 'lib/rb_snake/models/food.rb', line 12

def initialize(row:, col:)
  @location = Coordinate.new(row: row, col: col)
end

Instance Attribute Details

#locationObject (readonly)

Returns the value of attribute location.



8
9
10
# File 'lib/rb_snake/models/food.rb', line 8

def location
  @location
end

Instance Method Details

#regenerate(snake, grid) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rb_snake/models/food.rb', line 25

def regenerate(snake, grid)
  loop do
    new_row = rand(0...grid.rows)
    new_col = rand(0...grid.cols)

    if snake.body.none? { |position| position.row == new_row && position.col == new_col }
      @location = Coordinate.new(row: new_row, col: new_col)
      break
    end
  end
end

#render(window) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/rb_snake/models/food.rb', line 16

def render(window)
  return if rendered_element&.location == location

  window.remove(rendered_element.elem) if rendered_element

  elem = yield(location.row, location.col)
  @rendered_element = RenderedElement.new(elem, location)
end