class RubyTerminalGames::Snake::Game
Attributes
apple[R]
board[R]
counter[R]
direction[R]
points[R]
snake[R]
speed[R]
Public Class Methods
new()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 11 def initialize @direction = RIGHT @board = Board.new @apple = Apple.new( width: @board.width, height: @board.height ) @snake = Snake.new( width: @board.width, height: @board.height ) @points = 0 @speed = 0 @counter = 0 end
Public Instance Methods
about()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 48 def about [ "Remember the good old times. Use the keyboard ", "arrows to control the snake." ].join end
play!()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 30 def play! @playing = true Keyboard.capture(detect_direction: true) do |key| exit if key =~ /q/i next unless direction_allowed?(key) @direction = key end while @playing eat? snake.move!(direction) snake.died? and @playing = false game_interval! board.print_world!(self) end end
Private Instance Methods
add_points!()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 64 def add_points! @points += (1 * @counter += 1) end
direction_allowed?(dir)
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 76 def direction_allowed?(dir) allowed = case @direction when UP, DOWN [LEFT, RIGHT] when LEFT, RIGHT [UP, DOWN] end allowed.include?(dir) end
eat?()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 57 def eat? return unless snake.eat?(apple) snake.grow!(direction) add_points! increase_speed! end
game_interval!()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 72 def game_interval! sleep([0.1 - @speed, 0].max) end
increase_speed!()
click to toggle source
# File lib/ruby_terminal_games/snake/game.rb, line 68 def increase_speed! @speed += 0.0005 end