pgfw/pgfw/GameChild.py

95 lines
2.9 KiB
Python

from os.path import exists, join, basename, normpath, abspath, commonprefix, sep
from sys import argv, version_info
from pygame import mixer, event, time
from pygame.locals import *
if version_info[0] >= 3:
from . import Game
else:
import Game
class GameChild:
def __init__(self, parent=None):
self.parent = parent
self.game = self.get_game()
def get_game(self):
current = self
while not isinstance(current, Game.Game):
current = current.parent
return current
def get_configuration(self, section=None, option=None, linebreaks=True):
config = self.game.configuration
if option is None and section is None:
return config
elif option and section:
if config.has_option(section, option):
rvalue = config.get(section, option)
if not linebreaks and isinstance(rvalue, str):
rvalue = rvalue.replace("\n", " ")
return rvalue
elif option is None:
if config.has_section(section):
return config.get_section(section)
else:
return {}
def get_input(self):
return self.game.input
def get_screen(self):
return self.game.display.get_screen()
def get_display_surface(self):
current = self
attribute = "display_surface"
while not isinstance(current, Game.Game):
if hasattr(current, attribute):
return getattr(current, attribute)
current = current.parent
return current.display.get_screen()
def get_audio(self):
return self.game.audio
def get_delegate(self):
return self.game.delegate
def get_resource(self, path_or_section, option=None):
config = self.get_configuration()
rel_path = path_or_section
if option is not None:
rel_path = config.get(path_or_section, option)
if rel_path:
for root in config.get("setup", "resource-search-path"):
if self.is_shared_mode() and not self.is_absolute_path(root):
continue
path = join(root, rel_path)
if exists(path):
return normpath(path)
def is_shared_mode(self):
return self.check_command_line("s")
def check_command_line(self, flag):
return "-" + flag in argv
def print_debug(self, statement):
if self.is_debug_mode():
print(statement)
def is_debug_mode(self):
return self.check_command_line("d")
def is_absolute_path(self, path):
return normpath(path) == abspath(path)
def subscribe(self, callback, kind=None):
self.game.delegate.add_subscriber(callback, kind)
def unsubscribe(self, callback, kind=None):
self.game.delegate.remove_subscriber(callback, kind)