-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathutil.py
More file actions
86 lines (65 loc) · 2.75 KB
/
util.py
File metadata and controls
86 lines (65 loc) · 2.75 KB
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
79
80
81
82
83
84
85
86
"""Utility Functions for PyTiled"""
import json
import xml.etree.ElementTree as etree
from pathlib import Path
from typing import Any
from pytiled_parser.common_types import Color
def parse_color(color: str) -> Color:
"""Convert Tiled color format into PyTiled's.
Tiled's color format is #AARRGGBB and PyTiled's is an RGBA tuple.
Args:
color (str): Tiled formatted color string.
Returns:
:Color: Color object in the format that PyTiled understands.
"""
# the actual part we care about is always an even number
if len(color) % 2:
# strip initial '#' character
color = color[1:]
if len(color) == 6:
# full opacity if no alpha specified
return Color(int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16), 255)
elif len(color) == 8:
return Color(
int(color[2:4], 16),
int(color[4:6], 16),
int(color[6:8], 16),
int(color[0:2], 16),
)
raise ValueError("Improperly formatted color passed to parse_color")
def check_format(file_path: Path, encoding: str) -> str:
with open(file_path, encoding=encoding) as file:
line = file.readline().rstrip().strip()
if line[0] == "<":
return "tmx"
else:
return "json"
def load_object_template(file_path: Path, encoding: str) -> Any:
template_format = check_format(file_path, encoding)
new_tileset = None
new_tileset_path = None
if template_format == "tmx":
with open(file_path, encoding=encoding) as template_file:
template = etree.parse(template_file).getroot()
tileset_element = template.find("./tileset")
if tileset_element is not None:
tileset_path = Path(file_path.parent / tileset_element.attrib["source"])
new_tileset = load_object_tileset(tileset_path, encoding)
new_tileset_path = tileset_path.parent
else:
with open(file_path, encoding=encoding) as template_file:
template = json.load(template_file)
if "tileset" in template:
tileset_path = Path(file_path.parent / template["tileset"]["source"]) # type: ignore
new_tileset = load_object_tileset(tileset_path, encoding)
new_tileset_path = tileset_path.parent
return (template, new_tileset, new_tileset_path)
def load_object_tileset(file_path: Path, encoding: str) -> Any:
tileset_format = check_format(file_path, encoding)
new_tileset = None
with open(file_path, encoding=encoding) as tileset_file:
if tileset_format == "tmx":
new_tileset = etree.parse(tileset_file).getroot()
else:
new_tileset = json.load(tileset_file)
return new_tileset