forked from cmot17/CustomKnight-Creator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
88 lines (67 loc) · 2.03 KB
/
util.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
79
80
81
82
83
84
85
86
87
88
"""
This module provides miscellaneous utility functions for CustomKnight Creator.
"""
from math import ceil, log2
from typing import Callable, Hashable, Iterable, TypeVar, cast
T = TypeVar("T")
U = TypeVar("U")
def lunique(seq: Iterable[Hashable]) -> list[Hashable]:
"""
Returns a list of unique elements of an iterable, respecting the original
element order.
Parameters
----------
seq : Iterable[Hashable]
The sequence to trim duplicate elements from.
Returns
-------
list[Hashable]
A stably-ordered list of unique elements of `seq`.
"""
return list(dict.fromkeys(seq))
def lmap(func: Callable[[T], U], seq: Iterable[T]) -> list[U]:
"""
Returns a list with the results of a function map.
Parameters
----------
func : Callable[[T], U]
The function to map.
seq : Iterable[T]
The sequence of arguments to pass to `func`.
Returns
-------
list[U]
A list containing the result of `func` called on each successive
element in `seq`.
"""
return list(map(func, seq))
def first(seq: Iterable[T], condition: Callable[[T], bool] = lambda x: True) -> T:
"""
Returns the first element of an iterable satisfying an optional condition
function.
Parameters
----------
seq : Iterable[T]
A sequence of objects.
condition : Callable[[T], bool], optional
A function that returns whether an element is valid to be chosen. The
default is lambda x: True.
Returns
-------
T
The first element in `seq` for which `condition` returns True.
"""
return next(x for x in seq if condition(x))
def min_dimension(l: int) -> int:
"""
Returns the spritesheet dimension needed to accommodate a given length.
Parameters
----------
l : int
The length, along a given dimension, of the packed sprites.
Returns
-------
int
The appropriate spritesheet dimension to fit the sprites.
"""
return cast(int, 2 ** ceil(log2(l - 1)))