-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
82 lines (65 loc) · 2.46 KB
/
utilities.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
import pygame
import sys
import os
import gamestate
import fnmatch
from pathlib import Path
if not pygame.get_init():
pygame.init()
current_path = ""
if getattr(sys, 'frozen', False): # PyInstaller adds this attribute
# running in a bundle
current_path = sys._MEIPASS
else:
# running in normal python environment
current_path = os.path.dirname(__file__)
def get_filenames(*path, filetype="png"):
filenames = []
for file in os.listdir(os.path.join(current_path, os.path.join(*path))):
if fnmatch.fnmatch(file, "*." + filetype):
filenames.append(Path(file).stem)
return filenames
def load_image(name, *subfolders, filetype="png"):
"""Load image and return image object"""
if subfolders:
fullname = os.path.join(current_path, "images",
os.path.join(*subfolders),
name + os.extsep + filetype)
else:
fullname = os.path.join(current_path, "images",
name + os.extsep + filetype)
try:
image = pygame.image.load(fullname)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
return image
except FileNotFoundError:
print(f"Cannot find image file at {fullname}")
def load_audio(name, *subfolders, filetype="mp3"):
"""Load audio and return pygame.mixer.Sound object"""
if subfolders:
fullname = os.path.join(current_path, "audio",
os.path.join(*subfolders),
name + os.extsep + filetype)
else:
fullname = os.path.join(current_path, "audio",
name + os.extsep + filetype)
try:
audio = pygame.mixer.Sound(fullname)
return audio
except FileNotFoundError:
print(f"Cannot find audio file at {fullname}")
def load_font(name, size, align=pygame.FONT_LEFT, filetype="ttf"):
"""Load font and return font object"""
if name:
font = pygame.font.Font(os.path.join(current_path, "fonts", name + os.extsep + filetype), size)
else:
font = pygame.font.Font(None, size)
font.align = align
return font
def render_text(string, font, color, surface, **kwargs):
"""Render string in colored font on surface, and position it according to keyword arguments."""
text = font.render(string, False, color)
surface.blit(text, text.get_rect(**kwargs))