WMICraft/algorithms/genetic/map_importer_exporter.py

43 lines
1.2 KiB
Python
Raw Normal View History

2022-05-31 01:03:00 +02:00
import json
import random
import string
from datetime import datetime
2022-06-01 19:52:16 +02:00
from pathlib import Path
2022-05-31 01:03:00 +02:00
import numpy
import numpy.typing as npt
from os import listdir
from os.path import isfile, join
# Save map to file
def export_map(grid: npt.NDArray):
json_data = {"map": grid.tolist()}
now = datetime.now()
file_name = "map_" + now.strftime("%Y_%m_%d_%H_%M_%S") + ".json"
2022-06-02 00:52:16 +02:00
path = Path("../../resources/maps/")
file_to_open = path / file_name
2022-05-31 01:03:00 +02:00
2022-06-02 00:52:16 +02:00
with open(file_to_open, "w+") as write_file:
2022-05-31 01:03:00 +02:00
json.dump(json_data, write_file)
print("Saved map to file " + file_name)
def import_random_map() -> object:
path = "resources/maps"
files = [f for f in listdir(path) if isfile(join(path, f))]
random_map_name = random.choice(files)
return import_map(random_map_name)
# Read map from file
2022-06-01 19:52:16 +02:00
def import_map(file_name: string) -> object:
2022-06-02 00:52:16 +02:00
file_to_open = "resources/maps/" + file_name
2022-06-01 19:52:16 +02:00
with open(file_to_open, "r") as read_file:
print("Reading map from file " + file_name)
2022-05-31 01:03:00 +02:00
decoded_json = json.load(read_file)
decoded_grid = numpy.asarray(decoded_json["map"])
print(decoded_grid)
return decoded_grid.tolist()