This repository was archived by the owner on Apr 20, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathutils.py
108 lines (82 loc) · 2.76 KB
/
utils.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import math
from functools import lru_cache
from pathlib import Path
from random import uniform
import pygame
from wclib.constants import SIZE, ROOT_DIR
__all__ = [
"SIZE",
"SUBMISSION_DIR",
"ASSETS",
"SCREEN",
"load_image",
"rotate_image",
"clamp",
"random_in_rect",
"from_polar",
"clamp_vector",
"text",
]
SUBMISSION_DIR = Path(__file__).parent
ASSETS = SUBMISSION_DIR.parent / "assets"
SCREEN = pygame.Rect(0, 0, *SIZE)
@lru_cache()
def load_image(name: str, scale=1, alpha=True):
"""Load a image from the disk and caches the results."""
image = pygame.image.load(ASSETS / f"{name}.png")
if scale != 1:
new_size = image.get_width() * scale, image.get_height() * scale
image = pygame.transform.scale(image, new_size)
if alpha:
return image.convert_alpha()
else:
return image.convert()
@lru_cache()
def rotate_image(surf, angle: int):
"""Rotate function that caches its results for performance."""
return pygame.transform.rotate(surf, angle)
def clamp(value, mini, maxi):
"""Clamp value between mini and maxi"""
if value < mini:
return mini
elif maxi < value:
return maxi
else:
return value
def random_in_rect(rect):
"""Return a random point uniformly in a rectangle."""
rect = pygame.Rect(rect)
return pygame.Vector2(uniform(rect.left, rect.right), uniform(rect.top, rect.bottom))
def from_polar(rho, theta):
"""Create a Vector2 from its polar representation."""
v = pygame.Vector2()
v.from_polar((rho, theta))
return v
def clamp_vector(v: pygame.Vector2, max_length):
"""Ensure that a vector has a magnitude less than max_length."""
if v.length() > max_length:
return v.normalize() * max_length
return v
@lru_cache()
def font(size=20, name=None):
"""
Load a font from its name in the wclib/assets folder.
If a Path object is given as the name, this path will be used instead.
Results are cached.
"""
name = name or "regular"
if isinstance(name, Path):
path = name
else:
path = ROOT_DIR / "wclib" / "assets" / (name + ".ttf")
return pygame.font.Font(path, size)
@lru_cache(5000)
def text(txt, color, size=20, font_name=None):
"""Render a text on a surface. Results are cached."""
return font(size, font_name).render(str(txt), True, color)
def distance(p1, p2):
"""Get distance between 2 points"""
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
def map_to_range(value, from_x, from_y, to_x, to_y):
"""map the value from one range to another"""
return clamp(value * (to_y - to_x) / (from_y - from_x), to_x, to_y)