class Text2048::App

Controller class.

Attributes

board[R]
view[R]

Public Class Methods

new(view = CursesView.new, board = Board.new, high_score = HighScore.new) click to toggle source
# File lib/text2048/app.rb, line 13
def initialize(view = CursesView.new,
               board = Board.new,
               high_score = HighScore.new)
  @view = view
  @board = board
  @high_score = high_score
end

Public Instance Methods

demo() click to toggle source
# File lib/text2048/app.rb, line 54
def demo
  input [:left, :right, :up, :down][rand(5)]
end
generate(num_tiles = 1) click to toggle source
# File lib/text2048/app.rb, line 32
def generate(num_tiles = 1)
  num_tiles.times { @board = @board.generate }
  @view.update(@board)
  @view.zoom_tiles(@board.generated_tiles)
end
show_title() click to toggle source
# File lib/text2048/app.rb, line 21
def show_title
  @view.high_score(@high_score)
  @view.message = 'PRESS ANY KEY TO START'
  @board = Board.new([[nil, nil, nil, nil],
                      [2, 0, 4, 8],
                      [nil, nil, nil, nil],
                      [nil, nil, nil, nil]])
  @view.update(@board)
  @view.wait_any_key
end
step() click to toggle source
# File lib/text2048/app.rb, line 38
def step
  @view.win if @board.win?
  @view.game_over if @board.lose?
  input @view.command
  @view.high_score(@high_score)
end
wait_any_key(seconds) click to toggle source
# File lib/text2048/app.rb, line 45
def wait_any_key(seconds)
  begin
    timeout(seconds) { @view.wait_any_key }
  rescue Timeout::Error
    return false
  end
  true
end

Private Instance Methods

input(command) click to toggle source
# File lib/text2048/app.rb, line 60
def input(command)
  case command
  when :larger, :smaller
    @view.__send__ command, @board
  when :left, :right, :up, :down
    move_and_generate(command)
  when :quit
    exit 0
  end
end
move(command) click to toggle source
# File lib/text2048/app.rb, line 77
def move(command)
  last = @board
  @board = @board.__send__(command)
  @view.update(@board)
  @view.pop_tiles(@board.merged_tiles)
  last
end
move_and_generate(command) click to toggle source
# File lib/text2048/app.rb, line 71
def move_and_generate(command)
  last = move(command)
  generate if @board.generate?(last)
  @high_score.maybe_update(@board.score)
end