forked from cmot17/CustomKnight-Creator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSprite.py
More file actions
94 lines (78 loc) · 2.17 KB
/
Sprite.py
File metadata and controls
94 lines (78 loc) · 2.17 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
87
88
89
90
91
92
93
94
"""
This module implements a Sprite object for storing position data for, and the
content-based hash of, a single image/sprite.
"""
from dataclasses import dataclass
from pathlib import Path
from PIL import Image
from typing import Optional
@dataclass
class Sprite:
"""
The Sprite class stores details of the position and orientation of a sprite
within a CustomKnight spritesheet. Sprite objects also track the state of
the underlying sprite image file, updating the sprite content and hash
when the file has been modified.
"""
identifier: int
x: int
y: int
xr: int
yr: int
w: int
h: int
flipped: bool
path: Path
collection: str
mtime: Optional[float] = None
def __update_file(self) -> None:
"""
Checks if the source image has been modified, and recomputes the
cropped sprite content and resulting image hash if so.
Returns
-------
None.
"""
mtime: float = self.path.stat().st_mtime
if mtime == self.mtime:
return
self.mtime = mtime
im = Image.open(self.path)
w = im.size[1]
self.__content = im.crop(
(self.xr, w - self.yr - self.h, self.xr + self.w, w - self.yr)
)
self.__hash = hash(tuple(map(tuple, self.__content.getdata())))
@property
def image_hash(self) -> int:
"""
Getter for the image hash of the sprite content in the image file.
Returns
-------
int
The current hash.
"""
self.__update_file()
return self.__hash
@property
def content(self) -> Image.Image:
"""
Getter for the sprite content of the image file.
Returns
-------
Image
A PIL image with the underlying image file, cropped to the sprite
borders.
"""
self.__update_file()
return self.__content
@property
def animation(self) -> str:
"""
Returns the name of the animation the sprite is in.
Returns
-------
str
The animation name.
"""
return self.path.parent.name