miniworlds-data 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.
@@ -0,0 +1,169 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import List, Optional, Tuple
4
+
5
+ from miniworlds import Rectangle, Text, World
6
+
7
+
8
+ Color = Tuple[int, int, int] | Tuple[int, int, int, int]
9
+
10
+
11
+ DEFAULT_COLOR: Color = (130, 170, 200, 255)
12
+ TOP_COLOR: Color = (220, 60, 60, 255)
13
+ TEXT_COLOR: Color = (20, 20, 20, 255)
14
+ EMPTY_COLOR: Color = (120, 120, 120, 255)
15
+
16
+
17
+ class _StackBox(Rectangle):
18
+ """A single element box inside a :class:`StackWorld`."""
19
+
20
+ def __init__(
21
+ self,
22
+ value: object,
23
+ *,
24
+ world: "StackWorld",
25
+ color: Color,
26
+ width: float,
27
+ height: float,
28
+ ):
29
+ super().__init__((0, 0), width, height, world=world)
30
+ self.origin = "topleft"
31
+ self.fill_color = color
32
+ self.border = 1
33
+ self.border_color = (255, 255, 255, 255)
34
+ self.is_static = True
35
+ self.value = value
36
+ self._label = Text((0, 0), str(value), world=world)
37
+ self._label.origin = "topleft"
38
+ self._label.color = TEXT_COLOR
39
+ self._label.font_size = max(12, int(height * 0.5))
40
+ self._label.is_static = True
41
+
42
+ def move_to_slot(self, x: float, y: float) -> None:
43
+ self.topleft = (x, y)
44
+ label_x = x + self.width / 2 - self._label.get_text_width() / 2
45
+ label_y = y + self.height / 2 - self._label.font_size / 2
46
+ self._label.topleft = (label_x, label_y)
47
+
48
+ def remove_label(self) -> None:
49
+ if self._label.world is not None:
50
+ self._label.remove()
51
+
52
+
53
+ class StackWorld(World):
54
+ """Pixel world that visualizes a LIFO stack growing upward.
55
+
56
+ Elements are pushed onto the top and popped from the top. The topmost box
57
+ is highlighted in red.
58
+
59
+ Example:
60
+ ::
61
+
62
+ from miniworlds_data import StackWorld
63
+
64
+ world = StackWorld()
65
+ world.push(3)
66
+ world.push(7)
67
+ world.push(2)
68
+ print(world.peek()) # 2
69
+ print(world.pop()) # 2
70
+ world.run()
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ *,
76
+ capacity: int = 8,
77
+ box_width: int = 120,
78
+ box_height: int = 40,
79
+ margin: int = 10,
80
+ background: Color = (245, 245, 245, 255),
81
+ ):
82
+ if capacity <= 0:
83
+ raise ValueError("capacity must be > 0")
84
+ self._capacity = capacity
85
+ self._box_width = box_width
86
+ self._box_height = box_height
87
+ self._margin = margin
88
+ self._boxes: List[_StackBox] = []
89
+
90
+ width = box_width + margin * 2
91
+ height = capacity * box_height + margin * 2
92
+ super().__init__(width, height)
93
+ self.background.fill_color = background
94
+ self._top_label = Text((margin, 2), "top", world=self)
95
+ self._top_label.color = EMPTY_COLOR
96
+ self._top_label.font_size = 12
97
+ self._top_label.is_static = True
98
+
99
+
100
+ def __len__(self) -> int:
101
+ return len(self._boxes)
102
+
103
+ def is_empty(self) -> bool:
104
+ return not self._boxes
105
+
106
+ def is_full(self) -> bool:
107
+ return len(self._boxes) >= self._capacity
108
+
109
+ def peek(self) -> object:
110
+ """Return the top element without removing it.
111
+
112
+ Raises:
113
+ IndexError: when the stack is empty.
114
+ """
115
+ if self.is_empty():
116
+ raise IndexError("peek from empty stack")
117
+ return self._boxes[-1].value
118
+
119
+ def values(self) -> List[object]:
120
+ """Return the current elements, bottom-to-top order."""
121
+ return [box.value for box in self._boxes]
122
+
123
+ def push(self, value: object) -> None:
124
+ """Push ``value`` onto the top of the stack.
125
+
126
+ Raises:
127
+ OverflowError: when the stack is already at capacity.
128
+ """
129
+ if self.is_full():
130
+ raise OverflowError(f"stack overflow (capacity {self._capacity})")
131
+ box = _StackBox(
132
+ value,
133
+ world=self,
134
+ color=DEFAULT_COLOR,
135
+ width=self._box_width,
136
+ height=self._box_height,
137
+ )
138
+ self._boxes.append(box)
139
+ self._relayout()
140
+
141
+ def pop(self) -> object:
142
+ """Remove and return the top element.
143
+
144
+ Raises:
145
+ IndexError: when the stack is empty.
146
+ """
147
+ if self.is_empty():
148
+ raise IndexError("pop from empty stack")
149
+ box = self._boxes.pop()
150
+ box.remove_label()
151
+ box.remove()
152
+ self._relayout()
153
+ return box.value
154
+
155
+ def clear_elements(self) -> None:
156
+ """Remove every element from the stack."""
157
+ for box in self._boxes:
158
+ box.remove_label()
159
+ box.remove()
160
+ self._boxes.clear()
161
+ self._relayout()
162
+
163
+ def _relayout(self) -> None:
164
+ x = self._margin
165
+ for index, box in enumerate(self._boxes):
166
+ y = self.height - self._margin - (index + 1) * self._box_height
167
+ box.move_to_slot(x, y)
168
+ box.fill_color = TOP_COLOR if index == len(self._boxes) - 1 else DEFAULT_COLOR
169
+ self._top_label.text = "top" if self._boxes else "empty"
@@ -0,0 +1,200 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Callable, Generator, List, Optional, Tuple
4
+
5
+
6
+ # A step is a (name, payload) tuple the algorithm yields to mark a visible state.
7
+ # Example: ("compare", (i, j)) or ("swap", (i, j)) or ("mark_sorted", i).
8
+ Step = Tuple[str, object]
9
+
10
+
11
+ class Stepper:
12
+ """Drives a generator-based algorithm one visible step per frame.
13
+
14
+ Classical algorithms written as loops run entirely within a single frame,
15
+ so their intermediate states are never visible. ``Stepper`` solves this by
16
+ letting the algorithm be written as a *generator* that yields once per
17
+ step; the stepper advances it frame by frame (or on demand).
18
+
19
+ Each yielded step is a ``(name, payload)`` tuple (see :data:`Step`). The
20
+ stepper records every step so it can replay them forward and backward. For
21
+ backward stepping (``prev_step``, ``reset``, ``goto``) you must pass an
22
+ ``on_reset`` callback that restores the visualization to its initial
23
+ state, since algorithm steps like "swap" are not idempotent.
24
+
25
+ Example:
26
+ ::
27
+
28
+ from miniworlds_data import ListWorld, Stepper
29
+
30
+ world = ListWorld([5, 2, 4, 1, 3])
31
+
32
+ def bubble_sort(data):
33
+ n = len(data.values)
34
+ for i in range(n):
35
+ for j in range(n - i - 1):
36
+ yield "compare", (j, j + 1)
37
+ if data.values[j] > data.values[j + 1]:
38
+ yield "swap", (j, j + 1)
39
+
40
+ stepper = Stepper(bubble_sort(world), world, on_step=apply_step)
41
+ stepper.run() # advances one step per frame automatically
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ algorithm: Generator[Step, None, None],
47
+ world=None,
48
+ *,
49
+ on_step: Optional[Callable[[Step], None]] = None,
50
+ on_reset: Optional[Callable[[], None]] = None,
51
+ frames_per_step: int = 1,
52
+ ):
53
+ self._algorithm: Optional[Generator[Step, None, None]] = algorithm
54
+ self.world = world
55
+ self._on_step = on_step
56
+ self._on_reset = on_reset
57
+ self._frames_per_step = max(1, int(frames_per_step))
58
+ self._history: List[Step] = []
59
+ self._index: int = -1 # index of the most recently applied step
60
+ self._frame_counter: int = 0
61
+ self._finished: bool = False
62
+ self._registered_worlds = set()
63
+
64
+ # -- state -----------------------------------------------------------
65
+
66
+ @property
67
+ def steps(self) -> List[Step]:
68
+ """All steps recorded so far, in execution order."""
69
+ return list(self._history)
70
+
71
+ @property
72
+ def step_index(self) -> int:
73
+ """Index of the currently applied step (-1 before the first step)."""
74
+ return self._index
75
+
76
+ @property
77
+ def finished(self) -> bool:
78
+ """``True`` once the generator has been exhausted."""
79
+ return self._finished
80
+
81
+ @property
82
+ def auto_advance(self) -> bool:
83
+ """Whether the stepper advances automatically each frame."""
84
+ return bool(self._registered_worlds)
85
+
86
+ # -- single-step control --------------------------------------------
87
+
88
+ def next_step(self) -> Optional[Step]:
89
+ """Advance the algorithm by exactly one step and apply it.
90
+
91
+ Returns the applied step, or ``None`` at the end of the history
92
+ once the generator has been exhausted.
93
+ """
94
+ # We already have this step in history (e.g. after stepping back).
95
+ next_index = self._index + 1
96
+ if next_index < len(self._history):
97
+ step = self._history[next_index]
98
+ else:
99
+ step = self._pull_next_step()
100
+ if step is None:
101
+ return None
102
+
103
+ self._index = next_index
104
+ self._apply(step)
105
+ return step
106
+
107
+ def prev_step(self) -> Optional[Step]:
108
+ """Undo the most recently applied step and move backward.
109
+
110
+ Returns the step that was undone, or ``None`` at the beginning.
111
+
112
+ Raises ``RuntimeError`` if a rewind is needed and no ``on_reset``
113
+ callback was provided.
114
+ """
115
+ if self._index < 0:
116
+ return None
117
+ undone = self._history[self._index]
118
+ self._rewind(self._index - 1)
119
+ return undone
120
+
121
+ def reset(self) -> None:
122
+ """Rewind to the beginning and apply no steps.
123
+
124
+ Raises ``RuntimeError`` if no ``on_reset`` callback was provided.
125
+ """
126
+ self._rewind(-1)
127
+
128
+ def goto(self, index: int) -> None:
129
+ """Move to an absolute step index.
130
+
131
+ A negative index rewinds to the start; an index past the end advances
132
+ as far as the generator allows. Backward jumps require ``on_reset``.
133
+ """
134
+ target = max(-1, index)
135
+ if target < self._index:
136
+ self._rewind(target)
137
+ return
138
+ while self._index < target:
139
+ if self.next_step() is None:
140
+ break
141
+
142
+ # -- automatic frame-based driving ---------------------------------
143
+
144
+ def run(self, world=None) -> None:
145
+ """Register an ``act`` hook on the world that advances one step per frame.
146
+
147
+ Args:
148
+ world: World to register on. Defaults to the world passed at
149
+ construction time.
150
+ """
151
+ world = self.world if world is None else world
152
+ if world is None:
153
+ raise ValueError("Stepper.run() needs a world to register the act hook")
154
+ if world in self._registered_worlds:
155
+ return
156
+
157
+ @world.register
158
+ def act(_self):
159
+ self.on_frame()
160
+
161
+ self._registered_worlds.add(world)
162
+
163
+ def on_frame(self) -> Optional[Step]:
164
+ """Advance one step every ``frames_per_step`` frames.
165
+
166
+ Call this manually from your own ``act`` hook if you do not use
167
+ :meth:`run`.
168
+ """
169
+ self._frame_counter += 1
170
+ if self._frame_counter < self._frames_per_step:
171
+ return None
172
+ self._frame_counter = 0
173
+ return self.next_step()
174
+
175
+ # -- internal --------------------------------------------------------
176
+
177
+ def _pull_next_step(self) -> Optional[Step]:
178
+ if self._algorithm is None:
179
+ return None
180
+ try:
181
+ step = next(self._algorithm)
182
+ except StopIteration:
183
+ self._finished = True
184
+ self._algorithm = None
185
+ return None
186
+ self._history.append(step)
187
+ return step
188
+
189
+ def _apply(self, step: Step) -> None:
190
+ if self._on_step is not None:
191
+ self._on_step(step)
192
+
193
+ def _rewind(self, index: int) -> None:
194
+ if self._on_reset is None:
195
+ raise RuntimeError("Rewinding a Stepper requires an on_reset callback")
196
+ self._on_reset()
197
+ self._index = -1
198
+ self._frame_counter = 0
199
+ for _ in range(index + 1):
200
+ self.next_step()
@@ -0,0 +1,290 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ from miniworlds import Circle, Line, Text, World
6
+
7
+
8
+ Color = Tuple[int, int, int] | Tuple[int, int, int, int]
9
+
10
+
11
+ DEFAULT_COLOR: Color = (130, 170, 200, 255)
12
+ VISITED_COLOR: Color = (90, 190, 110, 255)
13
+ CURRENT_COLOR: Color = (245, 200, 60, 255)
14
+ ROOT_COLOR: Color = (220, 60, 60, 255)
15
+ EDGE_COLOR: Color = (140, 140, 140, 255)
16
+ EDGE_VISITED_COLOR: Color = (90, 190, 110, 255)
17
+ TEXT_COLOR: Color = (20, 20, 20, 255)
18
+
19
+
20
+ class TreeNode(Circle):
21
+ """A node actor in a :class:`TreeWorld`.
22
+
23
+ Each node stores a value, optional left/right children, and a highlight
24
+ state used during traversals. Edges to its children are drawn as lines.
25
+ """
26
+
27
+ def __init__(self, value: object, *, world: "TreeWorld", radius: int, color: Color):
28
+ super().__init__((0, 0), radius, world=world)
29
+ self.origin = "center"
30
+ self.fill_color = color
31
+ self.border = 2
32
+ self.border_color = (255, 255, 255, 255)
33
+ self.is_static = True
34
+ self.layer = 1
35
+ self.value: object = value
36
+ self.left: Optional[TreeNode] = None
37
+ self.right: Optional[TreeNode] = None
38
+ self._state: str = "default"
39
+ self._label = Text((0, 0), str(value), world=world)
40
+ self._label.origin = "center"
41
+ self._label.color = TEXT_COLOR
42
+ self._label.font_size = max(10, int(radius * 0.8))
43
+ self._label.is_static = True
44
+ self._label.layer = 2
45
+
46
+ @property
47
+ def state(self) -> str:
48
+ return self._state
49
+
50
+ def set_state(self, state: str) -> None:
51
+ self._state = state
52
+ self.fill_color = _STATE_COLORS.get(state, DEFAULT_COLOR)
53
+
54
+ def center_on(self, x: float, y: float) -> None:
55
+ self.center = (x, y)
56
+ self._label.center = (x, y)
57
+
58
+ def remove_label(self) -> None:
59
+ if self._label.world is not None:
60
+ self._label.remove()
61
+
62
+
63
+ _STATE_COLORS = {
64
+ "default": DEFAULT_COLOR,
65
+ "visited": VISITED_COLOR,
66
+ "current": CURRENT_COLOR,
67
+ "root": ROOT_COLOR,
68
+ }
69
+
70
+
71
+ class TreeWorld(World):
72
+ """Pixel world that visualizes a binary tree.
73
+
74
+ Nodes are added as a root plus left/right children. The world computes a
75
+ level-order layout automatically and exposes traversal-friendly highlight
76
+ methods.
77
+
78
+ Example:
79
+ ::
80
+
81
+ from miniworlds_data import TreeWorld
82
+
83
+ world = TreeWorld()
84
+ root = world.set_root(5)
85
+ world.add_left(root, 3)
86
+ world.add_right(root, 8)
87
+ world.highlight(root, "current")
88
+ world.run()
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ *,
94
+ width: int = 600,
95
+ height: int = 400,
96
+ node_radius: int = 22,
97
+ level_height: int = 70,
98
+ column_width: int = 60,
99
+ background: Color = (250, 250, 250, 255),
100
+ ):
101
+ super().__init__(width, height)
102
+ self.background.fill_color = background
103
+ self._node_radius = node_radius
104
+ self._level_height = level_height
105
+ self._column_width = column_width
106
+ self._root: Optional[TreeNode] = None
107
+ self._all_nodes: List[TreeNode] = []
108
+ self._edges: List[Line] = []
109
+
110
+ @property
111
+ def root(self) -> Optional[TreeNode]:
112
+ return self._root
113
+
114
+ @property
115
+ def nodes(self) -> List[TreeNode]:
116
+ return list(self._all_nodes)
117
+
118
+ def set_root(self, value: object) -> TreeNode:
119
+ """Create the root node and return it."""
120
+ if self._root is not None:
121
+ raise ValueError("root already set")
122
+ node = TreeNode(value, world=self, radius=self._node_radius, color=ROOT_COLOR)
123
+ node.set_state("root")
124
+ self._root = node
125
+ self._all_nodes.append(node)
126
+ self._relayout()
127
+ return node
128
+
129
+ def add_left(self, parent: TreeNode, value: object) -> TreeNode:
130
+ """Add a left child to ``parent`` and return it."""
131
+ self._require_node(parent)
132
+ if parent.left is not None:
133
+ raise ValueError("left child already exists")
134
+ node = self._create_child(value)
135
+ parent.left = node
136
+ self._relayout()
137
+ return node
138
+
139
+ def add_right(self, parent: TreeNode, value: object) -> TreeNode:
140
+ """Add a right child to ``parent`` and return it."""
141
+ self._require_node(parent)
142
+ if parent.right is not None:
143
+ raise ValueError("right child already exists")
144
+ node = self._create_child(value)
145
+ parent.right = node
146
+ self._relayout()
147
+ return node
148
+
149
+ def _require_node(self, node: TreeNode) -> None:
150
+ if node.world is not self or node not in self._all_nodes:
151
+ raise ValueError("node does not belong to this TreeWorld")
152
+
153
+ def _create_child(self, value: object) -> TreeNode:
154
+ node = TreeNode(value, world=self, radius=self._node_radius, color=DEFAULT_COLOR)
155
+ self._all_nodes.append(node)
156
+ return node
157
+
158
+ def highlight(self, node: TreeNode, state: str = "current") -> None:
159
+ """Highlight a node with the given state.
160
+
161
+ Args:
162
+ node: Node to highlight.
163
+ state: One of ``default``, ``visited``, ``current``, ``root``.
164
+ """
165
+ self._require_node(node)
166
+ node.set_state(state)
167
+
168
+ def highlight_edge(self, parent: TreeNode, child: TreeNode, visited: bool = True) -> None:
169
+ """Color the edge between ``parent`` and ``child`` as visited/unvisited."""
170
+ self._require_node(parent)
171
+ self._require_node(child)
172
+ for edge in self._edges:
173
+ if self._edge_matches(edge, parent, child):
174
+ edge.fill_color = EDGE_VISITED_COLOR if visited else EDGE_COLOR
175
+ return
176
+
177
+ @staticmethod
178
+ def _edge_matches(edge: Line, parent: TreeNode, child: TreeNode) -> bool:
179
+ if not hasattr(edge, "_endpoints"):
180
+ return False
181
+ p, c = edge._endpoints # type: ignore[attr-defined]
182
+ return (p is parent and c is child) or (p is child and c is parent)
183
+
184
+ def reset_colors(self) -> None:
185
+ """Reset every node to its default/root state and edges to default color."""
186
+ for node in self._all_nodes:
187
+ node.set_state("root" if node is self._root else "default")
188
+ for edge in self._edges:
189
+ edge.fill_color = EDGE_COLOR
190
+
191
+ # -- traversal helpers (non-visual) --------------------------------
192
+
193
+ def inorder(self) -> List[TreeNode]:
194
+ """Return nodes in in-order sequence."""
195
+ result: List[TreeNode] = []
196
+ self._inorder(self._root, result)
197
+ return result
198
+
199
+ def preorder(self) -> List[TreeNode]:
200
+ """Return nodes in pre-order sequence."""
201
+ result: List[TreeNode] = []
202
+ self._preorder(self._root, result)
203
+ return result
204
+
205
+ def postorder(self) -> List[TreeNode]:
206
+ """Return nodes in post-order sequence."""
207
+ result: List[TreeNode] = []
208
+ self._postorder(self._root, result)
209
+ return result
210
+
211
+ def _inorder(self, node: Optional[TreeNode], acc: List[TreeNode]) -> None:
212
+ if node is None:
213
+ return
214
+ self._inorder(node.left, acc)
215
+ acc.append(node)
216
+ self._inorder(node.right, acc)
217
+
218
+ def _preorder(self, node: Optional[TreeNode], acc: List[TreeNode]) -> None:
219
+ if node is None:
220
+ return
221
+ acc.append(node)
222
+ self._preorder(node.left, acc)
223
+ self._preorder(node.right, acc)
224
+
225
+ def _postorder(self, node: Optional[TreeNode], acc: List[TreeNode]) -> None:
226
+ if node is None:
227
+ return
228
+ self._postorder(node.left, acc)
229
+ self._postorder(node.right, acc)
230
+ acc.append(node)
231
+
232
+ # -- layout --------------------------------------------------------
233
+
234
+ def _relayout(self) -> None:
235
+ self._clear_edges()
236
+ if self._root is None:
237
+ return
238
+ positions: Dict[TreeNode, float] = {}
239
+ self._assign_x_positions(self._root, 0, positions)
240
+ depth = self._assign_depths(self._root, 0, {})
241
+ # In-order offsets run from 0 to max; center the tree around the
242
+ # world midpoint and space columns by _column_width pixels.
243
+ mid = (max(positions.values()) if positions else 0) / 2
244
+ for node, x_offset in positions.items():
245
+ depth_n = depth.get(node, 0)
246
+ y = 40 + depth_n * self._level_height
247
+ x = self.width / 2 + (x_offset - mid) * self._column_width
248
+ node.center_on(x, y)
249
+ self._draw_edges(self._root)
250
+
251
+ def _assign_x_positions(
252
+ self,
253
+ node: Optional[TreeNode],
254
+ x: float,
255
+ positions: Dict[TreeNode, float],
256
+ ) -> float:
257
+ if node is None:
258
+ return x
259
+ x = self._assign_x_positions(node.left, x, positions)
260
+ positions[node] = x
261
+ return self._assign_x_positions(node.right, x + 1, positions)
262
+
263
+ def _assign_depths(
264
+ self, node: Optional[TreeNode], depth: int, acc: Dict[TreeNode, int]
265
+ ) -> Dict[TreeNode, int]:
266
+ if node is None:
267
+ return acc
268
+ acc[node] = depth
269
+ self._assign_depths(node.left, depth + 1, acc)
270
+ self._assign_depths(node.right, depth + 1, acc)
271
+ return acc
272
+
273
+ def _clear_edges(self) -> None:
274
+ for edge in self._edges:
275
+ edge.remove()
276
+ self._edges.clear()
277
+
278
+ def _draw_edges(self, node: Optional[TreeNode]) -> None:
279
+ if node is None:
280
+ return
281
+ for child in (node.left, node.right):
282
+ if child is not None:
283
+ edge = Line(node.center, child.center, world=self)
284
+ edge.fill_color = EDGE_COLOR
285
+ edge.border = 2
286
+ edge.is_static = True
287
+ edge._endpoints = (node, child) # type: ignore[attr-defined]
288
+ edge.layer = 0
289
+ self._edges.append(edge)
290
+ self._draw_edges(child)