vcomputer 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. vcomputer/__init__.py +64 -0
  2. vcomputer/__main__.py +7 -0
  3. vcomputer/_version.py +6 -0
  4. vcomputer/api.py +525 -0
  5. vcomputer/backend_pygame.py +344 -0
  6. vcomputer/charset.py +59 -0
  7. vcomputer/cli.py +315 -0
  8. vcomputer/config.py +207 -0
  9. vcomputer/console.py +168 -0
  10. vcomputer/disk.py +222 -0
  11. vcomputer/examples/ball.py +21 -0
  12. vcomputer/examples/charset.py +20 -0
  13. vcomputer/examples/paint.py +34 -0
  14. vcomputer/examples/rainbow.py +26 -0
  15. vcomputer/examples/snake.py +85 -0
  16. vcomputer/font8x8.py +224 -0
  17. vcomputer/gfx.py +176 -0
  18. vcomputer/glyphs.py +266 -0
  19. vcomputer/keyboard.py +146 -0
  20. vcomputer/lessons/01_memory/lesson.md +59 -0
  21. vcomputer/lessons/01_memory/start.py +15 -0
  22. vcomputer/lessons/02_symbols/lesson.md +61 -0
  23. vcomputer/lessons/02_symbols/start.py +26 -0
  24. vcomputer/lessons/03_console/lesson.md +58 -0
  25. vcomputer/lessons/03_console/start.py +24 -0
  26. vcomputer/lessons/04_pixel/lesson.md +52 -0
  27. vcomputer/lessons/04_pixel/start.py +10 -0
  28. vcomputer/machine.py +268 -0
  29. vcomputer/memmap.py +137 -0
  30. vcomputer/memory.py +109 -0
  31. vcomputer/mouse.py +89 -0
  32. vcomputer/palette.py +64 -0
  33. vcomputer/sfx.py +112 -0
  34. vcomputer/sound.py +222 -0
  35. vcomputer/templates/README.md +44 -0
  36. vcomputer/templates/disk_readme.txt +2 -0
  37. vcomputer/templates/main.py +46 -0
  38. vcomputer/templates/vcomputer.toml +24 -0
  39. vcomputer/util.py +19 -0
  40. vcomputer/video.py +253 -0
  41. vcomputer/view.py +136 -0
  42. vcomputer-0.1.0.dist-info/METADATA +192 -0
  43. vcomputer-0.1.0.dist-info/RECORD +46 -0
  44. vcomputer-0.1.0.dist-info/WHEEL +4 -0
  45. vcomputer-0.1.0.dist-info/entry_points.txt +2 -0
  46. vcomputer-0.1.0.dist-info/licenses/LICENSE +21 -0
vcomputer/gfx.py ADDED
@@ -0,0 +1,176 @@
1
+ """Уровень 2: графика — точки, линии, прямоугольники, окружности, спрайты, текст.
2
+
3
+ Всё рисуется в страницу VID_DRAW прямо через память: адрес точки
4
+ page + y * width + x. Координаты за пределами экрана отсекаются без ошибки.
5
+ Этот код — учебный материал: каждую функцию можно написать самому через poke.
6
+ """
7
+
8
+ from . import api, glyphs
9
+ from .memmap import MODE_TEXT, PAGES, VID_DRAW
10
+
11
+
12
+ def _screen():
13
+ """(память, адрес страницы, ширина, высота) для рисования."""
14
+ m = api._m()
15
+ v = m.video
16
+ if v.mode == MODE_TEXT:
17
+ raise RuntimeError(
18
+ "gfx рисует в графических режимах. Включите графику: "
19
+ "vc.set_mode(vc.MODE_GFX)"
20
+ )
21
+ return m.data, PAGES[m.data[VID_DRAW] & 1], v.width, v.height
22
+
23
+
24
+ def _color(c):
25
+ if not isinstance(c, int) or isinstance(c, bool) or not 0 <= c <= 255:
26
+ raise ValueError(f"Цвет должен быть числом от 0 до 255, а получено: {c!r}")
27
+ return c
28
+
29
+
30
+ def clear(c=0):
31
+ """Залить весь экран цветом c."""
32
+ d, page, w, h = _screen()
33
+ d[page:page + w * h] = bytes((_color(c),)) * (w * h)
34
+
35
+
36
+ def pixel(x, y, c):
37
+ d, page, w, h = _screen()
38
+ if 0 <= x < w and 0 <= y < h:
39
+ d[page + y * w + x] = _color(c)
40
+
41
+
42
+ def get_pixel(x, y):
43
+ d, page, w, h = _screen()
44
+ if 0 <= x < w and 0 <= y < h:
45
+ return d[page + y * w + x]
46
+ return 0
47
+
48
+
49
+ def hline(x, y, length, c):
50
+ d, page, w, h = _screen()
51
+ c = _color(c)
52
+ if not 0 <= y < h or length <= 0:
53
+ return
54
+ x0, x1 = max(0, x), min(w, x + length)
55
+ if x0 < x1:
56
+ o = page + y * w
57
+ d[o + x0:o + x1] = bytes((c,)) * (x1 - x0)
58
+
59
+
60
+ def vline(x, y, length, c):
61
+ d, page, w, h = _screen()
62
+ c = _color(c)
63
+ if not 0 <= x < w or length <= 0:
64
+ return
65
+ for yy in range(max(0, y), min(h, y + length)):
66
+ d[page + yy * w + x] = c
67
+
68
+
69
+ def line(x0, y0, x1, y1, c):
70
+ """Отрезок по алгоритму Брезенхэма."""
71
+ d, page, w, h = _screen()
72
+ c = _color(c)
73
+ dx, dy = abs(x1 - x0), -abs(y1 - y0)
74
+ sx = 1 if x0 < x1 else -1
75
+ sy = 1 if y0 < y1 else -1
76
+ err = dx + dy
77
+ while True:
78
+ if 0 <= x0 < w and 0 <= y0 < h:
79
+ d[page + y0 * w + x0] = c
80
+ if x0 == x1 and y0 == y1:
81
+ break
82
+ e2 = 2 * err
83
+ if e2 >= dy:
84
+ err += dy
85
+ x0 += sx
86
+ if e2 <= dx:
87
+ err += dx
88
+ y0 += sy
89
+
90
+
91
+ def rect(x, y, width, height, c):
92
+ """Контур прямоугольника."""
93
+ if width <= 0 or height <= 0:
94
+ return
95
+ hline(x, y, width, c)
96
+ hline(x, y + height - 1, width, c)
97
+ vline(x, y, height, c)
98
+ vline(x + width - 1, y, height, c)
99
+
100
+
101
+ def fill_rect(x, y, width, height, c):
102
+ """Закрашенный прямоугольник."""
103
+ d, page, w, h = _screen()
104
+ c = _color(c)
105
+ x0, x1 = max(0, x), min(w, x + width)
106
+ if x0 >= x1:
107
+ return
108
+ row = bytes((c,)) * (x1 - x0)
109
+ for yy in range(max(0, y), min(h, y + height)):
110
+ o = page + yy * w
111
+ d[o + x0:o + x1] = row
112
+
113
+
114
+ def circle(cx, cy, r, c, fill=False):
115
+ """Окружность (алгоритм средней точки); fill=True — закрашенный круг."""
116
+ if r < 0:
117
+ return
118
+ x, y, err = r, 0, 1 - r
119
+ while x >= y:
120
+ if fill:
121
+ hline(cx - x, cy + y, 2 * x + 1, c)
122
+ hline(cx - x, cy - y, 2 * x + 1, c)
123
+ hline(cx - y, cy + x, 2 * y + 1, c)
124
+ hline(cx - y, cy - x, 2 * y + 1, c)
125
+ else:
126
+ for px, py in ((x, y), (y, x), (-y, x), (-x, y),
127
+ (-x, -y), (-y, -x), (y, -x), (x, -y)):
128
+ pixel(cx + px, cy + py, c)
129
+ y += 1
130
+ if err < 0:
131
+ err += 2 * y + 1
132
+ else:
133
+ x -= 1
134
+ err += 2 * (y - x) + 1
135
+
136
+
137
+ def sprite(x, y, rows, colors, transparent="."):
138
+ """Спрайт из строк: rows = ["..##..", ".####."], colors = {"#": vc.RED}.
139
+ Символ transparent не рисуется (прозрачный)."""
140
+ d, page, w, h = _screen()
141
+ for j, line_ in enumerate(rows):
142
+ yy = y + j
143
+ if not 0 <= yy < h:
144
+ continue
145
+ o = page + yy * w
146
+ for i, ch in enumerate(line_):
147
+ if ch == transparent:
148
+ continue
149
+ xx = x + i
150
+ if 0 <= xx < w:
151
+ if ch not in colors:
152
+ raise KeyError(f"Для символа {ch!r} спрайта не задан цвет в colors")
153
+ d[o + xx] = _color(colors[ch])
154
+
155
+
156
+ def text(x, y, s, c, bg=None, font=8):
157
+ """Текст шрифтом 8×8 (или 8×16) с точки (x, y); bg=None — фон прозрачный."""
158
+ d, page, w, h = _screen()
159
+ c = _color(c)
160
+ if bg is not None:
161
+ bg = _color(bg)
162
+ for k, ch in enumerate(str(s)):
163
+ rows = glyphs.glyph(ch, font, d)
164
+ x0 = x + k * 8
165
+ for j, bits in enumerate(rows):
166
+ yy = y + j
167
+ if not 0 <= yy < h:
168
+ continue
169
+ o = page + yy * w
170
+ for i in range(8):
171
+ xx = x0 + i
172
+ if 0 <= xx < w:
173
+ if (bits >> (7 - i)) & 1:
174
+ d[o + xx] = c
175
+ elif bg is not None:
176
+ d[o + xx] = bg
vcomputer/glyphs.py ADDED
@@ -0,0 +1,266 @@
1
+ """Изображения символов (глифы) для текстового режима, консоли и gfx.text.
2
+
3
+ Откуда берётся глиф:
4
+ 1. Символ есть в сокращённой таблице CHARSET → шрифт FONT8/FONT16 в памяти
5
+ компьютера (его можно перерисовать poke-ами).
6
+ 2. Иначе → встроенный шрифт пакета: нарисованные символы (font8x8.py),
7
+ линии псевдографики и блоки U+2500–U+259F (рисуются программой).
8
+ Для высоты 16 нарисованные символы растягиваются по высоте вдвое,
9
+ а линии и блоки рисуются сразу в нужной высоте.
10
+ 3. Символа нет нигде → «▯».
11
+
12
+ Глиф — bytes длиной 8 или 16, по байту на строку, бит 7 — левая точка.
13
+ """
14
+
15
+ import unicodedata
16
+ from functools import lru_cache
17
+
18
+ from . import charset
19
+ from .font8x8 import GLYPHS
20
+ from .memmap import FONT8, FONT16
21
+
22
+ FALLBACK = "▯"
23
+ WIDTH = 8
24
+
25
+
26
+ # --- линии псевдографики -----------------------------------------------------
27
+
28
+ _WEIGHTS = {"LIGHT": 1, "SINGLE": 1, "DOUBLE": 2, "HEAVY": 3}
29
+ _DIRS = {"UP": "U", "DOWN": "D", "LEFT": "L", "RIGHT": "R",
30
+ "HORIZONTAL": "LR", "VERTICAL": "UD"}
31
+
32
+
33
+ def _box_spec(ch):
34
+ """Разбор имени символа Юникода «BOX DRAWINGS …» в описание линий."""
35
+ try:
36
+ name = unicodedata.name(ch)
37
+ except ValueError:
38
+ return None
39
+ prefix = "BOX DRAWINGS "
40
+ if not name.startswith(prefix):
41
+ return None
42
+ rest = name[len(prefix):]
43
+ dashed = False
44
+ for dash in ("DOUBLE DASH", "TRIPLE DASH", "QUADRUPLE DASH"):
45
+ if dash in rest:
46
+ rest = rest.replace(dash, " ")
47
+ dashed = True
48
+ words = rest.split()
49
+ if "DIAGONAL" in words:
50
+ return {"diag": rest}
51
+ arms = {}
52
+ weight = 1
53
+ clause = []
54
+ for word in words + ["AND"]:
55
+ if word != "AND":
56
+ clause.append(word)
57
+ continue
58
+ ws = [_WEIGHTS[w] for w in clause if w in _WEIGHTS]
59
+ if ws:
60
+ weight = ws[0]
61
+ for w in clause:
62
+ for d in _DIRS.get(w, ""):
63
+ arms[d] = weight
64
+ clause = []
65
+ if not arms:
66
+ return None
67
+ return {"arms": arms, "dashed": dashed}
68
+
69
+
70
+ def _box_pixels(spec, h):
71
+ w = WIDTH
72
+ cx, cy = 3, h // 2 - 1
73
+ pix = [[0] * w for _ in range(h)]
74
+
75
+ def hseg(y, x0, x1):
76
+ for x in range(min(x0, x1), max(x0, x1) + 1):
77
+ if 0 <= x < w and 0 <= y < h:
78
+ pix[y][x] = 1
79
+
80
+ def vseg(x, y0, y1):
81
+ for y in range(min(y0, y1), max(y0, y1) + 1):
82
+ if 0 <= x < w and 0 <= y < h:
83
+ pix[y][x] = 1
84
+
85
+ if "diag" in spec:
86
+ name = spec["diag"]
87
+ for y in range(h):
88
+ x = (y * w) // h
89
+ if "UPPER LEFT TO LOWER RIGHT" in name or "CROSS" in name:
90
+ pix[y][x] = 1
91
+ if "UPPER RIGHT TO LOWER LEFT" in name or "CROSS" in name:
92
+ pix[y][w - 1 - x] = 1
93
+ return pix
94
+
95
+ arms = spec["arms"]
96
+ U, D, L, R = (arms.get(k, 0) for k in "UDLR")
97
+ vdouble = 2 in (U, D)
98
+ hdouble = 2 in (L, R)
99
+
100
+ # Горизонтальные «лучи»: из края клетки к центру.
101
+ for arm, sx in ((L, -1), (R, 1)):
102
+ if not arm:
103
+ continue
104
+ edge = 0 if sx < 0 else w - 1
105
+ opp = R if sx < 0 else L
106
+ if arm == 2:
107
+ for side, y in ((-1, cy - 1), (1, cy + 1)):
108
+ near = U if side < 0 else D # вертикаль с той же стороны
109
+ far = D if side < 0 else U
110
+ if near == 2:
111
+ end = cx + sx # внутренняя линия: до ближней вертикали
112
+ elif near == 0 and far == 2:
113
+ end = cx - sx # внешняя линия угла: до дальней вертикали
114
+ else:
115
+ end = cx
116
+ hseg(y, edge, end)
117
+ else:
118
+ if opp:
119
+ end = cx
120
+ elif vdouble:
121
+ end = cx + sx if (U and D) else cx - sx
122
+ else:
123
+ end = cx
124
+ for y in ([cy] if arm == 1 else [cy, cy + 1]):
125
+ hseg(y, edge, end)
126
+
127
+ # Вертикальные «лучи».
128
+ for arm, sy in ((U, -1), (D, 1)):
129
+ if not arm:
130
+ continue
131
+ edge = 0 if sy < 0 else h - 1
132
+ opp = D if sy < 0 else U
133
+ if arm == 2:
134
+ for side, x in ((-1, cx - 1), (1, cx + 1)):
135
+ near = L if side < 0 else R
136
+ far = R if side < 0 else L
137
+ if near == 2:
138
+ end = cy + sy
139
+ elif near == 0 and far == 2:
140
+ end = cy - sy
141
+ else:
142
+ end = cy
143
+ vseg(x, edge, end)
144
+ else:
145
+ if opp:
146
+ end = cy
147
+ elif hdouble:
148
+ end = cy + sy if (L and R) else cy - sy
149
+ else:
150
+ end = cy
151
+ for x in ([cx] if arm == 1 else [cx, cx + 1]):
152
+ vseg(x, edge, end)
153
+
154
+ if spec["dashed"]:
155
+ horizontal = not (U or D)
156
+ for y in range(h):
157
+ for x in range(w):
158
+ along = x if horizontal else y
159
+ if along % 4 == 3:
160
+ pix[y][x] = 0
161
+ return pix
162
+
163
+
164
+ # --- блоки и штриховки U+2580–U+259F ----------------------------------------------
165
+
166
+ def _block_pixels(ch, h):
167
+ code = ord(ch)
168
+ if not 0x2580 <= code <= 0x259F:
169
+ return None
170
+ w = WIDTH
171
+ pix = [[0] * w for _ in range(h)]
172
+
173
+ def rect(x0, y0, x1, y1): # доли клетки 0..1, [x0, x1) × [y0, y1)
174
+ for y in range(round(y0 * h), round(y1 * h)):
175
+ for x in range(round(x0 * w), round(x1 * w)):
176
+ pix[y][x] = 1
177
+
178
+ q = {"UL": (0, 0, .5, .5), "UR": (.5, 0, 1, .5),
179
+ "LL": (0, .5, .5, 1), "LR": (.5, .5, 1, 1)}
180
+ quads = {0x2596: "LL", 0x2597: "LR", 0x2598: "UL", 0x2599: "UL LL LR",
181
+ 0x259A: "UL LR", 0x259B: "UL UR LL", 0x259C: "UL UR LR",
182
+ 0x259D: "UR", 0x259E: "UR LL", 0x259F: "UR LL LR"}
183
+ if code == 0x2580:
184
+ rect(0, 0, 1, .5)
185
+ elif 0x2581 <= code <= 0x2588: # нижние восьмые … полный блок
186
+ rect(0, 1 - (code - 0x2580) / 8, 1, 1)
187
+ elif 0x2589 <= code <= 0x258F: # левые 7/8 … 1/8
188
+ rect(0, 0, (0x2590 - code) / 8, 1)
189
+ elif code == 0x2590:
190
+ rect(.5, 0, 1, 1)
191
+ elif code in (0x2591, 0x2592, 0x2593):
192
+ for y in range(h):
193
+ for x in range(w):
194
+ light = (x % 4 == 0 and y % 2 == 0) or (x % 4 == 2 and y % 2 == 1)
195
+ if code == 0x2591:
196
+ pix[y][x] = int(light)
197
+ elif code == 0x2592:
198
+ pix[y][x] = int((x + y) % 2 == 0)
199
+ else:
200
+ pix[y][x] = int(not light)
201
+ elif code == 0x2594:
202
+ rect(0, 0, 1, 1 / 8)
203
+ elif code == 0x2595:
204
+ rect(7 / 8, 0, 1, 1)
205
+ else:
206
+ for name in quads[code].split():
207
+ rect(*q[name])
208
+ return pix
209
+
210
+
211
+ def _pack(pix):
212
+ return bytes(sum(1 << (7 - x) for x, p in enumerate(row) if p) for row in pix)
213
+
214
+
215
+ def _stretch(data, h):
216
+ if h == len(data):
217
+ return bytes(data)
218
+ factor = h // len(data)
219
+ return bytes(b for b in data for _ in range(factor))
220
+
221
+
222
+ @lru_cache(maxsize=4096)
223
+ def builtin(ch, h=8):
224
+ """Глиф встроенного шрифта или None, если символа в нём нет."""
225
+ if h not in (8, 16):
226
+ raise ValueError("высота шрифта может быть только 8 или 16")
227
+ if ch == "\0":
228
+ return bytes(h)
229
+ spec = _box_spec(ch)
230
+ if spec is not None:
231
+ return _pack(_box_pixels(spec, h))
232
+ pix = _block_pixels(ch, h)
233
+ if pix is not None:
234
+ return _pack(pix)
235
+ data = GLYPHS.get(ch)
236
+ if data is not None:
237
+ return _stretch(data, h)
238
+ return None
239
+
240
+
241
+ def glyph(ch, h=8, mem=None):
242
+ """Глиф символа: из памяти (для CHARSET), встроенный или «▯»."""
243
+ if mem is not None:
244
+ code = charset.CODES.get(ch)
245
+ if code is not None:
246
+ base = (FONT8 + 8 * code) if h == 8 else (FONT16 + 16 * code)
247
+ return bytes(mem[base:base + h])
248
+ data = builtin(ch, h)
249
+ if data is None:
250
+ data = builtin(FALLBACK, h)
251
+ return data
252
+
253
+
254
+ def has_glyph(ch, h=8):
255
+ return ch in charset.CODES or builtin(ch, h) is not None
256
+
257
+
258
+ def font_rom(h):
259
+ """Начальное содержимое FONT8 (h=8) или FONT16 (h=16) для 256 символов CHARSET."""
260
+ out = bytearray()
261
+ for ch in charset.CHARSET:
262
+ data = builtin(ch, h)
263
+ if data is None:
264
+ data = builtin(FALLBACK, h)
265
+ out += data
266
+ return bytes(out)
vcomputer/keyboard.py ADDED
@@ -0,0 +1,146 @@
1
+ """Клавиатура: коды клавиш, таблица состояния, очереди событий и символов.
2
+
3
+ Коды привязаны к физическим клавишам (scancode), поэтому KEY_W — одна и та же
4
+ клавиша в любой раскладке. Символы (с учётом раскладки и регистра) идут в
5
+ отдельную очередь.
6
+ """
7
+
8
+ from .memmap import (
9
+ CHAR_BUF, CHAR_HEAD, CHAR_OVERFLOW, CHAR_QUEUE, CHAR_SIZE, CHAR_TAIL,
10
+ KEY_EV_HEAD, KEY_EV_OVERFLOW, KEY_EV_SIZE, KEY_EV_TAIL, KEY_EVENTS,
11
+ KEY_MODS, KEY_QUEUE, KEY_STATE,
12
+ )
13
+
14
+ # --- коды клавиш -------------------------------------------------------------
15
+
16
+ KEY_BACKSPACE = 0x08
17
+ KEY_TAB = 0x09
18
+ KEY_ENTER = 0x0D
19
+ KEY_ESC = 0x1B
20
+ KEY_SPACE = 0x20
21
+ KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN = 0x80, 0x81, 0x82, 0x83
22
+ KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN = 0x84, 0x85, 0x86, 0x87
23
+ KEY_INSERT, KEY_DELETE = 0x88, 0x89
24
+ KEY_LSHIFT, KEY_RSHIFT, KEY_LCTRL, KEY_RCTRL, KEY_LALT, KEY_RALT = range(0xA0, 0xA6)
25
+ KEY_MINUS, KEY_EQUALS, KEY_LBRACKET, KEY_RBRACKET, KEY_BACKSLASH = range(0xB0, 0xB5)
26
+ KEY_SEMICOLON, KEY_QUOTE, KEY_BACKQUOTE, KEY_COMMA, KEY_PERIOD, KEY_SLASH = range(0xB5, 0xBB)
27
+ KEY_CAPS_LOCK = 0xBB
28
+
29
+ # Цифры 0–9 и буквы A–Z: коды совпадают с ASCII.
30
+ _NAMES = {f"KEY_{d}": 0x30 + d for d in range(10)}
31
+ _NAMES.update({f"KEY_{chr(c)}": c for c in range(ord("A"), ord("Z") + 1)})
32
+ _NAMES.update({f"KEY_F{n}": 0x90 + n - 1 for n in range(1, 13)})
33
+ _NAMES.update({f"KEY_KP{d}": 0xC0 + d for d in range(10)})
34
+ globals().update(_NAMES)
35
+
36
+ #: Все константы KEY_* этого модуля.
37
+ KEY_CONSTANTS = {k: v for k, v in globals().items() if k.startswith("KEY_") and isinstance(v, int)}
38
+
39
+ # Флаги события
40
+ EV_PRESSED = 0x01
41
+ MOD_SHIFT = 0x02
42
+ MOD_CTRL = 0x04
43
+ MOD_ALT = 0x08
44
+ EV_REPEAT = 0x10
45
+
46
+ # --- scancode SDL -> код клавиши ------------------------------------------------
47
+
48
+ SDL_SCANCODES = {
49
+ 40: KEY_ENTER, 41: KEY_ESC, 42: KEY_BACKSPACE, 43: KEY_TAB, 44: KEY_SPACE,
50
+ 45: KEY_MINUS, 46: KEY_EQUALS, 47: KEY_LBRACKET, 48: KEY_RBRACKET,
51
+ 49: KEY_BACKSLASH, 51: KEY_SEMICOLON, 52: KEY_QUOTE, 53: KEY_BACKQUOTE,
52
+ 54: KEY_COMMA, 55: KEY_PERIOD, 56: KEY_SLASH, 57: KEY_CAPS_LOCK,
53
+ 73: KEY_INSERT, 74: KEY_HOME, 75: KEY_PAGE_UP, 76: KEY_DELETE, 77: KEY_END,
54
+ 78: KEY_PAGE_DOWN, 79: KEY_RIGHT, 80: KEY_LEFT, 81: KEY_DOWN, 82: KEY_UP,
55
+ 88: KEY_ENTER,
56
+ 224: KEY_LCTRL, 225: KEY_LSHIFT, 226: KEY_LALT,
57
+ 228: KEY_RCTRL, 229: KEY_RSHIFT, 230: KEY_RALT,
58
+ }
59
+ SDL_SCANCODES.update({4 + i: ord("A") + i for i in range(26)}) # A–Z
60
+ SDL_SCANCODES.update({30 + i: ord("1") + i for i in range(9)}) # 1–9
61
+ SDL_SCANCODES[39] = ord("0")
62
+ SDL_SCANCODES.update({58 + i: 0x90 + i for i in range(12)}) # F1–F12
63
+ SDL_SCANCODES.update({89 + i: 0xC1 + i for i in range(9)}) # KP1–KP9
64
+ SDL_SCANCODES[98] = 0xC0 # KP0
65
+
66
+ # Клавиши, которые сами по себе дают символ в очереди символов
67
+ CONTROL_CHARS = {KEY_ENTER: "\n", KEY_BACKSPACE: "\b", KEY_TAB: "\t", KEY_ESC: "\x1b"}
68
+
69
+
70
+ def ring_push(data, buf, head_reg, tail_reg, overflow_reg, size, entry):
71
+ """Запись в кольцевой буфер (делает устройство). entry — bytes длины записи."""
72
+ rec = len(entry)
73
+ head, tail = data[head_reg], data[tail_reg]
74
+ nxt = (tail + 1) % size
75
+ if nxt == head:
76
+ if data[overflow_reg] < 255:
77
+ data[overflow_reg] += 1
78
+ return False
79
+ data[buf + tail * rec:buf + (tail + 1) * rec] = entry
80
+ data[tail_reg] = nxt
81
+ return True
82
+
83
+
84
+ def ring_pop(data, buf, head_reg, tail_reg, size, rec):
85
+ """Чтение из кольцевого буфера (делает программа). None — пусто."""
86
+ head, tail = data[head_reg], data[tail_reg]
87
+ if head == tail:
88
+ return None
89
+ entry = bytes(data[buf + head * rec:buf + (head + 1) * rec])
90
+ data[head_reg] = (head + 1) % size
91
+ return entry
92
+
93
+
94
+ class Keyboard:
95
+ def __init__(self, data):
96
+ self.data = data
97
+ data[KEY_EV_SIZE] = KEY_QUEUE
98
+ data[CHAR_SIZE] = CHAR_QUEUE
99
+
100
+ def set_mods(self, mods):
101
+ self.data[KEY_MODS] = mods & (MOD_SHIFT | MOD_CTRL | MOD_ALT)
102
+
103
+ def inject(self, code, pressed, mods=None):
104
+ """Нажатие/отпускание клавиши с кодом code (0–255)."""
105
+ d = self.data
106
+ if mods is not None:
107
+ self.set_mods(mods)
108
+ repeat = pressed and d[KEY_STATE + code] == 1
109
+ d[KEY_STATE + code] = 1 if pressed else 0
110
+ flags = d[KEY_MODS] | (EV_PRESSED if pressed else 0) | (EV_REPEAT if repeat else 0)
111
+ ring_push(d, KEY_EVENTS, KEY_EV_HEAD, KEY_EV_TAIL, KEY_EV_OVERFLOW,
112
+ KEY_QUEUE, bytes((code, flags)))
113
+ if pressed and code in CONTROL_CHARS:
114
+ self.push_char(CONTROL_CHARS[code])
115
+
116
+ def push_char(self, ch):
117
+ cp = ord(ch)
118
+ if cp > 0xFFFF:
119
+ cp = 0xFFFD
120
+ ring_push(self.data, CHAR_BUF, CHAR_HEAD, CHAR_TAIL, CHAR_OVERFLOW,
121
+ CHAR_QUEUE, cp.to_bytes(2, "little"))
122
+
123
+ def push_text(self, text):
124
+ for ch in text:
125
+ self.push_char(ch)
126
+
127
+ def release_all(self):
128
+ """Окно потеряло фокус — все клавиши считаются отпущенными."""
129
+ d = self.data
130
+ for code in range(256):
131
+ if d[KEY_STATE + code]:
132
+ self.inject(code, False)
133
+
134
+ # --- чтение (используется API) ---------------------------------------
135
+
136
+ def read_key(self):
137
+ e = ring_pop(self.data, KEY_EVENTS, KEY_EV_HEAD, KEY_EV_TAIL, KEY_QUEUE, 2)
138
+ if e is None:
139
+ return None
140
+ return e[0], bool(e[1] & EV_PRESSED)
141
+
142
+ def read_char(self):
143
+ e = ring_pop(self.data, CHAR_BUF, CHAR_HEAD, CHAR_TAIL, CHAR_QUEUE, 2)
144
+ if e is None:
145
+ return None
146
+ return chr(e[0] | e[1] << 8)
@@ -0,0 +1,59 @@
1
+ # Урок 1. Память и первый символ
2
+
3
+ ## Что такое память
4
+
5
+ Память компьютера — это длинный ряд ячеек. В каждой ячейке лежит **байт** — число от 0 до 255.
6
+ У каждой ячейки есть номер — **адрес**. У нашего компьютера 5 МиБ памяти: адреса от `0` до `0x4FFFFF`.
7
+
8
+ Запись `0x100000` — число в шестнадцатеричной системе (как 1 048 576 в обычной). Адреса удобно
9
+ писать так, потому что «круглые» адреса выглядят круглыми.
10
+
11
+ ## Видеопамять
12
+
13
+ Компьютер включается в **текстовом режиме**: экран 40 столбцов × 30 строк. Видеокарта 60 раз в секунду
14
+ читает память с адреса `VIDEO0` и показывает то, что там лежит. Каждая клетка экрана — **4 байта**:
15
+
16
+ | Байт | Что в нём |
17
+ |---|---|
18
+ | +0, +1 | номер символа (`ord("A")` = 65, `ord("Ж")` = 1046) |
19
+ | +2 | цвет символа (0–255) |
20
+ | +3 | цвет фона (0–255) |
21
+
22
+ Клетка в строке `row`, столбце `col` начинается с адреса:
23
+
24
+ ```
25
+ VIDEO0 + (row * 40 + col) * 4
26
+ ```
27
+
28
+ ## Пример
29
+
30
+ ```python
31
+ import vcomputer as vc # vc — короткое имя для vcomputer
32
+
33
+ vc.poke16(vc.VIDEO0, ord("A")) # буква A в левый верхний угол (2 байта)
34
+ vc.poke(vc.VIDEO0 + 2, vc.RED) # цвет символа — красный
35
+ print(vc.peek(vc.VIDEO0)) # 65 — то, что лежит в памяти
36
+ ```
37
+
38
+ - `poke(адрес, число)` — записать байт; `peek(адрес)` — прочитать.
39
+ - `poke16` записывает сразу 2 байта (число до 65 535).
40
+ - `vc.mem[адрес] = число` — то же самое, что `poke`, только короче.
41
+
42
+ Запуск: `vcomputer run start.py` (или `python start.py`).
43
+
44
+ ## Задания
45
+
46
+ 1. Напишите своё имя в первой строке, по букве через `poke16`.
47
+ 2. Сделайте фон имени синим (`vc.BLUE`) — байт `+3` каждой клетки.
48
+ 3. Поставьте звёздочку `★` в правый нижний угол. Какой у него адрес?
49
+ 4. Заполните всю первую строку символом `█` с помощью цикла `for`.
50
+ 5. *Нарисуйте «лесенку»: символ `#` в клетках (0, 0), (1, 1), (2, 2) … (29, 29).*
51
+
52
+ ## Что сломается, если…
53
+
54
+ - …записать `vc.poke(vc.VIDEO0, 300)`? Прочитайте сообщение об ошибке.
55
+ - …записать символ по адресу `VIDEO0 + 1`, а не `VIDEO0`?
56
+
57
+ ## Вопрос
58
+
59
+ Сколько байт занимает весь текстовый экран 40 × 30?
@@ -0,0 +1,15 @@
1
+ """Урок 1. Память и первый символ."""
2
+
3
+ import vcomputer as vc
4
+
5
+ vc.poke16(vc.VIDEO0, ord("A")) # символ в клетку (0, 0)
6
+ vc.poke(vc.VIDEO0 + 2, vc.RED) # цвет символа
7
+
8
+ row, col = 2, 5 # строка 2, столбец 5
9
+ addr = vc.VIDEO0 + (row * 40 + col) * 4
10
+ vc.poke16(addr, ord("Ж"))
11
+ vc.poke(addr + 2, vc.YELLOW)
12
+ vc.poke(addr + 3, vc.DARK_BLUE)
13
+
14
+ print("В ячейке", hex(vc.VIDEO0), "лежит", vc.peek(vc.VIDEO0))
15
+ # Ваш код здесь