new builder option per draft - first one is gold per kill

This commit is contained in:
Ian Woods 2026-07-07 22:55:35 -07:00
parent 4a37d3747c
commit 157b77ebfa
21 changed files with 456 additions and 7 deletions

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dd9f1f667cfdcbf6d9ee44acc270f128
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,34 @@
// Assets/_Project/Scripts/Gameplay/BuilderEffects/BuilderEffectDefinition.cs
using UnityEngine;
using TD.Core;
namespace TD.Gameplay.BuilderEffects
{
/// <summary>
/// Base class for one builder effect — a passive perk that applies to every tower a
/// player's Builder constructs (e.g. "kills yield bonus gold"). Granted via the draft
/// (<see cref="TD.Gameplay.Draft.BuilderEffectDraftOption"/>) and tracked per-player by
/// <see cref="BuilderUpgradeManager"/>.
/// </summary>
/// <remarks>
/// <para><b>One asset per kind.</b> <see cref="Kind"/> is fixed per subclass (each concrete
/// type overrides it to its own <see cref="BuilderEffectKind"/>), so there's no way to
/// mis-tag an asset in the inspector. <see cref="BuilderEffectPool"/> uses it to build a
/// fixed-size, enum-indexed lookup table — no scanning to resolve a kind to its data.</para>
///
/// <para><b>No shared "Apply" contract.</b> Concrete subclasses (e.g.
/// <see cref="GoldPerKillEffectDefinition"/>) carry whatever payload they need. Effects with
/// different application shapes — a simple value read at an existing game-event hook vs.
/// behavior that needs its own component on the tower — are still just subclasses; consumers
/// query the concrete type they care about directly (see
/// <see cref="BuilderUpgradeManager.GetTotalGoldPerKillBonus"/>).</para>
/// </remarks>
public abstract class BuilderEffectDefinition : ScriptableObject
{
/// <summary>Which builder effect this asset's data belongs to.</summary>
public abstract BuilderEffectKind Kind { get; }
[Tooltip("Name shown wherever a player's active builder effects are listed.")]
public string DisplayName;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3a939cb6af19202e1a9bddf01d9f1857

View file

@ -0,0 +1,66 @@
// Assets/_Project/Scripts/Gameplay/BuilderEffects/BuilderEffectPool.cs
using System;
using UnityEngine;
using TD.Core;
namespace TD.Gameplay.BuilderEffects
{
/// <summary>
/// Scene singleton holding every <see cref="BuilderEffectDefinition"/> available this match,
/// authored as a flat array in the inspector for convenience. Internally it builds a
/// fixed-size table indexed by <see cref="BuilderEffectKind"/> so lookups are a single array
/// access, not a scan.
/// </summary>
/// <remarks>
/// Plain MonoBehaviour: identical on every peer (same assets), so there is nothing to sync.
/// The server reads it to resolve grants; clients read it to render an "active effects" list.
/// </remarks>
public class BuilderEffectPool : MonoBehaviour
{
public static BuilderEffectPool Instance { get; private set; }
[Tooltip("Every BuilderEffectDefinition asset available this match. One entry per " +
"BuilderEffectKind — order doesn't matter, Kind on the asset itself decides " +
"its slot.")]
[SerializeField] private BuilderEffectDefinition[] effects;
// Fixed-size, enum-indexed lookup built once in Awake. Sized to the enum's entry count,
// not authored count, so an out-of-range Kind is a compile-time impossibility rather
// than a bounds check we'd otherwise need on every Get().
private BuilderEffectDefinition[] byKind;
private void Awake()
{
if (Instance != null && Instance != this)
{
Debug.LogError("[BuilderEffectPool] Multiple instances detected. Only one per scene.");
return;
}
Instance = this;
int kindCount = Enum.GetValues(typeof(BuilderEffectKind)).Length;
byKind = new BuilderEffectDefinition[kindCount];
if (effects == null) return;
for (int i = 0; i < effects.Length; i++)
{
var def = effects[i];
if (def == null) continue;
byKind[(int)def.Kind] = def;
}
}
private void OnDestroy()
{
if (Instance == this) Instance = null;
}
/// <summary>Returns the effect asset for <paramref name="kind"/>, or null if none is
/// authored in this pool.</summary>
public BuilderEffectDefinition Get(BuilderEffectKind kind)
{
int i = (int)kind;
return (byKind != null && i >= 0 && i < byKind.Length) ? byKind[i] : null;
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6226c6e672c5b358a9cdc2a1bee47daf

View file

@ -0,0 +1,22 @@
// Assets/_Project/Scripts/Gameplay/BuilderEffects/GoldPerKillEffectDefinition.cs
using UnityEngine;
using TD.Core;
namespace TD.Gameplay.BuilderEffects
{
/// <summary>
/// Builder effect #1 — every tower the player owns yields extra gold per kill.
/// Read by <see cref="BuilderUpgradeManager.GetTotalGoldPerKillBonus"/>, which
/// <see cref="TD.Gameplay.WaveManager"/> queries when awarding kill gold.
/// </summary>
[CreateAssetMenu(fileName = "GoldPerKillEffect", menuName = "TD/Builder Effects/Gold Per Kill")]
public class GoldPerKillEffectDefinition : BuilderEffectDefinition
{
public override BuilderEffectKind Kind => BuilderEffectKind.GoldPerKill;
[Tooltip("Flat bonus gold awarded on top of the normal kill reward, for every kill by " +
"any of this player's towers.")]
[Min(0)]
public int BonusGoldPerKill = 1;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5ce77a7f27ed228a0ad0494dfc1a4749

View file

@ -0,0 +1,125 @@
// Assets/_Project/Scripts/Gameplay/BuilderUpgradeManager.cs
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using TD.Core;
using TD.Gameplay.BuilderEffects;
namespace TD.Gameplay
{
/// <summary>
/// Per-player set of granted builder effects. Lives on the Player prefab alongside
/// <see cref="PlayerGoldManager"/>, <see cref="PlayerTowerDeck"/>, and
/// <see cref="PlayerBuffManager"/>.
/// </summary>
/// <remarks>
/// <para><b>Bitmask, not a list.</b> A builder effect carries no per-grant state (no level,
/// no enable/disable toggle) — it's either granted or it isn't — so the granted set is one
/// <see cref="NetworkVariable{T}"/> bitmask keyed by <see cref="BuilderEffectKind"/> rather
/// than a <c>NetworkList</c>. "Has effect" and "grant effect" are both O(1) bit ops.</para>
///
/// <para><b>Granted via draft.</b> <see cref="TD.Gameplay.Draft.BuilderEffectDraftOption"/>
/// calls <see cref="ServerGrantEffect"/> when a player picks it. Effects are permanent for
/// the match — there is no revoke.</para>
///
/// <para><b>Query, don't snapshot.</b> Consumers (e.g. <see cref="WaveManager"/> awarding
/// kill gold) query this manager live at the point of use rather than towers caching their
/// own copy — every tower a player owns benefits immediately, including ones built before
/// the effect was granted.</para>
///
/// <para><b>Generic accessor, not one method per effect.</b>
/// <see cref="GetEffectDefinition{T}"/> is the only way to read an effect's tunable data.
/// This keeps the API surface fixed as the effect roster grows — a new effect kind adds a
/// call site where it's consumed (e.g. a new line in <c>WaveManager</c>), not a new method
/// here.</para>
/// </remarks>
public class BuilderUpgradeManager : NetworkBehaviour
{
// ----- Static registry (mirrors PlayerGoldManager / PlayerTowerDeck) -----
private static readonly Dictionary<ulong, BuilderUpgradeManager> s_byClientId
= new Dictionary<ulong, BuilderUpgradeManager>();
/// <summary>Returns the manager owned by the given client, or null.</summary>
public static BuilderUpgradeManager GetForClient(ulong clientId)
{
s_byClientId.TryGetValue(clientId, out var mgr);
return mgr;
}
/// <summary>Convenience: the local client's own manager.</summary>
public static BuilderUpgradeManager Local
{
get
{
var nm = NetworkManager.Singleton;
if (nm == null || !nm.IsClient) return null;
return GetForClient(nm.LocalClientId);
}
}
// ----- Networked state --------------------------------------------
// One bit per BuilderEffectKind. readPerm Everyone (consistent with the other
// per-player managers); writePerm Server.
private readonly NetworkVariable<uint> grantedMask = new NetworkVariable<uint>(
value: 0,
readPerm: NetworkVariableReadPermission.Everyone,
writePerm: NetworkVariableWritePermission.Server
);
/// <summary>Fired on every peer when a new effect is granted.</summary>
public event System.Action OnUpgradesChanged;
// ----- NGO lifecycle ------------------------------------------------
public override void OnNetworkSpawn()
{
s_byClientId[OwnerClientId] = this;
grantedMask.OnValueChanged += HandleMaskChanged;
}
public override void OnNetworkDespawn()
{
grantedMask.OnValueChanged -= HandleMaskChanged;
if (s_byClientId.TryGetValue(OwnerClientId, out var registered) && registered == this)
s_byClientId.Remove(OwnerClientId);
}
private void HandleMaskChanged(uint previous, uint current) => OnUpgradesChanged?.Invoke();
// ----- Read API -----------------------------------------------------
/// <summary>True if this player has been granted the given effect.</summary>
public bool PlayerHasEffect(BuilderEffectKind kind) => (grantedMask.Value & BitFor(kind)) != 0;
/// <summary>
/// Returns this player's <see cref="BuilderEffectDefinition"/> for <paramref name="kind"/>
/// as <typeparamref name="T"/>, or null if the player doesn't have it (or the pool has no
/// asset for it). Callers extract whatever field they need — see the "generic accessor"
/// note above for why this isn't a per-effect method.
/// </summary>
public T GetEffectDefinition<T>(BuilderEffectKind kind) where T : BuilderEffectDefinition
=> PlayerHasEffect(kind) ? BuilderEffectPool.Instance?.Get(kind) as T : null;
// ----- Server mutation -----------------------------------------------
/// <summary>
/// Server-only: grants the given effect (a draft pick). No-op if already granted.
/// Returns true if it was actually granted.
/// </summary>
public bool ServerGrantEffect(BuilderEffectKind kind)
{
if (!IsServer) return false;
uint bit = BitFor(kind);
if ((grantedMask.Value & bit) != 0) return false;
grantedMask.Value |= bit;
return true;
}
private static uint BitFor(BuilderEffectKind kind) => 1u << (int)kind;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 72dac94cde24af07ea0b5c77b228be34

View file

@ -0,0 +1,37 @@
// Assets/_Project/Scripts/Gameplay/Draft/BuilderEffectDraftOption.cs
using UnityEngine;
using TD.Core;
using TD.Gameplay.BuilderEffects;
namespace TD.Gameplay.Draft
{
/// <summary>
/// Draft choice #2 — "gain a builder effect". Grants the player a passive effect that
/// applies to every tower they own, adding it to their <see cref="BuilderUpgradeManager"/>.
/// </summary>
/// <remarks>
/// Unlike <see cref="NewTowerDraftOption"/>, this carries the <see cref="BuilderEffectKind"/>
/// directly rather than an asset reference — there's no id to resolve, the enum value is the
/// stable identifier <see cref="BuilderUpgradeManager"/> and <see cref="BuilderEffectPool"/>
/// already key off of.
/// </remarks>
[CreateAssetMenu(fileName = "BuilderEffectOption", menuName = "TD/Draft/Builder Effect Option")]
public class BuilderEffectDraftOption : DraftOption
{
[Header("Payload")]
[Tooltip("The builder effect this option grants.")]
public BuilderEffectKind Kind;
public override bool IsValidFor(ulong clientId)
{
var upgrades = BuilderUpgradeManager.GetForClient(clientId);
return upgrades != null && !upgrades.PlayerHasEffect(Kind);
}
public override bool ServerApply(ulong clientId)
{
var upgrades = BuilderUpgradeManager.GetForClient(clientId);
return upgrades != null && upgrades.ServerGrantEffect(Kind);
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4eaef3264612070c48fbc6a987c89858

View file

@ -3,6 +3,7 @@ using System.Collections;
using Unity.Netcode;
using UnityEngine;
using TD.Core;
using TD.Gameplay.BuilderEffects;
using TD.Gameplay.Draft;
using TD.Levels;
using TD.UI;
@ -524,22 +525,31 @@ namespace TD.Gameplay
var goldEntry = goldConfig?.GetWaveEntry(currentWaveIndex + 1);
if (goldEntry != null) killReward = goldEntry.GoldPerEnemy;
// Award kill gold to the tower owner that landed the killing blow.
// Award kill gold to the tower owner that landed the killing blow. The builder's
// "gold per kill" effect (if granted) is queried live here rather than cached on
// the killing tower — see BuilderUpgradeManager's "query, don't snapshot" note.
PlayerSlot killerSlot = health.LastHitOwner;
int totalReward = killReward;
if (killerSlot != PlayerSlot.None && killReward > 0)
{
var pms = PlayerMatchState.GetForSlot(killerSlot);
if (pms != null)
{
var gpk = BuilderUpgradeManager.GetForClient(pms.OwnerClientId)
?.GetEffectDefinition<GoldPerKillEffectDefinition>(BuilderEffectKind.GoldPerKill);
totalReward = killReward + (gpk?.BonusGoldPerKill ?? 0);
PlayerGoldManager.GetForClient(pms.OwnerClientId)
?.AwardGold(killReward);
?.AwardGold(totalReward);
}
}
// Show a "+N" gold popup above the corpse on every peer. Capture the
// position here on the server — by the time the RPC fires on clients
// the death sequence will be moving the corpse, but the spawn point
// is good enough and we want the popup to anchor where the kill happened.
if (killReward > 0)
ShowGoldRewardClientRpc(health.transform.position, killReward);
if (totalReward > 0)
ShowGoldRewardClientRpc(health.transform.position, totalReward);
UnsubscribeEnemy(health);
DecrementAndCheckComplete();