forked from ROBOT-IS-CHILL/robot-is-chill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert-json.py
78 lines (67 loc) · 2.99 KB
/
convert-json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import json
import tomlkit
import glob
from pathlib import Path
def try_convert(value: str | int | list[str]) -> str | int | list[int]:
if type(value) is str:
try:
return int(value)
except:
pass
if type(value) is list:
return [try_convert(element) for element in value]
return value
def main():
for path in glob.glob("data/custom/*.json"):
path = Path(path)
print(f"Converting {path} to .toml...")
with open(path, "r") as file:
arr: list[dict] = json.load(file)
print(f" Read {len(arr)} objects.")
tiles = tomlkit.document()
tiles.add(tomlkit.comment("----------------------------------------------------------------------------"))
tiles.add(tomlkit.comment(""))
tiles.add(tomlkit.comment(""))
tiles.add(tomlkit.comment(" File autogenerated by convert-json.py. Feel free to edit."))
tiles.add(tomlkit.comment(""))
tiles.add(tomlkit.comment(" Tile format:"))
tiles.add(tomlkit.comment(' baba = { sprite = "baba", color = [ 0, 3 ], tiling = 2 } '))
tiles.add(tomlkit.comment(' Please do not use multiline tables, as it will cause merge conflicts with Git. '))
tiles.add(tomlkit.comment(""))
tiles.add(tomlkit.comment(" Note: If your tile has tiling type 1,"))
tiles.add(tomlkit.comment(' you must add the "diagonal = true/false" attribute to the tile'))
tiles.add(tomlkit.comment(' in order for it to pass CI.'))
tiles.add(tomlkit.comment(' For example, "line" = { ..., diagonal = false }. '))
tiles.add(tomlkit.comment(""))
tiles.add(tomlkit.comment(""))
tiles.add(tomlkit.comment("----------------------------------------------------------------------------"))
tiles.add(tomlkit.nl())
tiles.add(tomlkit.nl())
tiles.add(tomlkit.nl())
for tile in arr:
name = tile.pop("name")
if name in tiles: continue
for key, value in tile.items():
tile[key] = try_convert(value)
if "tags" in tile:
tags: str = tile["tags"]
tile["tags"] = tags.split("\t")
# text_anni
if "tiling" not in tile:
tile["tiling"] = -1
if tile["tiling"] == 1:
# Check if diagtiling, and if it is, add a flag for it
sprite = tile["sprite"]
sprite_path = Path("data/sprites") / path.stem / f"{sprite}_16_1.png"
tile["diagonal"] = sprite_path.exists()
table = tomlkit.inline_table()
table.update(tile)
tiles.add(name, table)
tiles.add(tomlkit.nl())
toml_path = path.with_suffix(".toml")
with open(toml_path, "w+") as file:
tomlkit.dump(tiles, file)
print(f" Wrote file to {toml_path}.")
print("Done.")
if __name__ == "__main__":
main()