class Snake2d::Snake
Attributes
direction[W]
Public Class Methods
new()
click to toggle source
# File lib/snake2d.rb, line 14 def initialize @positions = [[2, 0], [2, 1], [2, 2], [2 ,3]] @direction = 'down' @growing = false end
Public Instance Methods
can_change_direction_to?(new_direction)
click to toggle source
# File lib/snake2d.rb, line 39 def can_change_direction_to?(new_direction) case @direction when 'up' then new_direction != 'down' when 'down' then new_direction != 'up' when 'left' then new_direction != 'right' when 'right' then new_direction != 'left' end end
draw()
click to toggle source
# File lib/snake2d.rb, line 20 def draw @positions.each do |position| Square.new(x: position[0] * SQUARE_SIZE, y: position[1] * SQUARE_SIZE, size: SQUARE_SIZE - 1, color: 'white') end end
grow()
click to toggle source
# File lib/snake2d.rb, line 26 def grow @growing = true end
hit_itself?()
click to toggle source
# File lib/snake2d.rb, line 68 def hit_itself? @positions.uniq.length != @positions.length end
move()
click to toggle source
# File lib/snake2d.rb, line 30 def move if !@growing @positions.shift end @positions.push(next_position) @growing = false end
next_position()
click to toggle source
# File lib/snake2d.rb, line 56 def next_position if @direction == 'down' new_coords(head[0], head[1] + 1) elsif @direction == 'up' new_coords(head[0], head[1] - 1) elsif @direction == 'left' new_coords(head[0] - 1, head[1]) elsif @direction == 'right' new_coords(head[0] + 1, head[1]) end end
x()
click to toggle source
# File lib/snake2d.rb, line 48 def x head[0] end
y()
click to toggle source
# File lib/snake2d.rb, line 52 def y head[1] end
Private Instance Methods
head()
click to toggle source
# File lib/snake2d.rb, line 78 def head @positions.last end
new_coords(x, y)
click to toggle source
# File lib/snake2d.rb, line 74 def new_coords(x, y) [x % GRID_WIDTH, y % GRID_HEIGHT] end