Class: Snake2d::Snake

Inherits:
Object
  • Object
show all
Defined in:
lib/snake2d.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSnake

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

Parameters:

  • value

    the value to set the attribute direction to.



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

Returns:

  • (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

#drawObject



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

#growObject



26
27
28
# File 'lib/snake2d.rb', line 26

def grow
  @growing = true
end

#hit_itself?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/snake2d.rb', line 68

def hit_itself?
  @positions.uniq.length != @positions.length
end

#moveObject



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_positionObject



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

#xObject



48
49
50
# File 'lib/snake2d.rb', line 48

def x
  head[0]
end

#yObject



52
53
54
# File 'lib/snake2d.rb', line 52

def y
  head[1]
end