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

Returns a new instance of Page.



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

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

Instance Method Details

#advance(char) ⇒ Object



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

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



95
96
97
# File 'lib/teletype/page.rb', line 95

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

#default(str) ⇒ Object



91
92
93
# File 'lib/teletype/page.rb', line 91

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

#eraseObject



68
69
70
71
72
73
74
75
# File 'lib/teletype/page.rb', line 68

def erase
  return unless @x.positive?

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

#fetchObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/teletype/page.rb', line 12

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

  @x = if (spaces = @line&.match(/\A\ +/))
         spaces[0].length
       else
         0
       end
end

#runObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/teletype/page.rb', line 30

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



77
78
79
# File 'lib/teletype/page.rb', line 77

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

#visible(char) ⇒ Object



81
82
83
84
85
86
87
88
89
# File 'lib/teletype/page.rb', line 81

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



99
100
101
# File 'lib/teletype/page.rb', line 99

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