-
Notifications
You must be signed in to change notification settings - Fork 0
/
curses_tools.py
80 lines (55 loc) · 2.23 KB
/
curses_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import time
SPACE_KEY_CODE = 32
LEFT_KEY_CODE = 260
RIGHT_KEY_CODE = 261
UP_KEY_CODE = 259
DOWN_KEY_CODE = 258
def read_controls(canvas):
"""Read keys pressed and returns tuple witl controls state."""
rows_direction = columns_direction = 0
space_pressed = False
while True:
pressed_key_code = canvas.getch()
if pressed_key_code == -1:
# https://docs.python.org/3/library/curses.html#curses.window.getch
break
if pressed_key_code == UP_KEY_CODE:
rows_direction = -1
if pressed_key_code == DOWN_KEY_CODE:
rows_direction = 1
if pressed_key_code == RIGHT_KEY_CODE:
columns_direction = 1
if pressed_key_code == LEFT_KEY_CODE:
columns_direction = -1
if pressed_key_code == SPACE_KEY_CODE:
space_pressed = True
return rows_direction, columns_direction, space_pressed
def draw_frame(canvas, start_row, start_column, text, negative=False):
"""Draw multiline text fragment on canvas, erase text instead of drawing if negative=True is specified."""
rows_number, columns_number = canvas.getmaxyx()
for row, line in enumerate(text.splitlines(), round(start_row)):
if row < 0:
continue
if row >= rows_number:
break
for column, symbol in enumerate(line, round(start_column)):
if column < 0:
continue
if column >= columns_number:
break
if symbol == ' ':
continue
# Check that current position it is not in a lower right corner of the window
# Curses will raise exception in that case. Don`t ask why…
# https://docs.python.org/3/library/curses.html#curses.window.addch
if row == rows_number - 1 and column == columns_number - 1:
continue
symbol = symbol if not negative else ' '
canvas.addch(row, column, symbol)
def get_frame_size(text):
"""Calculate size of multiline text fragment, return pair — number of rows and colums."""
lines = text.splitlines()
rows = len(lines)
columns = max([len(line) for line in lines])
return rows, columns