Class: RubyTerminalGames::Sudoku::Game

Inherits:
Game
  • Object
show all
Defined in:
lib/ruby_terminal_games/sudoku/game.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Game

#about

Constructor Details

#initializeGame



8
9
10
11
12
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 8

def initialize
  @puzzle = Puzzle.new
  @board = Board.new
  @user_input_index = 0
end

Instance Attribute Details

#boardObject (readonly)

Returns the value of attribute board.



7
8
9
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 7

def board
  @board
end

#puzzleObject (readonly)

Returns the value of attribute puzzle.



7
8
9
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 7

def puzzle
  @puzzle
end

#user_inputObject (readonly)

Returns the value of attribute user_input.



7
8
9
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 7

def user_input
  @user_input
end

#user_input_indexObject (readonly)

Returns the value of attribute user_input_index.



7
8
9
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 7

def user_input_index
  @user_input_index
end

Instance Method Details

#add_user_input(input) ⇒ Object



72
73
74
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 72

def add_user_input(input)
  puzzle.add_input(input, user_input_index)
end

#allowed_input?(key) ⇒ Boolean



68
69
70
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 68

def allowed_input?(key)
  ('0'..'9').include?(key)
end

#direction_key?(key) ⇒ Boolean



50
51
52
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 50

def direction_key?(key)
  [UP, LEFT, RIGHT, DOWN].include?(key)
end

#move_user_input(key) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 54

def move_user_input(key)
  moved = case key
  when UP
    [user_input_index - 9, 0].max
  when RIGHT
    [user_input_index + 1, 80].min
  when LEFT
    [user_input_index - 1, 0].max
  when DOWN
    [user_input_index + 9, 80].min
  end
  @user_input_index = moved
end

#play!Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 14

def play!
  @playing = true
  Keyboard.capture(detect_direction: true) do |key|
    begin
      @playing = false if key =~ /q/
      if direction_key?(key)
        move_user_input(key)
      else
        if allowed_input?(key)
          add_user_input(key.to_i)
        end
      end
    rescue
      Keyboard.stop_capture
      @playing = false
    end
  end

  while @playing
    board.print_board(self)
    sleep(0.1)
  end
end

#user_inputsObject



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ruby_terminal_games/sudoku/game.rb', line 38

def user_inputs
  @user_inputs ||= begin
    inputs = []
    [2, 3, 4, 6, 7, 8, 10, 11, 12].each do |row|
      [2, 4, 6, 8, 10, 12, 14, 16, 18].each do |col|
        inputs << [row, col]
      end
    end
    inputs
  end
end