Combat System

The combat module provides a turn-based combat system with extensible actions, targeting, and damage calculation.

Combat Engine

Turn-based combat system.

This module provides the core combat management system.

class barebones_rpg.combat.combat.CombatState(value)[source]

Bases: Enum

States of combat.

NOT_STARTED = 1
TURN_START = 2
PLAYER_TURN = 3
ENEMY_TURN = 4
TURN_END = 5
VICTORY = 6
DEFEAT = 7
FLED = 8
class barebones_rpg.combat.combat.CombatantGroup(**data)[source]

Bases: BaseModel

A group of combatants (party or enemy group).

name: str
members: List[Any]
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

get_alive_members()[source]

Get all living members.

Return type:

List[Any]

Returns:

List of alive members

is_defeated()[source]

Check if entire group is defeated.

Return type:

bool

Returns:

True if all members are dead

add_member(member)[source]

Add a member to the group.

Parameters:

member (Any) – Entity to add

Return type:

bool

Returns:

True if member was added successfully

remove_member(member)[source]

Remove a member from the group.

Parameters:

member (Any) – Entity to remove

Return type:

bool

Returns:

True if member was found and removed

class barebones_rpg.combat.combat.TurnOrder(**data)[source]

Bases: BaseModel

Manages turn order based on speed.

combatants: List[Any]
current_index: int
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

initialize(all_combatants)[source]

Initialize turn order.

Parameters:

all_combatants (List[Any]) – All entities in combat

Return type:

None

get_current()[source]

Get the current combatant.

Return type:

Optional[Any]

Returns:

Current combatant or None if none available

next_turn()[source]

Move to next turn.

Return type:

Optional[Any]

Returns:

Next combatant

get_alive_combatants()[source]

Get all alive combatants.

Return type:

List[Any]

Returns:

List of alive combatants

class barebones_rpg.combat.combat.Combat(player_group, enemy_group, events=None)[source]

Bases: object

Turn-based combat manager.

Manages combat between two groups (players vs enemies), handles turn order, and processes combat actions.

Example

>>> from barebones_rpg.entities import Character, Enemy
>>> from barebones_rpg.core import EventManager
>>> from barebones_rpg.party import Party
>>>
>>> hero = Character(name="Hero", stats=Stats(hp=100, atk=15))
>>> goblin = Enemy(name="Goblin", stats=Stats(hp=30, atk=5))
>>>
>>> # Using lists (backward compatible)
>>> combat = Combat(
...     player_group=[hero],
...     enemy_group=[goblin],
...     events=EventManager()
... )
>>>
>>> # Or using Party objects
>>> party = Party(name="Heroes", members=[hero])
>>> enemies = Party(name="Monsters", members=[goblin])
>>> combat = Combat(
...     player_group=party,
...     enemy_group=enemies,
...     events=EventManager()
... )
>>> combat.start()
>>> # Combat is now active
__init__(player_group, enemy_group, events=None)[source]

Initialize combat.

Parameters:
  • player_group (Union[List[Any], Party]) – List of player characters or Party object

  • enemy_group (Union[List[Any], Party]) – List of enemies or Party object

  • events (Optional[EventManager]) – Event manager for publishing combat events

start()[source]

Start combat.

Return type:

None

execute_action(action, source, targets)[source]

Execute a combat action.

Parameters:
  • action (CombatAction) – The action to execute

  • source (Any) – Entity performing the action

  • targets (List[Any]) – List of target entities (can be empty for self-targeting actions)

Return type:

ActionResult

Returns:

Result of the action

end_turn()[source]

End the current turn and move to next.

Return type:

None

on_victory(callback)[source]

Register callback for victory.

Parameters:

callback (Callable) – Function to call on victory

Return type:

None

on_defeat(callback)[source]

Register callback for defeat.

Parameters:

callback (Callable) – Function to call on defeat

Return type:

None

on_flee(callback)[source]

Register callback for fleeing.

Parameters:

callback (Callable) – Function to call when fled

Return type:

None

get_current_combatant()[source]

Get the current combatant whose turn it is.

Return type:

Optional[Any]

Returns:

Current combatant

is_player_turn()[source]

Check if it’s a player’s turn.

Return type:

bool

Returns:

True if current turn is a player

is_active()[source]

Check if combat is still active.

Return type:

bool

Returns:

True if combat is ongoing

get_dropped_loot()[source]

Get all loot dropped during this combat.

Return type:

List[Any]

Returns:

List of LootDrop objects

Example

>>> combat = Combat(...)
>>> # ... combat happens ...
>>> for drop in combat.get_dropped_loot():
...     player.inventory.add_item(drop.item)

Combat Actions

Combat actions and effects.

This module defines the actions that can be taken during combat.

class barebones_rpg.combat.actions.ActionType(value)[source]

Bases: Enum

Types of combat actions.

ATTACK = 1
SKILL = 2
ITEM = 3
RUN = 4
CUSTOM = 5
class barebones_rpg.combat.actions.ActionResult(**data)[source]

Bases: BaseModel

Result of a combat action.

Contains information about what happened when an action was performed. Supports both single-target and multi-target actions.

success: bool
damage: int
healing: int
message: str
critical: bool
missed: bool
targets_hit: List[Any]
target_results: Dict[str, Any]
metadata: Dict[str, Any]
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class barebones_rpg.combat.actions.CombatAction(action_type=ActionType.CUSTOM)[source]

Bases: ABC

Base class for combat actions.

All combat actions inherit from this and implement execute(). Actions now accept a list of targets to support both single-target and multi-target (AOE) abilities.

__init__(action_type=ActionType.CUSTOM)[source]
abstractmethod execute(source, targets, context)[source]

Execute the action.

Parameters:
  • source (Any) – Entity performing the action

  • targets (List[Any]) – List of target entities (empty list for self-only actions)

  • context (Dict[str, Any]) – Additional context (combat state, etc.)

Return type:

ActionResult

Returns:

Result of the action

Note

For single-target actions, use targets[0] (after checking the list isn’t empty). For multi-target actions, iterate through all targets in the list.

can_execute(source, context)[source]

Check if action can be executed.

Parameters:
  • source (Any) – Entity performing the action

  • context (Dict[str, Any]) – Additional context

Return type:

bool

Returns:

True if action can be performed

class barebones_rpg.combat.actions.AttackAction[source]

Bases: CombatAction

Basic physical attack action.

__init__()[source]
calculate_damage(source, target, weapon, context)[source]

Calculate base damage before crits and defense.

Override this method to add proficiency systems or other damage modifiers.

Parameters:
Return type:

Tuple[int, str]

Returns:

Tuple of (damage_amount, damage_type)

execute(source, targets, context)[source]

Execute a physical attack.

By default, attacks the first target in the list (single-target). Can be extended for cleave/multi-target attacks.

Parameters:
  • source (Any) – Attacker

  • targets (List[Any]) – List of target entities

  • context (Dict[str, Any]) – Combat context

Return type:

ActionResult

Returns:

Attack result

class barebones_rpg.combat.actions.SkillAction(name, mp_cost, effect, targets_enemy=True)[source]

Bases: CombatAction

Special skill/ability action.

This is a flexible action that can be customized.

__init__(name, mp_cost, effect, targets_enemy=True)[source]
can_execute(source, context)[source]

Check if skill can be used.

Parameters:
  • source (Any) – Entity using skill

  • context (Dict[str, Any]) – Combat context

Return type:

bool

Returns:

True if skill can be used

execute(source, targets, context)[source]

Execute the skill.

Parameters:
  • source (Any) – Entity using skill

  • targets (List[Any]) – List of target entities

  • context (Dict[str, Any]) – Combat context

Return type:

ActionResult

Returns:

Skill result

class barebones_rpg.combat.actions.ItemAction(item)[source]

Bases: CombatAction

Use an item during combat.

__init__(item)[source]
execute(source, targets, context)[source]

Use an item.

Parameters:
  • source (Any) – Entity using item

  • targets (List[Any]) – List of target entities (uses first target or source if empty)

  • context (Dict[str, Any]) – Combat context

Return type:

ActionResult

Returns:

Item use result

class barebones_rpg.combat.actions.RunAction[source]

Bases: CombatAction

Attempt to flee from combat.

__init__()[source]
execute(source, targets, context)[source]

Attempt to run from combat.

Parameters:
  • source (Any) – Entity trying to run

  • targets (List[Any]) – List of enemies (uses first for speed comparison if available)

  • context (Dict[str, Any]) – Combat context

Return type:

ActionResult

Returns:

Run attempt result

barebones_rpg.combat.actions.create_attack_action()[source]

Create a basic attack action.

Return type:

AttackAction

barebones_rpg.combat.actions.create_skill_action(name, mp_cost, damage_multiplier=1.5, damage_type='physical', targets_enemy=True, max_targets=1)[source]

Create a damage skill.

Parameters:
  • name (str) – Skill name

  • mp_cost (int) – MP cost

  • damage_multiplier (float) – Damage multiplier vs normal attack

  • damage_type (str) – Type of damage (physical, magic, or custom)

  • targets_enemy (bool) – Whether skill targets enemies

  • max_targets (int) – Maximum number of targets to hit (1=single target, 2=cleave, None=unlimited AOE)

Return type:

SkillAction

Returns:

Skill action

Example

>>> # Single-target skill
>>> fireball = create_skill_action("Fireball", mp_cost=10, damage_multiplier=2.0, damage_type="magic")
>>>
>>> # Cleave attack (hits 2 targets)
>>> cleave = create_skill_action("Cleave", mp_cost=5, damage_multiplier=1.2, max_targets=2)
>>>
>>> # AOE skill that hits all targets
>>> meteor = create_skill_action("Meteor", mp_cost=25, damage_multiplier=1.5, damage_type="magic", max_targets=None)
barebones_rpg.combat.actions.create_heal_skill(name, mp_cost, heal_amount, max_targets=1)[source]

Create a healing skill.

Parameters:
  • name (str) – Skill name

  • mp_cost (int) – MP cost

  • heal_amount (int) – Amount to heal per target

  • max_targets (int) – Maximum number of targets to heal (1=single target, None=unlimited group heal)

Return type:

SkillAction

Returns:

Healing skill action

Example

>>> # Single-target heal
>>> cure = create_heal_skill("Cure", mp_cost=5, heal_amount=30)
>>>
>>> # Group heal (heals 3 targets)
>>> group_heal = create_heal_skill("Group Heal", mp_cost=15, heal_amount=20, max_targets=3)
>>>
>>> # Mass heal (heals all targets)
>>> mass_heal = create_heal_skill("Mass Heal", mp_cost=25, heal_amount=15, max_targets=None)

Targeting

Targeting and distance calculation utilities for combat.

This module provides optional helper functions for distance calculations and target filtering. These are completely optional - games can use their own distance calculations or ignore positioning entirely.

barebones_rpg.combat.targeting.manhattan_distance(pos1, pos2)[source]

Calculate Manhattan (grid-based) distance between two positions.

Manhattan distance is the sum of horizontal and vertical distances, useful for grid-based movement where diagonal movement isn’t allowed or costs the same as orthogonal movement.

Parameters:
Return type:

int

Returns:

Manhattan distance as integer

Example

>>> manhattan_distance((0, 0), (3, 4))
7
>>> manhattan_distance((5, 5), (5, 8))
3
barebones_rpg.combat.targeting.euclidean_distance(pos1, pos2)[source]

Calculate Euclidean (straight-line) distance between two positions.

Euclidean distance is the straight-line distance between two points, useful for more realistic distance calculations or line-of-sight checks.

Parameters:
Return type:

float

Returns:

Euclidean distance as float

Example

>>> euclidean_distance((0, 0), (3, 4))
5.0
>>> euclidean_distance((0, 0), (1, 1))
1.414...
barebones_rpg.combat.targeting.chebyshev_distance(pos1, pos2)[source]

Calculate Chebyshev distance between two positions.

Chebyshev distance is the maximum of horizontal and vertical distances, useful for grid-based games where diagonal movement costs the same as orthogonal movement (8-directional movement).

Parameters:
Return type:

int

Returns:

Chebyshev distance as integer

Example

>>> chebyshev_distance((0, 0), (3, 4))
4
>>> chebyshev_distance((5, 5), (8, 7))
3
barebones_rpg.combat.targeting.is_in_range(source, target, range_value, distance_func=<function manhattan_distance>)[source]

Check if a target is within range of the source.

This is a helper function that checks if both entities have position attributes and calculates if the target is within the specified range.

Parameters:
  • source (Any) – Source entity (must have ‘position’ attribute)

  • target (Any) – Target entity (must have ‘position’ attribute)

  • range_value (int) – Maximum range

  • distance_func (Callable[[Tuple[int, int], Tuple[int, int]], float]) – Function to calculate distance (default: manhattan_distance)

Return type:

bool

Returns:

True if target is in range, False otherwise

Example

>>> class Entity:
...     def __init__(self, pos):
...         self.position = pos
>>> player = Entity((0, 0))
>>> enemy = Entity((2, 0))
>>> is_in_range(player, enemy, range_value=3)
True
>>> is_in_range(player, enemy, range_value=1)
False
barebones_rpg.combat.targeting.filter_targets_by_range(source, targets, range_value, distance_func=<function manhattan_distance>)[source]

Filter a list of targets to only those within range of the source.

This is useful for AOE abilities that have a maximum range, or for validating that all selected targets are reachable.

Parameters:
  • source (Any) – Source entity (must have ‘position’ attribute)

  • targets (List[Any]) – List of potential target entities

  • range_value (int) – Maximum range

  • distance_func (Callable[[Tuple[int, int], Tuple[int, int]], float]) – Function to calculate distance (default: manhattan_distance)

Return type:

List[Any]

Returns:

Filtered list of targets within range

Example

>>> class Entity:
...     def __init__(self, pos):
...         self.position = pos
>>> player = Entity((0, 0))
>>> enemies = [Entity((1, 0)), Entity((5, 0)), Entity((2, 1))]
>>> in_range = filter_targets_by_range(player, enemies, range_value=3)
>>> len(in_range)
2
barebones_rpg.combat.targeting.get_targets_in_area(center, radius, all_entities, distance_func=<function manhattan_distance>)[source]

Get all entities within a circular area.

This is useful for AOE effects centered on a position rather than an entity (e.g., a fireball explosion at a location).

Parameters:
  • center (Tuple[int, int]) – Center position (x, y)

  • radius (int) – Radius of the area

  • all_entities (List[Any]) – List of all entities to check

  • distance_func (Callable[[Tuple[int, int], Tuple[int, int]], float]) – Function to calculate distance (default: manhattan_distance)

Return type:

List[Any]

Returns:

List of entities within the area

Example

>>> class Entity:
...     def __init__(self, pos):
...         self.position = pos
>>> entities = [Entity((0, 0)), Entity((1, 1)), Entity((5, 5))]
>>> targets = get_targets_in_area((0, 0), radius=2, all_entities=entities)
>>> len(targets)
2
barebones_rpg.combat.targeting.get_targets_in_line(start, end, all_entities, width=0)[source]

Get all entities in a line between two points.

This is useful for line-based AOE effects like beam attacks or penetrating shots. Uses Bresenham’s line algorithm.

Parameters:
  • start (Tuple[int, int]) – Starting position (x, y)

  • end (Tuple[int, int]) – Ending position (x, y)

  • all_entities (List[Any]) – List of all entities to check

  • width (int) – Width of the line (0 = single tile wide)

Return type:

List[Any]

Returns:

List of entities along the line

Example

>>> class Entity:
...     def __init__(self, pos):
...         self.position = pos
>>> entities = [Entity((1, 0)), Entity((2, 0)), Entity((0, 1))]
>>> targets = get_targets_in_line((0, 0), (3, 0), entities)
>>> len(targets)
2

Damage Types

Damage type system with manager for flexible damage types and resistances.

This module provides a singleton manager for damage types, allowing games to register custom damage types with metadata while maintaining flexibility.

class barebones_rpg.combat.damage_types.DamageTypeMetadata(**data)[source]

Bases: BaseModel

Metadata for a damage type.

name: str
color: Optional[str]
description: Optional[str]
tags: List[str]
custom: Dict[str, Any]
model_config: ClassVar[ConfigDict] = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class barebones_rpg.combat.damage_types.DamageTypeManager(*args, **kwargs)[source]

Bases: object

Global manager for damage types (Singleton).

This manager handles all damage types in the game. It supports: - Pre-registration of common types - Metadata attachment (colors, descriptions, tags) - Lenient mode (auto-registers unknown types) - Query capabilities

Example

>>> # Register a custom damage type
>>> DamageTypeManager().register("necrotic", color="green", description="Death magic")
>>>
>>> # Check if registered
>>> DamageTypeManager().is_registered("necrotic")
True
>>>
>>> # Get metadata
>>> meta = DamageTypeManager().get_metadata("necrotic")
>>> print(meta.color)
green
>>>
>>> # Get all registered types
>>> types = DamageTypeManager().get_all()
>>> print(types)
['physical', 'magic', 'fire', 'ice', 'poison', 'lightning', 'dark', 'holy', 'necrotic']
__init__()[source]

Initialize the registry with common damage types.

register(damage_type, color=None, description=None, tags=None, **kwargs)[source]

Register a damage type with optional metadata.

Parameters:
  • damage_type (str) – Name of the damage type (e.g., “fire”, “necrotic”)

  • color (Optional[str]) – Display color for UI

  • description (Optional[str]) – Human-readable description

  • tags (Optional[List[str]]) – List of classification tags

  • **kwargs – Additional custom metadata

Return type:

None

is_registered(damage_type)[source]

Check if a damage type is registered.

Parameters:

damage_type (str) – Name of the damage type

Return type:

bool

Returns:

True if registered

get_metadata(damage_type)[source]

Get metadata for a damage type.

Parameters:

damage_type (str) – Name of the damage type

Return type:

Optional[DamageTypeMetadata]

Returns:

Metadata object or None if not registered

get_all()[source]

Get all registered damage types.

Return type:

List[str]

Returns:

List of damage type names

get_all_with_metadata()[source]

Get all damage types with their metadata.

Return type:

Dict[str, DamageTypeMetadata]

Returns:

Dictionary mapping damage type names to metadata

ensure_registered(damage_type)[source]

Ensure a damage type is registered, auto-registering if in lenient mode.

This is called internally when an unknown damage type is encountered. In lenient mode, it auto-registers with a warning. In strict mode, it raises an error.

Parameters:

damage_type (str) – Name of the damage type

Raises:

ValueError – If damage type not registered and not in lenient mode

Return type:

None

set_lenient_mode(lenient)[source]

Set lenient mode on/off.

In lenient mode, unknown damage types are auto-registered with a warning. In strict mode, unknown damage types raise an error.

Parameters:

lenient (bool) – True for lenient mode, False for strict mode

Return type:

None

classmethod reset()[source]

Reset manager to initial state (for testing).

Clears the singleton instance, causing the next access to create a fresh instance with default initialization.

Return type:

None