M2: Block attribution (generated / absorbed / wasted) #6

Closed
opened 2026-04-19 16:59:53 -07:00 by nelsong6 · 1 comment
nelsong6 commented 2026-04-19 16:59:53 -07:00 (Migrated from github.com)

Goal

Attribute each block card's generated block to what it actually did this run.

M2a already covered direct block-gained attribution. This issue tracks the remaining work to determine how much of each card's block actually absorbed damage vs. was effectively unnecessary.

This issue supersedes #1 and #14 so block attribution lives in one place.

Semantics

Use grant-order attribution with oldest block consumed first.

This is the intended behavior for the feature, not just a fallback heuristic:

  • The stat should reflect the player's mental model of marginal card value.
  • Earlier block is the baseline protection already in place.
  • Later block is the extra block added on top.
  • Whatever remains unused when block expires should be counted as waste for the source that added it.

Example:

  • Defend grants 5
  • Shrug It Off grants 8
  • Player later blocks 6 total damage
  • Turn ends with 7 block removed as unused

Attribution should be:

  • Defend: 5 effective, 0 wasted
  • Shrug It Off: 1 effective, 7 wasted

This is the signal we want: "was this later block card actually needed, or was it mostly redundant?"

Data model

Maintain a runtime provenance ledger for the player's current block pool.

private sealed class BlockChunk
{
    public string? CardInstanceId { get; init; }
    public int Remaining { get; set; }
    public int Sequence { get; init; }
    public bool CountsForCardStats => CardInstanceId != null;
}

State on combat history / run tracker side:

private readonly List<BlockChunk> _playerBlockLedger = new();
private int _nextBlockSequence = 0;

Event handling

1. On block gain

Whenever the player gains block from a BlockGainedEntry:

  • increment the source card's TotalBlockGenerated if the source is a card
  • append a new BlockChunk to _playerBlockLedger
  • preserve grant order using Sequence

Pseudo-code:

private void OnBlockGained(BlockGainedEntry entry)
{
    if (!IsPlayer(entry.Receiver) || entry.Amount <= 0)
        return;

    string? cardInstanceId = entry.CardPlay?.CardInstanceId;

    if (cardInstanceId != null)
        GetAggregate(cardInstanceId).TotalBlockGenerated += entry.Amount;

    _playerBlockLedger.Add(new BlockChunk
    {
        CardInstanceId = cardInstanceId,
        Remaining = entry.Amount,
        Sequence = _nextBlockSequence++
    });
}

Non-card block sources should still create chunks, but with CardInstanceId = null, so they participate in consumption order without polluting card stats.

2. On damage that consumes block

Whenever the player takes damage and some amount is blocked:

  • read BlockedDamage
  • walk _playerBlockLedger from oldest to newest
  • subtract from each chunk until the blocked amount is exhausted
  • for each card-backed chunk, add that consumed amount to TotalBlockEffective
  • remove chunks whose Remaining reaches zero

Pseudo-code:

private void OnDamageReceived(DamageReceivedEntry entry)
{
    if (!IsPlayer(entry.Receiver))
        return;

    int blocked = entry.Result?.BlockedDamage ?? 0;
    if (blocked <= 0)
        return;

    int remainingToAttribute = blocked;

    for (int i = 0; i < _playerBlockLedger.Count && remainingToAttribute > 0; i++)
    {
        BlockChunk chunk = _playerBlockLedger[i];
        if (chunk.Remaining <= 0)
            continue;

        int consumed = Math.Min(chunk.Remaining, remainingToAttribute);
        chunk.Remaining -= consumed;
        remainingToAttribute -= consumed;

        if (chunk.CardInstanceId != null)
            GetAggregate(chunk.CardInstanceId).TotalBlockEffective += consumed;
    }

    _playerBlockLedger.RemoveAll(chunk => chunk.Remaining <= 0);
}

This must run whenever damage happens, not only on enemy turns, because some rare effects can cause block consumption during the player's own turn.

3. On block expiration / removal without preventing HP loss

At the point where block is removed because it expired or otherwise ceased to exist without absorbing damage:

  • compute how much block actually disappeared from the player's pool for that reason
  • attribute that loss from oldest to newest or newest to oldest?

For this feature, unused block should be blamed on the most recently added surviving chunks first.

Why:

  • earlier block was the foundation that made the player "already safe"
  • later block is the marginal overfill
  • if turn ends and some block vanishes unused, that unused portion is most naturally the newest redundant block

So the final rule is:

  • blocked damage consumption: FIFO (oldest first)
  • unused leftover at expiry/removal: LIFO over the remaining ledger (newest first)

Pseudo-code:

private void AttributeUnusedBlock(int unusedBlockToRemove)
{
    for (int i = _playerBlockLedger.Count - 1; i >= 0 && unusedBlockToRemove > 0; i--)
    {
        BlockChunk chunk = _playerBlockLedger[i];
        if (chunk.Remaining <= 0)
            continue;

        int wasted = Math.Min(chunk.Remaining, unusedBlockToRemove);
        chunk.Remaining -= wasted;
        unusedBlockToRemove -= wasted;

        if (chunk.CardInstanceId != null)
            GetAggregate(chunk.CardInstanceId).TotalBlockWasted += wasted;
    }

    _playerBlockLedger.RemoveAll(chunk => chunk.Remaining <= 0);
}

This gives the intuitive result that the "extra" block card played later is the one that gets marked wasted first.

Required hook points

Need reliable hooks for:

  • player block gained
  • player damage received with BlockedDamage
  • turn-end block decay or any other explicit block reset/removal event
  • combat end cleanup for any surviving block that never mattered

If there is no single clean "block expired" event, the fallback is to compare:

  • total remaining ledger before the decay/reset point
  • actual player block after the decay/reset point

Then attribute the difference via AttributeUnusedBlock(diff).

Aggregate fields

  • TotalBlockGenerated ? raw block the card produced
  • TotalBlockEffective ? block that actually absorbed incoming damage
  • TotalBlockWasted ? block that disappeared unused

These should stay integer-valued throughout; no fractional math is needed with this model.

Display

Tooltip block section target:

Block gained    25
Avg block       5.0
Absorbed        18 (72%)
Wasted           7 (28%)

Definitions:

  • Absorbed % = TotalBlockEffective / TotalBlockGenerated
  • Wasted % = TotalBlockWasted / TotalBlockGenerated

Percentages may not sum to 100% if there are edge cases like retained block or unresolved removal categories that need their own handling.

Edge cases / design questions

  • Retained block: if block legitimately carries into the next turn, do not mark it wasted at normal end-of-turn decay.
  • Non-card sources: powers, relics, statuses, and other effects should occupy ledger space but not award/blame any card.
  • Block stripped by effects: decide whether this counts as Wasted or needs a separate future bucket such as Removed.
  • Combat end with block remaining: likely count as wasted, since it never prevented any future damage.
  • Missing events: confirm that fully blocked hits still emit the needed DamageReceivedEntry.Result.BlockedDamage in all relevant paths.
  • Hot reload / persistence: if combat state is resumable mid-fight, the ledger itself may need to be serialized, not just the aggregates.

Definition of done

  • Ordered block provenance ledger maintained during combat
  • BlockGainedEntry appends chunks and increments TotalBlockGenerated
  • DamageReceivedEntry attributes blocked damage FIFO into TotalBlockEffective
  • Block expiry/removal attributes unused block LIFO into TotalBlockWasted
  • Non-card sources are isolated from card aggregates
  • Aggregate fields persist correctly across hot reload/resume if needed
  • Tooltip renders absorbed and wasted rows clearly
## Goal Attribute each block card's generated block to what it actually did this run. M2a already covered direct block-gained attribution. This issue tracks the remaining work to determine how much of each card's block actually absorbed damage vs. was effectively unnecessary. This issue supersedes #1 and #14 so block attribution lives in one place. ## Semantics Use **grant-order attribution** with **oldest block consumed first**. This is the intended behavior for the feature, not just a fallback heuristic: - The stat should reflect the player's mental model of marginal card value. - Earlier block is the baseline protection already in place. - Later block is the extra block added on top. - Whatever remains unused when block expires should be counted as waste for the source that added it. Example: - Defend grants 5 - Shrug It Off grants 8 - Player later blocks 6 total damage - Turn ends with 7 block removed as unused Attribution should be: - Defend: 5 effective, 0 wasted - Shrug It Off: 1 effective, 7 wasted This is the signal we want: "was this later block card actually needed, or was it mostly redundant?" ## Data model Maintain a runtime provenance ledger for the player's current block pool. ```csharp private sealed class BlockChunk { public string? CardInstanceId { get; init; } public int Remaining { get; set; } public int Sequence { get; init; } public bool CountsForCardStats => CardInstanceId != null; } ``` State on combat history / run tracker side: ```csharp private readonly List<BlockChunk> _playerBlockLedger = new(); private int _nextBlockSequence = 0; ``` ## Event handling ### 1. On block gain Whenever the player gains block from a `BlockGainedEntry`: - increment the source card's `TotalBlockGenerated` if the source is a card - append a new `BlockChunk` to `_playerBlockLedger` - preserve grant order using `Sequence` Pseudo-code: ```csharp private void OnBlockGained(BlockGainedEntry entry) { if (!IsPlayer(entry.Receiver) || entry.Amount <= 0) return; string? cardInstanceId = entry.CardPlay?.CardInstanceId; if (cardInstanceId != null) GetAggregate(cardInstanceId).TotalBlockGenerated += entry.Amount; _playerBlockLedger.Add(new BlockChunk { CardInstanceId = cardInstanceId, Remaining = entry.Amount, Sequence = _nextBlockSequence++ }); } ``` Non-card block sources should still create chunks, but with `CardInstanceId = null`, so they participate in consumption order without polluting card stats. ### 2. On damage that consumes block Whenever the player takes damage and some amount is blocked: - read `BlockedDamage` - walk `_playerBlockLedger` from oldest to newest - subtract from each chunk until the blocked amount is exhausted - for each card-backed chunk, add that consumed amount to `TotalBlockEffective` - remove chunks whose `Remaining` reaches zero Pseudo-code: ```csharp private void OnDamageReceived(DamageReceivedEntry entry) { if (!IsPlayer(entry.Receiver)) return; int blocked = entry.Result?.BlockedDamage ?? 0; if (blocked <= 0) return; int remainingToAttribute = blocked; for (int i = 0; i < _playerBlockLedger.Count && remainingToAttribute > 0; i++) { BlockChunk chunk = _playerBlockLedger[i]; if (chunk.Remaining <= 0) continue; int consumed = Math.Min(chunk.Remaining, remainingToAttribute); chunk.Remaining -= consumed; remainingToAttribute -= consumed; if (chunk.CardInstanceId != null) GetAggregate(chunk.CardInstanceId).TotalBlockEffective += consumed; } _playerBlockLedger.RemoveAll(chunk => chunk.Remaining <= 0); } ``` This must run whenever damage happens, not only on enemy turns, because some rare effects can cause block consumption during the player's own turn. ### 3. On block expiration / removal without preventing HP loss At the point where block is removed because it expired or otherwise ceased to exist without absorbing damage: - compute how much block actually disappeared from the player's pool for that reason - attribute that loss from oldest to newest or newest to oldest? For this feature, **unused block should be blamed on the most recently added surviving chunks first**. Why: - earlier block was the foundation that made the player "already safe" - later block is the marginal overfill - if turn ends and some block vanishes unused, that unused portion is most naturally the newest redundant block So the final rule is: - blocked damage consumption: **FIFO** (oldest first) - unused leftover at expiry/removal: **LIFO** over the remaining ledger (newest first) Pseudo-code: ```csharp private void AttributeUnusedBlock(int unusedBlockToRemove) { for (int i = _playerBlockLedger.Count - 1; i >= 0 && unusedBlockToRemove > 0; i--) { BlockChunk chunk = _playerBlockLedger[i]; if (chunk.Remaining <= 0) continue; int wasted = Math.Min(chunk.Remaining, unusedBlockToRemove); chunk.Remaining -= wasted; unusedBlockToRemove -= wasted; if (chunk.CardInstanceId != null) GetAggregate(chunk.CardInstanceId).TotalBlockWasted += wasted; } _playerBlockLedger.RemoveAll(chunk => chunk.Remaining <= 0); } ``` This gives the intuitive result that the "extra" block card played later is the one that gets marked wasted first. ## Required hook points Need reliable hooks for: - player block gained - player damage received with `BlockedDamage` - turn-end block decay or any other explicit block reset/removal event - combat end cleanup for any surviving block that never mattered If there is no single clean "block expired" event, the fallback is to compare: - total remaining ledger before the decay/reset point - actual player block after the decay/reset point Then attribute the difference via `AttributeUnusedBlock(diff)`. ## Aggregate fields - `TotalBlockGenerated` ? raw block the card produced - `TotalBlockEffective` ? block that actually absorbed incoming damage - `TotalBlockWasted` ? block that disappeared unused These should stay integer-valued throughout; no fractional math is needed with this model. ## Display Tooltip block section target: ```text Block gained 25 Avg block 5.0 Absorbed 18 (72%) Wasted 7 (28%) ``` Definitions: - `Absorbed % = TotalBlockEffective / TotalBlockGenerated` - `Wasted % = TotalBlockWasted / TotalBlockGenerated` Percentages may not sum to 100% if there are edge cases like retained block or unresolved removal categories that need their own handling. ## Edge cases / design questions - **Retained block:** if block legitimately carries into the next turn, do not mark it wasted at normal end-of-turn decay. - **Non-card sources:** powers, relics, statuses, and other effects should occupy ledger space but not award/blame any card. - **Block stripped by effects:** decide whether this counts as `Wasted` or needs a separate future bucket such as `Removed`. - **Combat end with block remaining:** likely count as wasted, since it never prevented any future damage. - **Missing events:** confirm that fully blocked hits still emit the needed `DamageReceivedEntry.Result.BlockedDamage` in all relevant paths. - **Hot reload / persistence:** if combat state is resumable mid-fight, the ledger itself may need to be serialized, not just the aggregates. ## Definition of done - [ ] Ordered block provenance ledger maintained during combat - [ ] `BlockGainedEntry` appends chunks and increments `TotalBlockGenerated` - [ ] `DamageReceivedEntry` attributes blocked damage FIFO into `TotalBlockEffective` - [ ] Block expiry/removal attributes unused block LIFO into `TotalBlockWasted` - [ ] Non-card sources are isolated from card aggregates - [ ] Aggregate fields persist correctly across hot reload/resume if needed - [ ] Tooltip renders absorbed and wasted rows clearly
nelsong6 commented 2026-04-20 21:39:57 -07:00 (Migrated from github.com)

Shipped in 3da6037.

This lands the main M2 block-attribution pass:

  • player block provenance ledger maintained during combat
  • BlockGainedEntry credited back to the originating card, with current/recent play fallback when the history entry omits CardPlay
  • blocked damage attributed FIFO into TotalBlockEffective
  • cleared/expired leftover block attributed LIFO into TotalBlockWasted
  • surviving block at combat end counted as wasted
  • non-card sources still occupy ledger space without polluting card stats
  • tooltip now shows Block gained / Avg block together plus Absorbed and Wasted
  • schema bumped to 5 with fixture/test coverage

Verification:

  • dotnet test D:\repos\CardUtilityStats\Tests\CardUtilityStats.Core.Tests\CardUtilityStats.Core.Tests.csproj -c Debug passed 12/12
  • in-game manual verification confirmed block cards now show the new stats and layout correctly
Shipped in 3da6037. This lands the main M2 block-attribution pass: - player block provenance ledger maintained during combat - BlockGainedEntry credited back to the originating card, with current/recent play fallback when the history entry omits CardPlay - blocked damage attributed FIFO into TotalBlockEffective - cleared/expired leftover block attributed LIFO into TotalBlockWasted - surviving block at combat end counted as wasted - non-card sources still occupy ledger space without polluting card stats - tooltip now shows Block gained / Avg block together plus Absorbed and Wasted - schema bumped to 5 with fixture/test coverage Verification: - dotnet test D:\repos\CardUtilityStats\Tests\CardUtilityStats.Core.Tests\CardUtilityStats.Core.Tests.csproj -c Debug passed 12/12 - in-game manual verification confirmed block cards now show the new stats and layout correctly
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
romaine-life/spirelens#6
No description provided.