Class: Snake2d::Snake
- Inherits:
-
Object
- Object
- Snake2d::Snake
- Defined in:
- lib/snake2d.rb
Instance Attribute Summary collapse
-
#direction ⇒ Object
writeonly
Sets the attribute direction.
Instance Method Summary collapse
- #can_change_direction_to?(new_direction) ⇒ Boolean
- #draw ⇒ Object
- #grow ⇒ Object
- #hit_itself? ⇒ Boolean
-
#initialize ⇒ Snake
constructor
A new instance of Snake.
- #move ⇒ Object
- #next_position ⇒ Object
- #x ⇒ Object
- #y ⇒ Object
Constructor Details
#initialize ⇒ Snake
Returns a new instance of Snake.
14 15 16 17 18 |
# File 'lib/snake2d.rb', line 14 def initialize @positions = [[2, 0], [2, 1], [2, 2], [2 ,3]] @direction = 'down' @growing = false end |
Instance Attribute Details
#direction=(value) ⇒ Object (writeonly)
Sets the attribute direction
12 13 14 |
# File 'lib/snake2d.rb', line 12 def direction=(value) @direction = value end |
Instance Method Details
#can_change_direction_to?(new_direction) ⇒ Boolean
39 40 41 42 43 44 45 46 |
# 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 ⇒ Object
20 21 22 23 24 |
# 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 ⇒ Object
26 27 28 |
# File 'lib/snake2d.rb', line 26 def grow @growing = true end |
#hit_itself? ⇒ Boolean
68 69 70 |
# File 'lib/snake2d.rb', line 68 def hit_itself? @positions.uniq.length != @positions.length end |
#move ⇒ Object
30 31 32 33 34 35 36 37 |
# File 'lib/snake2d.rb', line 30 def move if !@growing @positions.shift end @positions.push(next_position) @growing = false end |
#next_position ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 |
# 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 ⇒ Object
48 49 50 |
# File 'lib/snake2d.rb', line 48 def x head[0] end |
#y ⇒ Object
52 53 54 |
# File 'lib/snake2d.rb', line 52 def y head[1] end |