class Snake
Constants
- DOWN
- LEFT
- Pos
- RIGHT
- UP
Direction:
Attributes
body[R]
food[R]
score[R]
Public Class Methods
new(width, height, length = 5)
click to toggle source
# 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
Public Instance Methods
alive?()
click to toggle source
# File lib/ruby-snake/snake.rb, line 54 def alive? @alive end
eat(pos)
click to toggle source
# File lib/ruby-snake/snake.rb, line 82 def eat pos @body.unshift pos @food = make_food @score += 10 end
goto(direction)
click to toggle source
# 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_food()
click to toggle source
# 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)
click to toggle source
# File lib/ruby-snake/snake.rb, line 77 def move pos @body.unshift pos @body.pop end
next_pos(direction)
click to toggle source
# 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