Class: Snake

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-snake/snake.rb

Defined Under Namespace

Classes: Pos

Constant Summary collapse

UP =

Direction:

0
RIGHT =
1
DOWN =
2
LEFT =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(width, height, length = 5) ⇒ Snake

Returns a new instance of Snake.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ruby-snake/snake.rb', line 11

def initialize width, height, length = 5
  @body = []
  @direction = RIGHT
  length.times  do |i| 
    @body << Pos.new(length - i + 1, height)
  end
  @width, @height = width, height
  @food = make_food
  @wall = []
  0.upto(width) do |i|
    @wall << Pos.new(i, 0)
    @wall << Pos.new(i, height + 1)
  end
  1.upto(height - 1) do |j|
    @wall << Pos.new(0, j)
    @wall << Pos.new(width + 1, j)
  end
  @alive = true
  @score = 0
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



9
10
11
# File 'lib/ruby-snake/snake.rb', line 9

def body
  @body
end

#foodObject (readonly)

Returns the value of attribute food.



9
10
11
# File 'lib/ruby-snake/snake.rb', line 9

def food
  @food
end

#scoreObject (readonly)

Returns the value of attribute score.



9
10
11
# File 'lib/ruby-snake/snake.rb', line 9

def score
  @score
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/ruby-snake/snake.rb', line 54

def alive?
  @alive
end

#eat(pos) ⇒ Object



82
83
84
85
86
# File 'lib/ruby-snake/snake.rb', line 82

def eat pos
  @body.unshift pos
  @food = make_food
  @score += 10
end

#goto(direction) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ruby-snake/snake.rb', line 40

def goto direction
  n_pos = next_pos direction
  tail = @body.last
  case
  when @wall.include?(n_pos) || @body.include?(n_pos)
    @alive = false
  when n_pos == @food
    eat n_pos
  else
    move n_pos
  end
  tail # when the snake moves, the UI class could know which cell should be erased.

end

#make_foodObject



32
33
34
35
36
37
38
# File 'lib/ruby-snake/snake.rb', line 32

def make_food
  food = Pos.new(rand(@width - 2) + 2, rand(@height - 1) + 1)
  while @body.include?(food)
    food = Pos.new(rand(@width - 2) + 2, rand(@height - 1) + 1)
  end
  food
end

#move(pos) ⇒ Object



77
78
79
80
# File 'lib/ruby-snake/snake.rb', line 77

def move pos
  @body.unshift pos
  @body.pop
end

#next_pos(direction) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/ruby-snake/snake.rb', line 58

def next_pos direction
  if [[RIGHT, LEFT], [UP, DOWN]].include? [direction, @direction].sort
    direction = @direction
  else
    @direction = direction
  end
  head = @body[0]
  case direction
  when UP
    Pos.new(head.x, head.y - 1)
  when DOWN
    Pos.new(head.x, head.y + 1)
  when RIGHT
    Pos.new(head.x + 1, head.y)
  when LEFT
    Pos.new(head.x - 1, head.y)
  end
end