miniworlds-data 0.1.0__tar.gz
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.
- miniworlds_data-0.1.0/LICENSE +21 -0
- miniworlds_data-0.1.0/PKG-INFO +113 -0
- miniworlds_data-0.1.0/README.md +97 -0
- miniworlds_data-0.1.0/pyproject.toml +29 -0
- miniworlds_data-0.1.0/setup.cfg +4 -0
- miniworlds_data-0.1.0/source/miniworlds_data/__init__.py +18 -0
- miniworlds_data-0.1.0/source/miniworlds_data/graph_world.py +258 -0
- miniworlds_data-0.1.0/source/miniworlds_data/list_world.py +239 -0
- miniworlds_data-0.1.0/source/miniworlds_data/py.typed +0 -0
- miniworlds_data-0.1.0/source/miniworlds_data/queue_world.py +185 -0
- miniworlds_data-0.1.0/source/miniworlds_data/stack_world.py +169 -0
- miniworlds_data-0.1.0/source/miniworlds_data/stepper.py +200 -0
- miniworlds_data-0.1.0/source/miniworlds_data/tree_world.py +290 -0
- miniworlds_data-0.1.0/source/miniworlds_data.egg-info/PKG-INFO +113 -0
- miniworlds_data-0.1.0/source/miniworlds_data.egg-info/SOURCES.txt +17 -0
- miniworlds_data-0.1.0/source/miniworlds_data.egg-info/dependency_links.txt +1 -0
- miniworlds_data-0.1.0/source/miniworlds_data.egg-info/requires.txt +1 -0
- miniworlds_data-0.1.0/source/miniworlds_data.egg-info/top_level.txt +1 -0
- miniworlds_data-0.1.0/test/test_data_worlds.py +697 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Andreas Siebel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: miniworlds-data
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Data structure visualization worlds for miniworlds
|
|
5
|
+
Author: Andreas Siebel
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Intended Audience :: Education
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python
|
|
10
|
+
Classifier: Topic :: Education
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: miniworlds
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# miniworlds_data
|
|
18
|
+
|
|
19
|
+
`miniworlds_data` is an extension library for miniworlds. It provides pixel
|
|
20
|
+
worlds that visualize classic data structures so that algorithms (search,
|
|
21
|
+
sorting, traversal, pathfinding) can be shown step by step.
|
|
22
|
+
|
|
23
|
+
The library builds everything from miniworlds worlds and actors. It does not
|
|
24
|
+
load pygame sprites or expose pygame primitives.
|
|
25
|
+
|
|
26
|
+
The package lives in its own repository and uses miniworlds as its rendering
|
|
27
|
+
engine.
|
|
28
|
+
|
|
29
|
+
## Worlds
|
|
30
|
+
|
|
31
|
+
| World | Visualizes | Typical algorithms |
|
|
32
|
+
|--------------|----------------------|--------------------------------------------|
|
|
33
|
+
| `ListWorld` | array of bars | linear/binary search, bubble/selection sort |
|
|
34
|
+
| `StackWorld` | LIFO stack | recursion / call-stack, DFS, undo |
|
|
35
|
+
| `QueueWorld` | FIFO queue | BFS frontier |
|
|
36
|
+
| `TreeWorld` | binary tree | traversals (pre/in/post-order), BST search |
|
|
37
|
+
| `GraphWorld` | graph with edges | BFS, DFS, shortest path |
|
|
38
|
+
|
|
39
|
+
Each world uses the same standardized color language for highlight states
|
|
40
|
+
(`default`, `compare`, `swap`, `sorted`, `pivot`, `visited`, `current`,
|
|
41
|
+
`frontier`, `start`, `target`, `path`).
|
|
42
|
+
|
|
43
|
+
## Stepper
|
|
44
|
+
|
|
45
|
+
Algorithms written as plain loops run inside a single frame, so intermediate
|
|
46
|
+
states are never visible. `Stepper` solves this: the algorithm is written as a
|
|
47
|
+
*generator* that `yield`s once per step, and the stepper advances it one step
|
|
48
|
+
per frame (or on demand).
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from miniworlds_data import ListWorld, Stepper
|
|
52
|
+
|
|
53
|
+
initial = [5, 2, 4, 1, 3]
|
|
54
|
+
world = ListWorld(initial)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def apply_step(step):
|
|
58
|
+
name, (i, j) = step
|
|
59
|
+
world.reset_all()
|
|
60
|
+
if name == "compare":
|
|
61
|
+
world.compare(i, j)
|
|
62
|
+
elif name == "swap":
|
|
63
|
+
world.swap(i, j)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def bubble_sort(data):
|
|
67
|
+
n = data.length
|
|
68
|
+
for i in range(n):
|
|
69
|
+
for j in range(n - i - 1):
|
|
70
|
+
yield "compare", (j, j + 1)
|
|
71
|
+
if data.values[j] > data.values[j + 1]:
|
|
72
|
+
yield "swap", (j, j + 1)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
stepper = Stepper(bubble_sort(world), world, on_step=apply_step)
|
|
76
|
+
stepper.run() # advances one step per frame
|
|
77
|
+
world.run()
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`Stepper` also supports single stepping (`next_step`), going back (`prev_step`),
|
|
81
|
+
`reset`, and `goto`. Pass an `on_reset` callback that restores the initial values
|
|
82
|
+
and highlights to use `reset` or move backward. Recorded steps can be replayed
|
|
83
|
+
after the generator finishes. See [Bubble Sort with the Stepper](examples/03_bubble_sort_stepper.py)
|
|
84
|
+
for an example with an `on_reset` callback.
|
|
85
|
+
|
|
86
|
+
## Example: sorting
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from miniworlds_data import ListWorld
|
|
90
|
+
|
|
91
|
+
world = ListWorld([5, 2, 4, 1, 3])
|
|
92
|
+
world.compare(0, 1)
|
|
93
|
+
world.swap(0, 1)
|
|
94
|
+
world.mark_sorted(0)
|
|
95
|
+
world.run()
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Example: graph pathfinding
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from miniworlds_data import GraphWorld
|
|
102
|
+
|
|
103
|
+
world = GraphWorld()
|
|
104
|
+
a = world.add_node("A", "A", (100, 100))
|
|
105
|
+
b = world.add_node("B", "B", (300, 100))
|
|
106
|
+
c = world.add_node("C", "C", (200, 250))
|
|
107
|
+
world.connect(a, b)
|
|
108
|
+
world.connect(a, c)
|
|
109
|
+
world.connect(b, c)
|
|
110
|
+
world.set_start(a)
|
|
111
|
+
world.set_target(c)
|
|
112
|
+
world.run()
|
|
113
|
+
```
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# miniworlds_data
|
|
2
|
+
|
|
3
|
+
`miniworlds_data` is an extension library for miniworlds. It provides pixel
|
|
4
|
+
worlds that visualize classic data structures so that algorithms (search,
|
|
5
|
+
sorting, traversal, pathfinding) can be shown step by step.
|
|
6
|
+
|
|
7
|
+
The library builds everything from miniworlds worlds and actors. It does not
|
|
8
|
+
load pygame sprites or expose pygame primitives.
|
|
9
|
+
|
|
10
|
+
The package lives in its own repository and uses miniworlds as its rendering
|
|
11
|
+
engine.
|
|
12
|
+
|
|
13
|
+
## Worlds
|
|
14
|
+
|
|
15
|
+
| World | Visualizes | Typical algorithms |
|
|
16
|
+
|--------------|----------------------|--------------------------------------------|
|
|
17
|
+
| `ListWorld` | array of bars | linear/binary search, bubble/selection sort |
|
|
18
|
+
| `StackWorld` | LIFO stack | recursion / call-stack, DFS, undo |
|
|
19
|
+
| `QueueWorld` | FIFO queue | BFS frontier |
|
|
20
|
+
| `TreeWorld` | binary tree | traversals (pre/in/post-order), BST search |
|
|
21
|
+
| `GraphWorld` | graph with edges | BFS, DFS, shortest path |
|
|
22
|
+
|
|
23
|
+
Each world uses the same standardized color language for highlight states
|
|
24
|
+
(`default`, `compare`, `swap`, `sorted`, `pivot`, `visited`, `current`,
|
|
25
|
+
`frontier`, `start`, `target`, `path`).
|
|
26
|
+
|
|
27
|
+
## Stepper
|
|
28
|
+
|
|
29
|
+
Algorithms written as plain loops run inside a single frame, so intermediate
|
|
30
|
+
states are never visible. `Stepper` solves this: the algorithm is written as a
|
|
31
|
+
*generator* that `yield`s once per step, and the stepper advances it one step
|
|
32
|
+
per frame (or on demand).
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from miniworlds_data import ListWorld, Stepper
|
|
36
|
+
|
|
37
|
+
initial = [5, 2, 4, 1, 3]
|
|
38
|
+
world = ListWorld(initial)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def apply_step(step):
|
|
42
|
+
name, (i, j) = step
|
|
43
|
+
world.reset_all()
|
|
44
|
+
if name == "compare":
|
|
45
|
+
world.compare(i, j)
|
|
46
|
+
elif name == "swap":
|
|
47
|
+
world.swap(i, j)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def bubble_sort(data):
|
|
51
|
+
n = data.length
|
|
52
|
+
for i in range(n):
|
|
53
|
+
for j in range(n - i - 1):
|
|
54
|
+
yield "compare", (j, j + 1)
|
|
55
|
+
if data.values[j] > data.values[j + 1]:
|
|
56
|
+
yield "swap", (j, j + 1)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
stepper = Stepper(bubble_sort(world), world, on_step=apply_step)
|
|
60
|
+
stepper.run() # advances one step per frame
|
|
61
|
+
world.run()
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`Stepper` also supports single stepping (`next_step`), going back (`prev_step`),
|
|
65
|
+
`reset`, and `goto`. Pass an `on_reset` callback that restores the initial values
|
|
66
|
+
and highlights to use `reset` or move backward. Recorded steps can be replayed
|
|
67
|
+
after the generator finishes. See [Bubble Sort with the Stepper](examples/03_bubble_sort_stepper.py)
|
|
68
|
+
for an example with an `on_reset` callback.
|
|
69
|
+
|
|
70
|
+
## Example: sorting
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from miniworlds_data import ListWorld
|
|
74
|
+
|
|
75
|
+
world = ListWorld([5, 2, 4, 1, 3])
|
|
76
|
+
world.compare(0, 1)
|
|
77
|
+
world.swap(0, 1)
|
|
78
|
+
world.mark_sorted(0)
|
|
79
|
+
world.run()
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Example: graph pathfinding
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from miniworlds_data import GraphWorld
|
|
86
|
+
|
|
87
|
+
world = GraphWorld()
|
|
88
|
+
a = world.add_node("A", "A", (100, 100))
|
|
89
|
+
b = world.add_node("B", "B", (300, 100))
|
|
90
|
+
c = world.add_node("C", "C", (200, 250))
|
|
91
|
+
world.connect(a, b)
|
|
92
|
+
world.connect(a, c)
|
|
93
|
+
world.connect(b, c)
|
|
94
|
+
world.set_start(a)
|
|
95
|
+
world.set_target(c)
|
|
96
|
+
world.run()
|
|
97
|
+
```
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "miniworlds-data"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Data structure visualization worlds for miniworlds"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"miniworlds",
|
|
13
|
+
]
|
|
14
|
+
authors = [
|
|
15
|
+
{ name = "Andreas Siebel" },
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Intended Audience :: Education",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Programming Language :: Python",
|
|
22
|
+
"Topic :: Education",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
where = ["source"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.package-data]
|
|
29
|
+
miniworlds_data = ["py.typed"]
|
|
@@ -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
|