Class: Teletype::Page

Inherits:
Object
  • Object
show all
Defined in:
lib/teletype/page.rb

Overview

Prints lines of text to screen and handles key strokes.

Instance Method Summary collapse

Constructor Details

#initialize(lines, screen, stats) ⇒ Page



6
7
8
9
10
11
# File 'lib/teletype/page.rb', line 6

def initialize(lines, screen, stats)
  @lines = lines.map { |line| line.gsub("\t", '⇥') }
  @screen = screen
  @stats = stats
  @y = -1
end

Instance Method Details

#advance(char) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/teletype/page.rb', line 48

def advance(char)
  at = @line[@x]
  if char == at
    @stats.hit!(at)
    print(correct(char))
  else
    @stats.miss!(at)
    print(wrong(visible(char)))
  end
  @x += 1
  fetch if @x == @line.length
  to(@x, @y)
end

#correct(str) ⇒ Object



89
90
91
# File 'lib/teletype/page.rb', line 89

def correct(str)
  "\e[2;32m#{str}\e[0m"
end

#default(str) ⇒ Object



85
86
87
# File 'lib/teletype/page.rb', line 85

def default(str)
  "\e[94m#{str}\e[0m"
end

#eraseObject



62
63
64
65
66
67
68
69
# File 'lib/teletype/page.rb', line 62

def erase
  return unless @x.positive?

  @x -= 1
  to(@x, @y)
  print default(@line[@x])
  to(@x, @y)
end

#fetchObject



13
14
15
16
17
18
19
20
21
22
# File 'lib/teletype/page.rb', line 13

def fetch
  loop do
    @line = @lines.shift
    @y += 1
    break if @line.nil? || @line.strip.length.positive?
  end

  # skip white spaces at the beginning of a line
  @x = @line&.match(/[[:graph:]]/)&.pre_match&.length || 0
end

#runObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/teletype/page.rb', line 24

def run
  @screen.fill(@lines.map { |line| default(line) })

  fetch
  to(@x, @y)

  loop do
    break if @lines.empty? && @line.nil?

    char = Key.read

    case char
    when '⏻'
      exit
    when '⌫'
      erase
    else
      advance(char)
    end

    @screen.log(@stats.rankings)
  end
end

#to(x, y) ⇒ Object



71
72
73
# File 'lib/teletype/page.rb', line 71

def to(x, y)
  @screen.to(x, y)
end

#visible(char) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/teletype/page.rb', line 75

def visible(char)
  case char
  when ' ' then '␣'
  when "\n" then '↵'
  when ("\u0001".."\u001A") then '⌃' # Ctrl[a-z]
  when /^\e/ then '�'
  else; char
  end
end

#wrong(str) ⇒ Object



93
94
95
# File 'lib/teletype/page.rb', line 93

def wrong(str)
  "\e[91m#{str}\e[0m"
end