Skip to content

Instantly share code, notes, and snippets.

@pauloromeira
Created March 24, 2015 15:31
Show Gist options
  • Save pauloromeira/3a5ec46943b5be414b12 to your computer and use it in GitHub Desktop.
Save pauloromeira/3a5ec46943b5be414b12 to your computer and use it in GitHub Desktop.
# Python 3.4
import curses as cs
import random as rd
import sys
l = []
for i in range(33, 127):
l.append(chr(i))
port = 'áéíóú' 'âêô' 'ãõ' 'à' 'ç'
l.extend(port)
l.extend(port.upper())
errors = {}
def main(win):
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as f:
inpt = f.read()
train(win, inpt)
else:
len_l = len(l)
while True:
rd.shuffle(l)
inpt = ''
for i in range(len_l):
inpt += l[i]
if (i + 1) % 20 == 0 or i == len_l - 1:
inpt += '\n'
elif rd.random() < .3:
inpt += ' '
train(win, inpt)
def train(win, inpt):
i = 0
while i < len(inpt):
refresh(win, inpt, i)
c = win.get_wch()
if c == cs.KEY_BACKSPACE or c == '\x7f':
if i == 0:
continue
i -=1
if i in errors:
del errors[i]
else:
if c != inpt[i]:
cs.beep()
errors[i] = c
i += 1
def parse_char(ch, expected=None):
expected = expected or ch
if ch == '\n':
res = '↵'
elif ch == ' ':
res = '␣'
elif ch not in l:
res = '•'
else:
res = ch
if expected == '\n':
res += '\n'
return str(res)
def refresh(win, inpt, i):
win.clear()
if i > 0 and i <= len(inpt):
for j in range(i):
if j in errors:
win.addstr(parse_char(errors[j], inpt[j]), cs.A_BLINK)
else:
win.addstr(inpt[j], cs.A_REVERSE)
if i < len(inpt):
cpos = win.getyx()
win.addstr(parse_char(inpt[i]))
if i < len(inpt) - 1:
win.addstr(inpt[i+1:])
win.move(cpos[0], cpos[1])
win.refresh()
if __name__ == '__main__':
try:
cs.initscr()
cs.noecho()
cs.cbreak()
win = cs.newwin(0,0,1,2)
win.keypad(1)
main(win)
except KeyboardInterrupt:
pass
finally:
cs.echo()
cs.nocbreak()
cs.endwin()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment