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,18 @@
1
+ from miniworlds_data.graph_world import GraphEdge, GraphNode, GraphWorld
2
+ from miniworlds_data.list_world import ListWorld
3
+ from miniworlds_data.queue_world import QueueWorld
4
+ from miniworlds_data.stack_world import StackWorld
5
+ from miniworlds_data.stepper import Stepper
6
+ from miniworlds_data.tree_world import TreeNode, TreeWorld
7
+
8
+ __all__ = [
9
+ "GraphEdge",
10
+ "GraphNode",
11
+ "GraphWorld",
12
+ "ListWorld",
13
+ "QueueWorld",
14
+ "StackWorld",
15
+ "Stepper",
16
+ "TreeNode",
17
+ "TreeWorld",
18
+ ]
@@ -0,0 +1,258 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, Iterable, 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
+ FRONTIER_COLOR: Color = (160, 110, 220, 255)
15
+ START_COLOR: Color = (220, 60, 60, 255)
16
+ TARGET_COLOR: Color = (60, 140, 210, 255)
17
+ PATH_COLOR: Color = (90, 190, 110, 255)
18
+ EDGE_COLOR: Color = (160, 160, 160, 255)
19
+ EDGE_VISITED_COLOR: Color = (90, 190, 110, 255)
20
+ EDGE_PATH_COLOR: Color = (220, 120, 50, 255)
21
+ TEXT_COLOR: Color = (20, 20, 20, 255)
22
+
23
+
24
+ class GraphNode(Circle):
25
+ """A node actor in a :class:`GraphWorld`."""
26
+
27
+ def __init__(self, name: str, value: object, *, world: "GraphWorld", 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.name: str = name
36
+ self.value: object = value
37
+ self._state: str = "default"
38
+ self._label = Text((0, 0), str(value), world=world)
39
+ self._label.origin = "center"
40
+ self._label.color = TEXT_COLOR
41
+ self._label.font_size = max(10, int(radius * 0.8))
42
+ self._label.is_static = True
43
+ self._label.layer = 2
44
+
45
+ @property
46
+ def state(self) -> str:
47
+ return self._state
48
+
49
+ def set_state(self, state: str, color: Optional[Color] = None) -> None:
50
+ self._state = state
51
+ self.fill_color = color if color is not None else _STATE_COLORS.get(state, DEFAULT_COLOR)
52
+
53
+ def center_on(self, x: float, y: float) -> None:
54
+ self.center = (x, y)
55
+ self._label.center = (x, y)
56
+
57
+ def remove_label(self) -> None:
58
+ if self._label.world is not None:
59
+ self._label.remove()
60
+
61
+
62
+ _STATE_COLORS = {
63
+ "default": DEFAULT_COLOR,
64
+ "visited": VISITED_COLOR,
65
+ "current": CURRENT_COLOR,
66
+ "frontier": FRONTIER_COLOR,
67
+ "start": START_COLOR,
68
+ "target": TARGET_COLOR,
69
+ "path": PATH_COLOR,
70
+ }
71
+
72
+
73
+ class GraphEdge(Line):
74
+ """An edge actor in a :class:`GraphWorld` connecting two nodes."""
75
+
76
+ def __init__(self, source: GraphNode, target: GraphNode, *, world: "GraphWorld"):
77
+ super().__init__(source.center, target.center, world=world)
78
+ self.fill_color = EDGE_COLOR
79
+ self.border = 2
80
+ self.is_static = True
81
+ self.source = source
82
+ self.target = target
83
+ self.layer = 0
84
+
85
+ def refresh(self) -> None:
86
+ self.start_position = self.source.center
87
+ self.end_position = self.target.center
88
+
89
+ def set_state(self, state: str, color: Optional[Color] = None) -> None:
90
+ if color is not None:
91
+ self.fill_color = color
92
+ elif state == "visited":
93
+ self.fill_color = EDGE_VISITED_COLOR
94
+ elif state == "path":
95
+ self.fill_color = EDGE_PATH_COLOR
96
+ else:
97
+ self.fill_color = EDGE_COLOR
98
+
99
+
100
+ class GraphWorld(World):
101
+ """Pixel world that visualizes an undirected graph.
102
+
103
+ Nodes are added by name at explicit positions and connected by edges. The
104
+ world is well-suited for pathfinding (BFS/DFS) and traversal tasks.
105
+
106
+ Example:
107
+ ``GraphWorld()`` creates a drawing area for named nodes. Use
108
+ ``add_node(...)`` and ``connect(...)`` to build the graph, then call
109
+ ``set_start(...)``, ``set_target(...)``, or ``highlight(...)`` while an
110
+ algorithm runs.
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ *,
116
+ width: int = 600,
117
+ height: int = 400,
118
+ node_radius: int = 22,
119
+ background: Color = (250, 250, 250, 255),
120
+ ):
121
+ super().__init__(width, height)
122
+ self.background.fill_color = background
123
+ self._node_radius = node_radius
124
+ self._nodes: Dict[str, GraphNode] = {}
125
+ self._edges: List[GraphEdge] = []
126
+ self._adjacency: Dict[str, Dict[str, GraphEdge]] = {}
127
+ self._start: Optional[str] = None
128
+ self._target: Optional[str] = None
129
+
130
+ @property
131
+ def nodes(self) -> List[GraphNode]:
132
+ return list(self._nodes.values())
133
+
134
+ @property
135
+ def edges(self) -> List[GraphEdge]:
136
+ return list(self._edges)
137
+
138
+ def add_node(self, name: str, value: object = None, position: Optional[Tuple[float, float]] = None) -> GraphNode:
139
+ """Add a node and return it.
140
+
141
+ Args:
142
+ name: Unique node identifier.
143
+ value: Displayed value (defaults to ``name``).
144
+ position: Center position. Defaults to the world center.
145
+ """
146
+ if name in self._nodes:
147
+ raise ValueError(f"node {name!r} already exists")
148
+ x, y = position if position is not None else (self.width / 2, self.height / 2)
149
+ value = name if value is None else value
150
+ node = GraphNode(name, value, world=self, radius=self._node_radius, color=DEFAULT_COLOR)
151
+ node.center_on(x, y)
152
+ self._nodes[name] = node
153
+ self._adjacency[name] = {}
154
+ return node
155
+
156
+ def get_node(self, name: str) -> GraphNode:
157
+ """Return the node with the given name."""
158
+ try:
159
+ return self._nodes[name]
160
+ except KeyError:
161
+ raise KeyError(f"unknown node {name!r}") from None
162
+
163
+ def connect(self, source: str | GraphNode, target: str | GraphNode) -> GraphEdge:
164
+ """Connect two nodes with an undirected edge and return it."""
165
+ src = self._coerce_node(source)
166
+ dst = self._coerce_node(target)
167
+ if src is dst:
168
+ raise ValueError("cannot connect a node to itself")
169
+ if dst.name in self._adjacency[src.name]:
170
+ raise ValueError(f"edge {src.name}-{dst.name} already exists")
171
+ edge = GraphEdge(src, dst, world=self)
172
+ self._adjacency[src.name][dst.name] = edge
173
+ self._adjacency[dst.name][src.name] = edge
174
+ self._edges.append(edge)
175
+ return edge
176
+
177
+ def neighbors(self, node: str | GraphNode) -> List[GraphNode]:
178
+ """Return the neighbors of a node in the order they were connected."""
179
+ name = self._coerce_name(node)
180
+ return [self._nodes[n] for n in self._adjacency[name]]
181
+
182
+ def set_start(self, node: str | GraphNode) -> None:
183
+ """Mark the search start in red. A shared start and target stays blue."""
184
+ name = self._coerce_name(node)
185
+ previous = self._start
186
+ self._start = name
187
+ if previous is not None and previous != name:
188
+ self.get_node(previous).set_state(self._endpoint_state(previous))
189
+ self.get_node(name).set_state(self._endpoint_state(name))
190
+
191
+ def set_target(self, node: str | GraphNode) -> None:
192
+ """Mark a node as the search target (blue)."""
193
+ name = self._coerce_name(node)
194
+ previous = self._target
195
+ self._target = name
196
+ if previous is not None and previous != name:
197
+ self.get_node(previous).set_state(self._endpoint_state(previous))
198
+ self.get_node(name).set_state("target")
199
+
200
+ def highlight(self, node: str | GraphNode, state: str = "current", color: Optional[Color] = None) -> None:
201
+ """Highlight a node with a named state or an explicit color.
202
+
203
+ Args:
204
+ node: Node name or instance.
205
+ state: One of ``default``, ``visited``, ``current``, ``frontier``,
206
+ ``start``, ``target``, ``path``.
207
+ color: Optional explicit color overriding the state's default color.
208
+ """
209
+ self._coerce_node(node).set_state(state, color)
210
+
211
+ def highlight_edge(self, source: str | GraphNode, target: str | GraphNode, state: str = "visited", color: Optional[Color] = None) -> None:
212
+ """Highlight the edge between two nodes."""
213
+ src_name = self._coerce_name(source)
214
+ dst_name = self._coerce_name(target)
215
+ edge = self._adjacency[src_name].get(dst_name)
216
+ if edge is not None:
217
+ edge.set_state(state, color)
218
+
219
+ def reset_colors(self) -> None:
220
+ """Reset every node to its start/target/default state and edges to default color."""
221
+ for name, node in self._nodes.items():
222
+ node.set_state(self._endpoint_state(name))
223
+ for edge in self._edges:
224
+ edge.set_state("default")
225
+
226
+ def path_edges(self, path: Iterable[str | GraphNode]) -> None:
227
+ """Highlight the edges along a sequence of node names or instances.
228
+
229
+ Raises ``ValueError`` if consecutive nodes are not connected.
230
+ """
231
+ names = [self._coerce_name(n) for n in path]
232
+ path_edges = []
233
+ for source, target in zip(names, names[1:]):
234
+ edge = self._adjacency[source].get(target)
235
+ if edge is None:
236
+ raise ValueError(f"no edge between {source!r} and {target!r}")
237
+ path_edges.append(edge)
238
+ for edge in self._edges:
239
+ edge.set_state("default")
240
+ for edge in path_edges:
241
+ edge.set_state("path")
242
+
243
+ def _endpoint_state(self, name: str) -> str:
244
+ if name == self._target:
245
+ return "target"
246
+ if name == self._start:
247
+ return "start"
248
+ return "default"
249
+
250
+ def _coerce_node(self, node: str | GraphNode) -> GraphNode:
251
+ if isinstance(node, GraphNode):
252
+ if node.world is not self or self._nodes.get(node.name) is not node:
253
+ raise ValueError("node does not belong to this GraphWorld")
254
+ return node
255
+ return self.get_node(node)
256
+
257
+ def _coerce_name(self, node: str | GraphNode) -> str:
258
+ return self._coerce_node(node).name
@@ -0,0 +1,239 @@
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
+ # Standardized algorithm-visualization color language.
12
+ DEFAULT_COLOR: Color = (130, 170, 200, 255) # idle / unsorted
13
+ COMPARE_COLOR: Color = (245, 200, 60, 255) # currently being compared
14
+ SWAP_COLOR: Color = (220, 60, 60, 255) # about to be swapped
15
+ SORTED_COLOR: Color = (90, 190, 110, 255) # final position reached
16
+ PIVOT_COLOR: Color = (160, 110, 220, 255) # pivot / current key
17
+ MARK_COLOR: Color = (60, 140, 210, 255) # arbitrary marker (min/max index)
18
+ TEXT_COLOR: Color = (20, 20, 20, 255)
19
+
20
+
21
+ class _ListCell(Rectangle):
22
+ """A single visual cell (bar + value label) of a :class:`ListWorld`."""
23
+
24
+ def __init__(
25
+ self,
26
+ value: int | float,
27
+ *,
28
+ world: "ListWorld",
29
+ index: int,
30
+ color: Color,
31
+ width: float,
32
+ height: float,
33
+ label_height: float,
34
+ ):
35
+ super().__init__((0, 0), width, height, world=world)
36
+ self.origin = "topleft"
37
+ self.fill_color = color
38
+ self.border = 1
39
+ self.border_color = (255, 255, 255, 255)
40
+ self.is_static = True
41
+ self.value: int | float = value
42
+ self.index: int = index
43
+ self._state: str = "default"
44
+ self.label_height = label_height
45
+ self._label = Text((0, 0), str(value), world=world)
46
+ self._label.origin = "topleft"
47
+ self._label.color = TEXT_COLOR
48
+ self._label.font_size = max(10, int(label_height * 0.6))
49
+ self._label.is_static = True
50
+
51
+ @property
52
+ def state(self) -> str:
53
+ return self._state
54
+
55
+ def set_state(self, state: str, color: Optional[Color] = None) -> None:
56
+ self._state = state
57
+ self.fill_color = color if color is not None else _STATE_COLORS[state]
58
+
59
+ def set_value(self, value: int | float) -> None:
60
+ self.value = value
61
+ self._label.set_text(str(value))
62
+
63
+ def move_to_slot(self, x: float, bar_y: float) -> None:
64
+ self.topleft = (x, bar_y)
65
+ label_y = bar_y + self.height + 2
66
+ self._label.topleft = (x, label_y)
67
+
68
+ def remove_label(self) -> None:
69
+ if self._label.world is not None:
70
+ self._label.remove()
71
+
72
+
73
+ _STATE_COLORS = {
74
+ "default": DEFAULT_COLOR,
75
+ "compare": COMPARE_COLOR,
76
+ "swap": SWAP_COLOR,
77
+ "sorted": SORTED_COLOR,
78
+ "pivot": PIVOT_COLOR,
79
+ "mark": MARK_COLOR,
80
+ }
81
+
82
+
83
+ class ListWorld(World):
84
+ """Pixel world that visualizes a list of values as an array of bars.
85
+
86
+ The world exposes high-level operations such as ``highlight()``,
87
+ ``compare()``, and ``swap()`` that algorithms use to make single steps
88
+ visible. The named states are ``default``, ``compare``, ``swap``,
89
+ ``sorted``, ``pivot``, and ``mark``.
90
+
91
+ Example:
92
+ ``ListWorld([5, 2, 4, 1, 3])`` creates a bar visualization. Calling
93
+ ``compare(0, 1)``, ``swap(0, 1)``, and ``mark_sorted(0)`` updates the
94
+ visible state for a sorting algorithm.
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ values: List[int | float] | None = None,
100
+ *,
101
+ cell_width: int = 50,
102
+ bar_height: int = 200,
103
+ label_height: int = 30,
104
+ margin: int = 10,
105
+ background: Color = (245, 245, 245, 255),
106
+ ):
107
+ values = list(values) if values is not None else []
108
+ if not values:
109
+ raise ValueError("ListWorld requires at least one value")
110
+ if any(not isinstance(v, (int, float)) for v in values):
111
+ raise TypeError("ListWorld values must be int or float")
112
+
113
+ self._cell_width = cell_width
114
+ self._bar_height = bar_height
115
+ self._label_height = label_height
116
+ self._margin = margin
117
+ self._cells: List[_ListCell] = []
118
+
119
+ width = len(values) * cell_width + margin * 2
120
+ height = bar_height + label_height + margin * 2 + label_height
121
+ super().__init__(width, height)
122
+ self.background.fill_color = background
123
+
124
+ for index, value in enumerate(values):
125
+ self._cells.append(self._build_cell(value, index))
126
+ self._relayout()
127
+
128
+ def _build_cell(self, value: int | float, index: int) -> _ListCell:
129
+ return _ListCell(
130
+ value,
131
+ world=self,
132
+ index=index,
133
+ color=DEFAULT_COLOR,
134
+ width=self._cell_width,
135
+ height=self._bar_height,
136
+ label_height=self._label_height,
137
+ )
138
+
139
+ def _relayout(self) -> None:
140
+ values = self.values
141
+ minimum = min(min(values), 0)
142
+ value_range = max(max(values) - minimum, 1)
143
+ base_y = self._margin + self._bar_height
144
+ for index, cell in enumerate(self._cells):
145
+ x = self._margin + index * self._cell_width
146
+ normalized = (cell.value - minimum) / value_range
147
+ cell.height = self._bar_height * max(0.05, normalized)
148
+ cell.move_to_slot(x, base_y - cell.height)
149
+
150
+ # -- read access -----------------------------------------------------
151
+
152
+ @property
153
+ def values(self) -> List[int | float]:
154
+ """Current values, read left-to-right."""
155
+ return [cell.value for cell in self._cells]
156
+
157
+ @property
158
+ def length(self) -> int:
159
+ return len(self._cells)
160
+
161
+ def is_sorted(self) -> bool:
162
+ """Return ``True`` when the values are non-decreasing."""
163
+ values = self.values
164
+ return all(values[i] <= values[i + 1] for i in range(len(values) - 1))
165
+
166
+ # -- high-level algorithm operations --------------------------------
167
+
168
+ def set_color(self, index: int, state: str, color: Optional[Color] = None) -> None:
169
+ """Color a cell with a named state or an explicit color.
170
+
171
+ Args:
172
+ index: Cell index.
173
+ state: One of ``default``, ``compare``, ``swap``, ``sorted``,
174
+ ``pivot``, ``mark``.
175
+ color: Optional explicit color overriding the state's default color.
176
+ """
177
+ self._cells[self._validate_index(index)].set_state(state, color)
178
+
179
+ def highlight(self, index: int, state: str = "compare") -> None:
180
+ """Color a cell with one of the named states.
181
+
182
+ Args:
183
+ index: Cell index.
184
+ state: Named state (see class docstring).
185
+ """
186
+ self.set_color(index, state)
187
+
188
+ def mark_sorted(self, index: int) -> None:
189
+ """Mark a cell as having reached its final (sorted) position."""
190
+ self.set_color(index, "sorted")
191
+
192
+ def reset_color(self, index: int) -> None:
193
+ """Reset a cell back to the default (unsorted) color."""
194
+ self.set_color(index, "default")
195
+
196
+ def reset_all(self) -> None:
197
+ """Reset every cell back to the default color."""
198
+ for index in range(self.length):
199
+ self.reset_color(index)
200
+
201
+ def compare(self, i: int, j: int) -> bool:
202
+ """Highlight cells ``i`` and ``j`` and return ``values[i] > values[j]``.
203
+
204
+ This is the canonical "one comparison" step for sorting/search tasks.
205
+ """
206
+ self._validate_index(i)
207
+ self._validate_index(j)
208
+ self.set_color(i, "compare")
209
+ self.set_color(j, "compare")
210
+ return self._cells[i].value > self._cells[j].value
211
+
212
+ def swap(self, i: int, j: int) -> None:
213
+ """Swap the values (and bar heights) of cells ``i`` and ``j``.
214
+
215
+ Both cells are colored with the ``swap`` state during the operation.
216
+ """
217
+ self._validate_index(i)
218
+ self._validate_index(j)
219
+ cell_i, cell_j = self._cells[i], self._cells[j]
220
+ cell_i.set_state("swap")
221
+ cell_j.set_state("swap")
222
+ cell_i.value, cell_j.value = cell_j.value, cell_i.value
223
+ cell_i.set_value(cell_i.value)
224
+ cell_j.set_value(cell_j.value)
225
+ self._relayout()
226
+
227
+ def set_value(self, index: int, value: int | float) -> None:
228
+ """Set the value of a cell and relayout all bars."""
229
+ if not isinstance(value, (int, float)):
230
+ raise TypeError("value must be int or float")
231
+ self._cells[self._validate_index(index)].set_value(value)
232
+ self._relayout()
233
+
234
+ def _validate_index(self, index: int) -> int:
235
+ if not isinstance(index, int):
236
+ raise TypeError(f"index must be int, got {type(index).__name__}")
237
+ if index < 0 or index >= self.length:
238
+ raise IndexError(f"ListWorld index {index} out of range (0..{self.length - 1})")
239
+ return index
File without changes
@@ -0,0 +1,185 @@
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
+ FRONT_COLOR: Color = (220, 60, 60, 255)
13
+ BACK_COLOR: Color = (160, 110, 220, 255)
14
+ TEXT_COLOR: Color = (20, 20, 20, 255)
15
+ EMPTY_COLOR: Color = (120, 120, 120, 255)
16
+
17
+
18
+ class _QueueBox(Rectangle):
19
+ """A single element box inside a :class:`QueueWorld`."""
20
+
21
+ def __init__(
22
+ self,
23
+ value: object,
24
+ *,
25
+ world: "QueueWorld",
26
+ color: Color,
27
+ width: float,
28
+ height: float,
29
+ ):
30
+ super().__init__((0, 0), width, height, world=world)
31
+ self.origin = "topleft"
32
+ self.fill_color = color
33
+ self.border = 1
34
+ self.border_color = (255, 255, 255, 255)
35
+ self.is_static = True
36
+ self.value = value
37
+ self._label = Text((0, 0), str(value), world=world)
38
+ self._label.origin = "topleft"
39
+ self._label.color = TEXT_COLOR
40
+ self._label.font_size = max(12, int(height * 0.5))
41
+ self._label.is_static = True
42
+
43
+ def move_to_slot(self, x: float, y: float) -> None:
44
+ self.topleft = (x, y)
45
+ label_x = x + self.width / 2 - self._label.get_text_width() / 2
46
+ label_y = y + self.height / 2 - self._label.font_size / 2
47
+ self._label.topleft = (label_x, label_y)
48
+
49
+ def remove_label(self) -> None:
50
+ if self._label.world is not None:
51
+ self._label.remove()
52
+
53
+
54
+ class QueueWorld(World):
55
+ """Pixel world that visualizes a FIFO queue growing left-to-right.
56
+
57
+ Elements are enqueued at the back and dequeued at the front. The front
58
+ box is highlighted in red, the back box in purple.
59
+
60
+ Example:
61
+ ::
62
+
63
+ from miniworlds_data import QueueWorld
64
+
65
+ world = QueueWorld()
66
+ world.enqueue(3)
67
+ world.enqueue(7)
68
+ world.enqueue(2)
69
+ print(world.front()) # 3
70
+ print(world.dequeue()) # 3
71
+ world.run()
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ capacity: int = 8,
78
+ box_width: int = 80,
79
+ box_height: int = 50,
80
+ margin: int = 10,
81
+ background: Color = (245, 245, 245, 255),
82
+ ):
83
+ if capacity <= 0:
84
+ raise ValueError("capacity must be > 0")
85
+ self._capacity = capacity
86
+ self._box_width = box_width
87
+ self._box_height = box_height
88
+ self._margin = margin
89
+ self._boxes: List[_QueueBox] = []
90
+
91
+ width = capacity * box_width + margin * 2
92
+ height = box_height + margin * 2 + 20
93
+ super().__init__(width, height)
94
+ self.background.fill_color = background
95
+ self._front_label = Text((margin, margin + box_height + 2), "front", world=self)
96
+ self._front_label.color = EMPTY_COLOR
97
+ self._front_label.font_size = 12
98
+ self._front_label.is_static = True
99
+
100
+
101
+ def __len__(self) -> int:
102
+ return len(self._boxes)
103
+
104
+ def is_empty(self) -> bool:
105
+ return not self._boxes
106
+
107
+ def is_full(self) -> bool:
108
+ return len(self._boxes) >= self._capacity
109
+
110
+ def front(self) -> object:
111
+ """Return the front element without removing it.
112
+
113
+ Raises:
114
+ IndexError: when the queue is empty.
115
+ """
116
+ if self.is_empty():
117
+ raise IndexError("front of empty queue")
118
+ return self._boxes[0].value
119
+
120
+ def back(self) -> object:
121
+ """Return the back element without removing it.
122
+
123
+ Raises:
124
+ IndexError: when the queue is empty.
125
+ """
126
+ if self.is_empty():
127
+ raise IndexError("back of empty queue")
128
+ return self._boxes[-1].value
129
+
130
+ def values(self) -> List[object]:
131
+ """Return the current elements, front-to-back order."""
132
+ return [box.value for box in self._boxes]
133
+
134
+ def enqueue(self, value: object) -> None:
135
+ """Add ``value`` to the back of the queue.
136
+
137
+ Raises:
138
+ OverflowError: when the queue is already at capacity.
139
+ """
140
+ if self.is_full():
141
+ raise OverflowError(f"queue overflow (capacity {self._capacity})")
142
+ box = _QueueBox(
143
+ value,
144
+ world=self,
145
+ color=DEFAULT_COLOR,
146
+ width=self._box_width,
147
+ height=self._box_height,
148
+ )
149
+ self._boxes.append(box)
150
+ self._relayout()
151
+
152
+ def dequeue(self) -> object:
153
+ """Remove and return the front element.
154
+
155
+ Raises:
156
+ IndexError: when the queue is empty.
157
+ """
158
+ if self.is_empty():
159
+ raise IndexError("dequeue from empty queue")
160
+ box = self._boxes.pop(0)
161
+ box.remove_label()
162
+ box.remove()
163
+ self._relayout()
164
+ return box.value
165
+
166
+ def clear_elements(self) -> None:
167
+ """Remove every element from the queue."""
168
+ for box in self._boxes:
169
+ box.remove_label()
170
+ box.remove()
171
+ self._boxes.clear()
172
+ self._relayout()
173
+
174
+ def _relayout(self) -> None:
175
+ y = self._margin
176
+ for index, box in enumerate(self._boxes):
177
+ x = self._margin + index * self._box_width
178
+ box.move_to_slot(x, y)
179
+ if index == 0:
180
+ box.fill_color = FRONT_COLOR
181
+ elif index == len(self._boxes) - 1:
182
+ box.fill_color = BACK_COLOR
183
+ else:
184
+ box.fill_color = DEFAULT_COLOR
185
+ self._front_label.text = "front" if self._boxes else "empty"