class Snake::Model::Snake

Constants

LEFT_TURN_MAP
RIGHT_TURN_MAP
SCORE_EAT_APPLE

Attributes

collided[RW]
collided?[RW]
game[R]
vertebrae[RW]

vertebrae and joins are ordered from tail to head

Public Class Methods

new(game) click to toggle source
# File examples/snake/model/snake.rb, line 22
def initialize(game)
  @game = game
end

Public Instance Methods

generate(initial_row: nil, initial_column: nil, initial_orientation: nil) click to toggle source

generates a new snake location and orientation from scratch or via dependency injection of what head_cell and orientation are (for testing purposes)

# File examples/snake/model/snake.rb, line 27
def generate(initial_row: nil, initial_column: nil, initial_orientation: nil)
  self.collided = false
  initial_vertebra = Vertebra.new(snake: self, row: initial_row, column: initial_column, orientation: initial_orientation)
  self.vertebrae = [initial_vertebra]
end
grow() click to toggle source
# File examples/snake/model/snake.rb, line 84
def grow
  @game.score += SCORE_EAT_APPLE
  @vertebrae.prepend(@old_tail)
end
head() click to toggle source
# File examples/snake/model/snake.rb, line 37
def head
  @vertebrae.last
end
inspect() click to toggle source

inspect is overridden to prevent printing very long stack traces

# File examples/snake/model/snake.rb, line 90
def inspect
  "#{super[0, 150]}... >"
end
length() click to toggle source
# File examples/snake/model/snake.rb, line 33
def length
  @vertebrae.length
end
move() click to toggle source
# File examples/snake/model/snake.rb, line 50
def move
  @old_tail = tail.dup
  @new_head = head.dup
  case @new_head.orientation
  when :east
    @new_head.column = (@new_head.column + 1) % @game.width
  when :west
    @new_head.column = (@new_head.column - 1) % @game.width
  when :south
    @new_head.row = (@new_head.row + 1) % @game.height
  when :north
    @new_head.row = (@new_head.row - 1) % @game.height
  end
  if @vertebrae.map {|v| [v.row, v.column]}.include?([@new_head.row, @new_head.column])
    self.collided = true
    @game.over = true
  else
    @vertebrae.append(@new_head)
    @vertebrae.delete(tail)
    if head.row == @game.apple.row && head.column == @game.apple.column
      grow
      @game.apple.generate
    end
  end
end
remove() click to toggle source
# File examples/snake/model/snake.rb, line 45
def remove
  self.vertebrae.clear
  self.joins.clear
end
tail() click to toggle source
# File examples/snake/model/snake.rb, line 41
def tail
  @vertebrae.first
end
turn_left() click to toggle source
# File examples/snake/model/snake.rb, line 80
def turn_left
  head.orientation = LEFT_TURN_MAP[head.orientation]
end
turn_right() click to toggle source
# File examples/snake/model/snake.rb, line 76
def turn_right
  head.orientation = RIGHT_TURN_MAP[head.orientation]
end