added basic save/load

This commit is contained in:
Louis Heredero 2024-07-01 23:25:47 +02:00
parent 5d99a0d2c5
commit efc88658ee
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
2 changed files with 42 additions and 8 deletions

View File

@ -103,6 +103,10 @@ class Editor:
self.zoom_out() self.zoom_out()
elif event.key == pygame.K_BACKSPACE: elif event.key == pygame.K_BACKSPACE:
self.deleted_selected_objects() self.deleted_selected_objects()
elif event.key == pygame.K_s and event.mod & (pygame.KMOD_CTRL | pygame.KMOD_META):
self.graph.save(input("Save as: "))
elif event.key == pygame.K_l and event.mod & (pygame.KMOD_CTRL | pygame.KMOD_META):
self.graph = Graph.load(input("Load from: "))
elif event.key == pygame.K_RETURN: elif event.key == pygame.K_RETURN:
if len(self.selected_nodes) > 0: if len(self.selected_nodes) > 0:
self.typing_text = "" if len(self.selected_nodes) > 1 else self.graph.nodes[self.selected_nodes[0]].name self.typing_text = "" if len(self.selected_nodes) > 1 else self.graph.nodes[self.selected_nodes[0]].name

View File

@ -1,9 +1,11 @@
from __future__ import annotations
from math import inf from math import inf
from typing import Iterator, Optional from typing import Iterator, Optional
from src.graph.node import Node from src.graph.node import Node
from src.graph.edge import Edge from src.graph.edge import Edge
class Graph: class Graph:
def __init__(self): def __init__(self):
self.edges: list[Edge] = [] self.edges: list[Edge] = []
@ -95,3 +97,31 @@ class Graph:
node_sequences[end].append(end) node_sequences[end].append(end)
return node_sequences[target_index] return node_sequences[target_index]
def save(self, path: str) -> None:
with open(path, "w") as f:
for node in self.nodes:
f.write(f"n {node.x} {node.z} {node.name}\n")
f.write("\n")
for edge in self.edges:
f.write(f"e {edge.start} {edge.end} {edge.length}\n")
@staticmethod
def load(path: str) -> Graph:
graph = Graph()
with open(path, "r") as f:
lines = f.read().splitlines()
for line in lines:
if len(line.strip()) == 0:
continue
entry_type, values = line.split(" ", 1)
if entry_type == "n":
x, z, name = values.split(" ", 2)
x, z = int(x), int(z)
graph.add_node(x, z, name)
elif entry_type == "e":
start, end, length = values.split(" ", 2)
start, end, length = int(start), int(end), float(length)
graph.add_edge(start, end, length)
return graph