Class: RbSnake::Models::Snake

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

Defined Under Namespace

Classes: RenderedBodyElem

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body:) ⇒ Snake

Returns a new instance of Snake.



13
14
15
# File 'lib/rb_snake/models/snake.rb', line 13

def initialize(body:)
  @body = body
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



11
12
13
# File 'lib/rb_snake/models/snake.rb', line 11

def body
  @body
end

Instance Method Details

#eat(food) ⇒ Object



47
48
49
# File 'lib/rb_snake/models/snake.rb', line 47

def eat(food)
  body.unshift(food.location)
end

#move_to(position) ⇒ Object



51
52
53
54
# File 'lib/rb_snake/models/snake.rb', line 51

def move_to(position)
  body.unshift(position)
  body.pop
end

#next_position(direction, grid) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rb_snake/models/snake.rb', line 24

def next_position(direction, grid)
  new_row = head.row
  new_col = head.col

  case direction
  when Direction::UP
    new_row -= 1
  when Direction::RIGHT
    new_col += 1
  when Direction::DOWN
    new_row += 1
  when Direction::LEFT
    new_col -= 1
  else
    raise StandardError, "direction #{direction} not recognized"
  end

  new_row = truncate_row(new_row, grid)
  new_col = truncate_col(new_col, grid)

  Coordinate.new(row: new_row, col: new_col)
end

#render(window, &block) ⇒ Object



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

def render(window, &block)
  return build_rendered_body(&block) if rendered_body.nil?

  update_last_rendered_position(window)
  update_first_rendered_position(&block)
end