class Mineswiper::Display
Constants
- COLORS
- GLOBAL_BACKGROUND
- KEYMAP
- MOVES
Attributes
board[RW]
Public Class Methods
new(board)
click to toggle source
# File lib/mineswiper/display.rb, line 21 def initialize(board) @board = board @cursor_pos = [0, 0] end
Public Instance Methods
build_grid()
click to toggle source
# File lib/mineswiper/display.rb, line 26 def build_grid @board.grid.each_index do |i| rowdisplay = "" @board.grid[i].each_index do |j| output = board.grid[i][j].tilerender color_options = colors_for(i, j) rowdisplay << output.colorize(color_options) + " ".colorize(background: GLOBAL_BACKGROUND) unless output.nil? end puts rowdisplay end end
colors_for(i, j)
click to toggle source
# File lib/mineswiper/display.rb, line 38 def colors_for(i, j) if [i, j] == @cursor_pos bg = :light_red else bg = GLOBAL_BACKGROUND end if (@board.grid[i][j].hidden == false) color = COLORS[@board.grid[i][j].adj_bombs] if @board.grid[i][j].bomb? color = :light_red end elsif @board.grid[i][j].flagged? color = :light_red else color = :white end { background: bg, color: color } end
get_input()
click to toggle source
# File lib/mineswiper/display.rb, line 81 def get_input key = KEYMAP[read_char] handle_key(key) end
handle_key(key)
click to toggle source
# File lib/mineswiper/display.rb, line 86 def handle_key(key) case key when :ctrl_c exit 0 when :space @cursor_pos when :left, :right, :up, :down update_pos(MOVES[key]) nil when :f [:flag, @cursor_pos] else puts key end end
read_char()
click to toggle source
# File lib/mineswiper/display.rb, line 102 def read_char STDIN.echo = false STDIN.raw! input = STDIN.getc.chr if input == "\e" then input << STDIN.read_nonblock(3) rescue nil input << STDIN.read_nonblock(2) rescue nil end ensure STDIN.echo = true STDIN.cooked! return input end
render()
click to toggle source
# File lib/mineswiper/display.rb, line 58 def render system("clear") puts "W-A-S-D to move the cursor - Spacebar to reveal." build_grid end
update_pos(diff)
click to toggle source
# File lib/mineswiper/display.rb, line 118 def update_pos(diff) new_pos = [@cursor_pos[0] + diff[0], @cursor_pos[1] + diff[1]] @cursor_pos = new_pos if @board.in_bounds?(new_pos) end