Core System

The core module provides the fundamental game engine components including the event system, game loop, state management, and save/load functionality.

Game Engine

Core game engine and state management.

This module provides the main Game class that manages the game loop, state, and coordinates all systems.

class barebones_rpg.core.game.GameState(value)[source]

Bases: Enum

Possible game states.

MENU = 1
PLAYING = 2
COMBAT = 3
DIALOG = 4
PAUSED = 5
GAME_OVER = 6
class barebones_rpg.core.game.GameConfig(title='Barebones RPG', screen_width=800, screen_height=600, fps=60, auto_save=True, debug_mode=False, save_directory='saves', extra=<factory>)[source]

Bases: object

Configuration for the game.

This can be extended by users to add their own config options.

title: str = 'Barebones RPG'
screen_width: int = 800
screen_height: int = 600
fps: int = 60
auto_save: bool = True
debug_mode: bool = False
save_directory: str = 'saves'
extra: Dict[str, Any]
__init__(title='Barebones RPG', screen_width=800, screen_height=600, fps=60, auto_save=True, debug_mode=False, save_directory='saves', extra=<factory>)
class barebones_rpg.core.game.Game(config=None)[source]

Bases: object

Main game engine that manages the game loop and state.

The Game class is the central hub that coordinates all game systems. It manages the game loop, state transitions, and provides access to all major systems (entities, world, combat, etc.).

Example

>>> game = Game(GameConfig(title="My RPG"))
>>> game.events.subscribe(EventType.GAME_START, lambda e: print("Game started!"))
>>> game.start()
>>> game.run()  # Start the game loop
__init__(config=None)[source]

Initialize the game.

Parameters:

config (Optional[GameConfig]) – Game configuration. Uses defaults if not provided.

register_system(name, system)[source]

Register a game system (combat, world, etc.).

Parameters:
  • name (str) – Name of the system (e.g., “combat”, “world”)

  • system (Any) – The system instance

Return type:

None

get_system(name)[source]

Get a registered system by name.

Parameters:

name (str) – Name of the system

Return type:

Any

Returns:

The system instance or None if not found

register_entity(entity)[source]

Register an entity for saving/loading.

Parameters:

entity (Any) – Entity to register

Return type:

None

register_item(item)[source]

Register an item for saving/loading.

Parameters:

item (Any) – Item to register

Return type:

None

register_party(party)[source]

Register a party for saving/loading.

Parameters:

party (Any) – Party to register

Return type:

None

register_quest(quest)[source]

Register a quest for saving/loading.

Deprecated since version Use: QuestManager().add_quest(quest) instead. QuestManager is the single source of truth for quests.

Parameters:

quest (Any) – Quest to register

Return type:

None

get_entity(entity_id)[source]

Get a registered entity by ID.

Parameters:

entity_id (str) – Entity ID

Return type:

Any

Returns:

Entity or None if not found

get_item(item_id)[source]

Get a registered item by ID.

Parameters:

item_id (str) – Item ID

Return type:

Any

Returns:

Item or None if not found

get_party(party_name)[source]

Get a registered party by name.

Parameters:

party_name (str) – Party name

Return type:

Any

Returns:

Party or None if not found

get_quest(quest_id)[source]

Get a registered quest by ID.

Parameters:

quest_id (str) – Quest ID

Return type:

Any

Returns:

Quest or None if not found

property quests: QuestManager

Access the quest manager singleton.

Returns:

The QuestManager singleton instance

Example

>>> game = Game()
>>> quest = Quest(name="Save the Village")
>>> game.quests.start_quest(quest.id)
start()[source]

Start the game and initialize all systems.

Return type:

None

stop()[source]

Stop the game.

Return type:

None

pause()[source]

Pause the game.

Return type:

None

resume()[source]

Resume the game from pause.

Return type:

None

change_state(new_state)[source]

Change the game state.

Parameters:

new_state (GameState) – The new state to transition to

Return type:

None

update(delta_time)[source]

Update game logic.

This is called every frame by the game loop.

Parameters:

delta_time (float) – Time elapsed since last frame (in seconds)

Return type:

None

handle_input(input_data)[source]

Handle player input.

Parameters:

input_data (Any) – Input data (will be pygame events in the rendering layer)

Return type:

None

save_game(save_name='default')[source]

Save the current game state.

Parameters:

save_name (str) – Name of the save file

Return type:

Dict[str, Any]

Returns:

Dictionary containing the game state

load_game(save_data)[source]

Load a saved game state.

Parameters:

save_data (Dict[str, Any]) – Dictionary containing the saved game state

Return type:

None

save_to_file(save_name='default')[source]

Save the game to a file.

Parameters:

save_name (str) – Name of the save file

Return type:

bool

Returns:

True if save was successful

Raises:

SerializationError – If the save data cannot be serialized or written

Example

>>> game.save_to_file("quicksave")
load_from_file(save_name)[source]

Load the game from a file.

Parameters:

save_name (str) – Name of the save file to load

Return type:

bool

Returns:

True if load was successful

Raises:

SerializationError – If the save file is corrupted or unreadable

Example

>>> game.load_from_file("quicksave")
list_saves()[source]

List all available save files.

Return type:

List[str]

Returns:

List of save names

delete_save(save_name)[source]

Delete a save file.

Parameters:

save_name (str) – Name of the save to delete

Return type:

bool

Returns:

True if deletion was successful

Event System

Event system for the RPG framework.

This module provides a flexible publish-subscribe event system that allows different parts of the game to communicate without tight coupling.

class barebones_rpg.core.events.EventType(value)[source]

Bases: Enum

Built-in event types. Users can extend this or use custom strings.

GAME_START = 1
GAME_END = 2
GAME_PAUSE = 3
GAME_RESUME = 4
COMBAT_START = 5
COMBAT_END = 6
COMBAT_TURN_START = 7
COMBAT_TURN_END = 8
ATTACK = 9
DAMAGE_DEALT = 10
DAMAGE_TAKEN = 11
HEAL = 12
DEATH = 13
ENTITY_CREATED = 14
ENTITY_DESTROYED = 15
STAT_CHANGED = 16
LEVEL_UP = 17
ITEM_ACQUIRED = 18
ITEM_USED = 19
ITEM_DROPPED = 20
ITEM_EQUIPPED = 21
ITEM_UNEQUIPPED = 22
QUEST_STARTED = 23
QUEST_COMPLETED = 24
QUEST_FAILED = 25
OBJECTIVE_COMPLETED = 26
LOCATION_ENTERED = 27
LOCATION_EXITED = 28
DOOR_OPENED = 29
CHEST_OPENED = 30
DIALOG_STARTED = 31
DIALOG_ENDED = 32
CHOICE_MADE = 33
class barebones_rpg.core.events.Event(event_type, data=None)[source]

Bases: object

Base event class that carries event data.

event_type: EventType | str
data: Optional[Dict[str, Any]] = None
__init__(event_type, data=None)
class barebones_rpg.core.events.EventManager[source]

Bases: object

Central event manager for publish-subscribe pattern.

This allows different parts of the game to communicate without tight coupling. Components can subscribe to events and publish events without knowing about each other.

Example

>>> events = EventManager()
>>> def on_damage(event):
...     print(f"Damage dealt: {event.data['amount']}")
>>> events.subscribe(EventType.DAMAGE_DEALT, on_damage)
>>> events.publish(Event(EventType.DAMAGE_DEALT, {"amount": 10}))
Damage dealt: 10
__init__()[source]
subscribe(event_type, callback)[source]

Subscribe a callback function to an event type.

Parameters:
  • event_type (EventType | str) – The type of event to listen for

  • callback (Callable[[Event], None]) – Function to call when event is published. Takes Event as argument.

Return type:

None

unsubscribe(event_type, callback)[source]

Unsubscribe a callback from an event type.

Parameters:
  • event_type (EventType | str) – The type of event to stop listening for

  • callback (Callable[[Event], None]) – The callback function to remove

Return type:

None

publish(event)[source]

Publish an event to all subscribers.

Parameters:

event (Event) – The event to publish

Return type:

None

enable_history()[source]

Enable recording of all published events.

Return type:

None

disable_history()[source]

Disable recording of events.

Return type:

None

get_history()[source]

Get the history of all published events.

Return type:

List[Event]

clear_history()[source]

Clear the event history.

Return type:

None

clear_all_subscribers()[source]

Remove all event subscribers. Useful for cleanup.

Return type:

None

Save Manager

Save manager for handling game save/load operations.

This module provides the SaveManager class for managing game saves, including JSON serialization, file I/O, and directory management.

class barebones_rpg.core.save_manager.SaveManager(save_directory)[source]

Bases: object

Manager for saving and loading game state.

Handles JSON serialization, file I/O, directory creation, and versioning.

Example

>>> manager = SaveManager("saves")
>>> save_data = {"player": {"name": "Hero", "level": 5}}
>>> manager.save("my_save", save_data)
>>> loaded = manager.load("my_save")
>>> print(loaded["player"]["name"])
Hero
SAVE_VERSION = '1.0.0'
__init__(save_directory)[source]

Initialize the save manager.

Parameters:

save_directory (str) – Directory path for save files (absolute or relative)

save(save_name, save_data)[source]

Save game data to a file.

Parameters:
  • save_name (str) – Name of the save

  • save_data (Dict[str, Any]) – Dictionary containing game state

Return type:

bool

Returns:

True if save was successful

Example

>>> manager.save("quicksave", game_state)
load(save_name)[source]

Load game data from a file.

Parameters:

save_name (str) – Name of the save to load

Return type:

Optional[Dict[str, Any]]

Returns:

Dictionary containing game state, or None if load failed

Example

>>> data = manager.load("quicksave")
delete(save_name)[source]

Delete a save file.

Parameters:

save_name (str) – Name of the save to delete

Return type:

bool

Returns:

True if deletion was successful

list_saves()[source]

List all available save files.

Return type:

List[str]

Returns:

List of save names

Example

>>> saves = manager.list_saves()
>>> print(saves)
['quicksave', 'autosave', 'manual_save_1']
get_save_info(save_name)[source]

Get metadata about a save file.

Parameters:

save_name (str) – Name of the save

Return type:

Optional[Dict[str, Any]]

Returns:

Dictionary with save metadata (version, timestamp, etc.)

exists(save_name)[source]

Check if a save file exists.

Parameters:

save_name (str) – Name of the save

Return type:

bool

Returns:

True if save exists

Serialization

Serialization utilities for save/load system.

This module provides utilities for serializing game state, including a callback registry for handling function references in saved data.

class barebones_rpg.core.serialization.CallbackRegistry[source]

Bases: object

Registry for mapping callback functions to symbolic names.

This enables serialization of callbacks by storing symbolic names instead of function references. When loading, the registry is used to restore the actual function references.

Example

>>> def heal_player(entity, context):
...     entity.heal(50)
>>>
>>> CallbackRegistry.register("heal_player", heal_player)
>>> key = CallbackRegistry.encode(heal_player)
>>> print(key)
'heal_player'
>>>
>>> restored = CallbackRegistry.decode(key)
>>> restored is heal_player
True
classmethod register(name, callback)[source]

Register a callback with a symbolic name.

Parameters:
  • name (str) – Symbolic name for the callback

  • callback (Callable) – The callback function to register

Return type:

None

Example

>>> CallbackRegistry.register("my_callback", my_function)
classmethod get(name)[source]

Get a callback by name.

Parameters:

name (str) – Name of the callback

Return type:

Optional[Callable]

Returns:

The callback function or None if not found

classmethod has(name)[source]

Check if a callback is registered.

Parameters:

name (str) – Name to check

Return type:

bool

Returns:

True if callback is registered

classmethod encode(callback)[source]

Encode a callback to its symbolic name.

Parameters:

callback (Optional[Callable]) – The callback function to encode

Return type:

Optional[str]

Returns:

Symbolic name or None if callback is None or not registered

Example

>>> key = CallbackRegistry.encode(my_function)
classmethod decode(name)[source]

Decode a symbolic name back to a callback.

Parameters:

name (Optional[str]) – Symbolic name of the callback

Return type:

Optional[Callable]

Returns:

The callback function or None if not found

Example

>>> callback = CallbackRegistry.decode("my_callback")
classmethod clear()[source]

Clear all registered callbacks.

This is primarily for testing purposes.

Return type:

None

classmethod get_all_names()[source]

Get all registered callback names.

Return type:

List[str]

Returns:

List of callback names

classmethod auto_register_from_module(module_name, prefix='')[source]

Auto-register all functions from a module.

This is a convenience method for bulk registration.

Parameters:
  • module_name (str) – Name of the module to import

  • prefix (str) – Optional prefix for registered names

Return type:

int

Returns:

Number of functions registered

Example

>>> CallbackRegistry.auto_register_from_module("my_game.callbacks")
barebones_rpg.core.serialization.serialize_callback(callback)[source]

Serialize a callback to a string key.

This is a convenience wrapper around CallbackRegistry.encode().

Parameters:

callback (Optional[Callable]) – Callback to serialize

Return type:

Optional[str]

Returns:

String key or None

barebones_rpg.core.serialization.deserialize_callback(key)[source]

Deserialize a callback from a string key.

This is a convenience wrapper around CallbackRegistry.decode().

Parameters:

key (Optional[str]) – String key to deserialize

Return type:

Optional[Callable]

Returns:

Callback function or None

barebones_rpg.core.serialization.serialize_callbacks(callbacks)[source]

Serialize a list of callbacks.

Parameters:

callbacks (Optional[List[Callable]]) – List of callbacks to serialize

Return type:

List[str]

Returns:

List of string keys (skips None values)

barebones_rpg.core.serialization.deserialize_callbacks(keys)[source]

Deserialize a list of callbacks.

Parameters:

keys (Optional[List[str]]) – List of string keys

Return type:

List[Callable]

Returns:

List of callback functions (skips unresolved keys)

barebones_rpg.core.serialization.encode_enum(enum_value)[source]

Encode an enum value to a string.

Parameters:

enum_value (Any) – Enum value to encode

Return type:

str

Returns:

String representation (enum.name)

barebones_rpg.core.serialization.decode_enum(enum_class, value)[source]

Decode a string to an enum value.

Parameters:
  • enum_class (Type[Enum]) – The enum class

  • value (str) – String name of the enum value

Return type:

Any

Returns:

Enum value

class barebones_rpg.core.serialization.SerializationContext[source]

Bases: object

Context for serialization operations.

This can be used to pass additional context during serialization, such as entity lookups, custom serializers, etc.

__init__()[source]
register_entity(entity)[source]

Register an entity for lookup during deserialization.

Parameters:

entity (Any) – Entity to register

Return type:

None

register_item(item)[source]

Register an item for lookup during deserialization.

Parameters:

item (Any) – Item to register

Return type:

None

get_entity(entity_id)[source]

Get an entity by ID.

Parameters:

entity_id (str) – Entity ID

Return type:

Optional[Any]

Returns:

Entity or None if not found

get_item(item_id)[source]

Get an item by ID.

Parameters:

item_id (str) – Item ID

Return type:

Optional[Any]

Returns:

Item or None if not found

Registry System

Generic registry base class for framework registries.

This module provides a reusable registry pattern used throughout the framework for managing collections of named objects (AI types, loot items, callbacks, etc.).

class barebones_rpg.core.registry.Registry[source]

Bases: Generic[T]

Base class for type-safe registries.

Provides a common interface for registering and retrieving named objects. Subclasses should define their own _registry class variable to maintain separate storage.

Example

>>> class MyItemRegistry(Registry[Item]):
...     _registry: Dict[str, Item] = {}
>>>
>>> item = Item(name="Sword")
>>> MyItemRegistry.register("sword", item)
>>> retrieved = MyItemRegistry.get("sword")
>>> assert retrieved is item
classmethod register(name, item)[source]

Register an item with a name.

Parameters:
  • name (str) – Unique name for the item

  • item (TypeVar(T)) – Item to register

Return type:

None

Example

>>> Registry.register("my_item", my_item)
classmethod get(name)[source]

Get an item by name.

Parameters:

name (str) – Name of the item to retrieve

Return type:

Optional[TypeVar(T)]

Returns:

The registered item or None if not found

Example

>>> item = Registry.get("my_item")
classmethod has(name)[source]

Check if an item is registered.

Parameters:

name (str) – Name to check

Return type:

bool

Returns:

True if the item is registered

Example

>>> if Registry.has("my_item"):
...     print("Item exists")
classmethod get_all_names()[source]

Get all registered names.

Return type:

List[str]

Returns:

List of all registered names

Example

>>> names = Registry.get_all_names()
>>> print(names)
['item1', 'item2', 'item3']
classmethod get_all()[source]

Get all registered items.

Return type:

Dict[str, TypeVar(T)]

Returns:

Dictionary of all registered items

Example

>>> items = Registry.get_all()
>>> for name, item in items.items():
...     print(f"{name}: {item}")
classmethod clear()[source]

Clear all registered items.

This is primarily for testing purposes.

Example

>>> Registry.clear()
Return type:

None

Singleton Pattern

Singleton metaclass for framework systems.

This module provides a singleton pattern implementation for framework-managed systems like QuestManager, ensuring only one instance exists.

class barebones_rpg.core.singleton.Singleton[source]

Bases: type

Metaclass that implements the singleton pattern.

Ensures only one instance of a class exists. Subsequent calls to create an instance return the existing instance.

Example

>>> class MySystem(metaclass=Singleton):
...     def __init__(self):
...         self.data = []
>>>
>>> instance1 = MySystem()
>>> instance2 = MySystem()
>>> instance1 is instance2
True
__call__(*args, **kwargs)[source]

Create or return existing instance.

Parameters:
  • *args – Positional arguments for instance creation

  • **kwargs – Keyword arguments for instance creation

Returns:

The singleton instance of the class

classmethod clear_instances()[source]

Clear all singleton instances.

Useful for testing or when you need to reset framework state.