WTS/game/scripts/utility/actions.rpy
2024-05-03 22:20:51 +01:00

100 lines
3.0 KiB
Plaintext

init python:
class SetShopCategory(Action):
def __init__(self, category: str, items: list):
self.category = category
self.items = items
def __call__(self):
cs = renpy.current_screen()
if cs is None:
raise Exception("No current screen.")
items = self.items
scope = cs.scope
scope["shop_items"] = items
scope["selected_category"] = self.category
scope["selected_item"] = items[0] if items else None
renpy.restart_interaction()
class CycleShopCategory(Action):
def __init__(self, screenvar: str, items: dict, reverse=False):
self.screenvar = screenvar
self.items = items
self.reverse = reverse
def __call__(self):
cs = renpy.current_screen()
if cs is None:
raise Exception("No current screen.")
scope = cs.scope
var = self.screenvar
current = scope[var]
keys_list = list(self.items.keys())
try:
current_index = keys_list.index(current)
except ValueError:
current_index = -1
step = -1 if self.reverse else 1
next_index = (current_index + step) % len(keys_list)
next_key = keys_list[next_index]
scope[var] = next_key
SetShopCategory(next_key, self.items[next_key])()
class SortFilter(Action):
def __init__(self, screenvar: str, sort_keys=None, filter_keys=None):
self.screenvar = screenvar
self.filter_keys = filter_keys
self.sort_keys = sort_keys
def __call__(self):
cs = renpy.current_screen()
if cs is None:
raise Exception("No current screen.")
scope = cs.scope
var = self.screenvar
if var not in scope:
raise Exception("Screen var is missing.")
items = scope[var]
if self.filter_keys:
items = self.filter(items, self.filter_keys)
if self.sort_keys:
items = self.sort(items, self.sort_keys)
scope[var] = items
renpy.restart_interaction()
@staticmethod
def filter(items, keys):
for key in keys:
if key.startswith("not "):
attr = key[4:]
items = filter(lambda x: not getattr(x, attr), items)
else:
items = filter(lambda x: getattr(x, key), items)
return items
@staticmethod
def sort(items, keys):
for key in keys:
items = sorted(items, key=lambda x: SortFilter.natsort(getattr(x, key)))
return items
@staticmethod
def natsort(s, pattern=re.compile("([0-9]+)")):
return [int(t) if t.isdigit() else t.lower() for t in pattern.split(str(s))]