| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897 |
- using System.Collections.Generic;
- using UnityEngine;
- using System.Linq;
- using UnityEngine.UIElements;
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- /// <summary>
- /// Handles post-battle looting when all enemies are defeated
- /// Allows players to loot enemy corpses and manage inventory weight
- /// </summary>
- public class PostBattleLootSystem : MonoBehaviour
- {
- [Header("UI Toolkit References")]
- public UIDocument lootUIDocument;
- public VisualTreeAsset lootScreenTemplate;
- public PanelSettings panelSettings;
- [Header("Currency Settings")]
- public int baseGoldReward = 5;
- public int baseSilverReward = 15;
- public int baseCopperReward = 25;
- [Header("Debug Settings")]
- public bool showDebugLogs = true;
- // Events
- public event System.Action OnLootingComplete;
- private List<LootableEnemy> lootableEnemies = new List<LootableEnemy>();
- private bool isLootingActive = false;
- private VisualElement rootElement;
- private bool takeAllPressed = false;
- /// <summary>
- /// Gets whether the looting process is currently active
- /// </summary>
- public bool IsLootingActive => isLootingActive;
- [System.Serializable]
- public class LootableEnemy
- {
- public string enemyName;
- public List<string> dropItems = new List<string>();
- public int goldReward;
- public int silverReward;
- public int copperReward;
- public bool hasBeenLooted = false;
- public Vector3 corpsePosition;
- public LootableEnemy(string name, Vector3 position)
- {
- enemyName = name;
- corpsePosition = position;
- }
- }
- [System.Serializable]
- public class LootableItem
- {
- public string itemName;
- public string description;
- public int weight = 1;
- public int value = 1; // In copper
- public bool isSelected = false;
- public LootableItem(string name, string desc, int itemWeight = 1, int itemValue = 1)
- {
- itemName = name;
- description = desc;
- weight = itemWeight;
- value = itemValue;
- }
- }
- /// <summary>
- /// Initialize looting system with defeated enemies
- /// </summary>
- public void InitializeLootSystem(List<GameObject> defeatedEnemies)
- {
- lootableEnemies.Clear();
- foreach (var enemy in defeatedEnemies)
- {
- if (enemy == null) continue;
- Character enemyCharacter = enemy.GetComponent<Character>();
- if (enemyCharacter == null || !enemyCharacter.IsDead) continue;
- var lootableEnemy = new LootableEnemy(enemyCharacter.CharacterName, enemy.transform.position);
- // Generate loot based on enemy type and random factors
- GenerateEnemyLoot(lootableEnemy, enemyCharacter);
- lootableEnemies.Add(lootableEnemy);
- }
- if (showDebugLogs)
- Debug.Log($"💰 Initialized loot system with {lootableEnemies.Count} lootable enemies");
- }
- /// <summary>
- /// Show the loot UI and start looting phase
- /// </summary>
- public void StartLooting()
- {
- if (lootableEnemies.Count == 0)
- {
- if (showDebugLogs)
- Debug.Log("💰 No enemies to loot, ending battle");
- OnLootingComplete?.Invoke();
- return;
- }
- isLootingActive = true;
- CreateAndShowLootUI();
- if (showDebugLogs)
- Debug.Log("💰 Started post-battle looting phase");
- }
- /// <summary>
- /// Create and show the UI Toolkit loot interface
- /// </summary>
- private void CreateAndShowLootUI()
- {
- // Find or create UI Document
- if (lootUIDocument == null)
- {
- GameObject uiGO = new GameObject("LootUIDocument");
- uiGO.transform.SetParent(transform);
- lootUIDocument = uiGO.AddComponent<UIDocument>();
- }
- // Set up the UI Document with proper references
- SetupLootUIDocument();
- // Get the root element
- if (lootUIDocument.visualTreeAsset != null)
- {
- rootElement = lootUIDocument.rootVisualElement;
- // Show the overlay
- var overlay = rootElement.Q<VisualElement>("LootScreenOverlay");
- if (overlay != null)
- {
- overlay.style.display = DisplayStyle.Flex;
- }
- // Populate the UI with loot data
- PopulateLootUI();
- // Set up button callbacks
- SetupUICallbacks();
- }
- else
- {
- // Fallback - create basic UI if template loading failed
- Debug.LogWarning("PostBattleLootScreen.uxml not found. Creating basic UI.");
- CreateBasicLootUI();
- }
- }
- /// <summary>
- /// Set up the UIDocument with proper UXML template and panel settings
- /// </summary>
- private void SetupLootUIDocument()
- {
- if (lootUIDocument == null) return;
- // Load the UXML template if not assigned
- if (lootScreenTemplate == null)
- {
- lootScreenTemplate = Resources.Load<VisualTreeAsset>("UI/BattleSceneUI/PostBattleLootScreen");
- if (lootScreenTemplate == null)
- {
- #if UNITY_EDITOR
- // Try alternative path in editor
- lootScreenTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/BattleSceneUI/PostBattleLootScreen.uxml");
- #endif
- }
- }
- // Load panel settings if not assigned
- if (panelSettings == null)
- {
- panelSettings = Resources.Load<PanelSettings>("MainSettings");
- if (panelSettings == null)
- {
- // Try alternative panel settings
- panelSettings = Resources.Load<PanelSettings>("UI/TravelPanelSettings");
- if (panelSettings == null)
- {
- // Try to find any PanelSettings in the project
- var allPanelSettings = Resources.FindObjectsOfTypeAll<PanelSettings>();
- if (allPanelSettings.Length > 0)
- panelSettings = allPanelSettings[0];
- }
- }
- }
- // Configure the UIDocument
- lootUIDocument.visualTreeAsset = lootScreenTemplate;
- lootUIDocument.panelSettings = panelSettings;
- // Load and apply stylesheet
- var stylesheet = Resources.Load<StyleSheet>("UI/BattleSceneUI/PostBattleLootScreen");
- if (stylesheet == null)
- {
- #if UNITY_EDITOR
- stylesheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/BattleSceneUI/PostBattleLootScreen.uss");
- #endif
- }
- if (stylesheet != null && lootUIDocument.rootVisualElement != null)
- {
- lootUIDocument.rootVisualElement.styleSheets.Add(stylesheet);
- }
- if (lootScreenTemplate == null)
- {
- Debug.LogError("PostBattleLootSystem: Could not load PostBattleLootScreen.uxml template!");
- }
- if (panelSettings == null)
- {
- Debug.LogWarning("PostBattleLootSystem: No PanelSettings found. UI may not display correctly.");
- }
- }
- /// <summary>
- /// Create a basic fallback UI if the UXML template isn't available
- /// </summary>
- private void CreateBasicLootUI()
- {
- // Create a simple overlay using UI Toolkit elements
- rootElement = lootUIDocument.rootVisualElement;
- // Create overlay
- var overlay = new VisualElement();
- overlay.name = "LootScreenOverlay";
- overlay.style.position = Position.Absolute;
- overlay.style.top = 0;
- overlay.style.left = 0;
- overlay.style.right = 0;
- overlay.style.bottom = 0;
- overlay.style.backgroundColor = new Color(0, 0, 0, 0.8f);
- overlay.style.justifyContent = Justify.Center;
- overlay.style.alignItems = Align.Center;
- // Create background panel
- var background = new VisualElement();
- background.style.backgroundColor = new Color(0.1f, 0.1f, 0.2f, 0.95f);
- background.style.borderTopWidth = 2;
- background.style.borderBottomWidth = 2;
- background.style.borderLeftWidth = 2;
- background.style.borderRightWidth = 2;
- background.style.borderTopColor = new Color(0.7f, 0.5f, 0.2f);
- background.style.borderBottomColor = new Color(0.7f, 0.5f, 0.2f);
- background.style.borderLeftColor = new Color(0.7f, 0.5f, 0.2f);
- background.style.borderRightColor = new Color(0.7f, 0.5f, 0.2f);
- background.style.borderTopLeftRadius = 15;
- background.style.borderTopRightRadius = 15;
- background.style.borderBottomLeftRadius = 15;
- background.style.borderBottomRightRadius = 15;
- background.style.paddingTop = 30;
- background.style.paddingBottom = 30;
- background.style.paddingLeft = 30;
- background.style.paddingRight = 30;
- background.style.width = new Length(80, LengthUnit.Percent);
- background.style.maxWidth = 800;
- // Add title
- var title = new Label("🏆 VICTORY! 🏆");
- title.style.fontSize = 36;
- title.style.color = new Color(1f, 0.84f, 0f);
- title.style.unityTextAlign = TextAnchor.MiddleCenter;
- title.style.marginBottom = 20;
- // Add loot info
- var lootInfo = new Label();
- lootInfo.name = "LootInfo";
- lootInfo.style.fontSize = 14;
- lootInfo.style.color = Color.white;
- lootInfo.style.whiteSpace = WhiteSpace.Normal;
- lootInfo.style.marginBottom = 20;
- // Add continue button
- var continueButton = new Button(() => CompleteLootingProcess());
- continueButton.text = "Continue";
- continueButton.name = "ContinueButton";
- continueButton.style.fontSize = 16;
- continueButton.style.paddingTop = 10;
- continueButton.style.paddingBottom = 10;
- continueButton.style.paddingLeft = 20;
- continueButton.style.paddingRight = 20;
- // Assemble the UI
- background.Add(title);
- background.Add(lootInfo);
- background.Add(continueButton);
- overlay.Add(background);
- rootElement.Add(overlay);
- // Populate basic loot info
- PopulateBasicLootInfo(lootInfo);
- }
- /// <summary>
- /// Set up UI element callbacks for the loot interface
- /// </summary>
- private void SetupUICallbacks()
- {
- if (rootElement == null) return;
- // Set up Take All button
- var takeAllButton = rootElement.Q<Button>("TakeAllButton");
- if (takeAllButton != null)
- {
- takeAllButton.clicked += () =>
- {
- takeAllPressed = true;
- AutoLootAll();
- CompleteLootingProcess();
- };
- }
- // Set up Continue button
- var continueButton = rootElement.Q<Button>("ContinueButton");
- if (continueButton != null)
- {
- continueButton.clicked += () =>
- {
- if (!takeAllPressed)
- {
- AutoLootAll(); // Auto-loot if not already done
- }
- CompleteLootingProcess();
- };
- }
- // Set up keyboard input for space key
- rootElement.RegisterCallback<KeyDownEvent>(OnKeyDown);
- // Make sure the root element can receive focus for keyboard events
- rootElement.focusable = true;
- rootElement.Focus();
- }
- /// <summary>
- /// Handle keyboard input for the loot UI
- /// </summary>
- private void OnKeyDown(KeyDownEvent evt)
- {
- if (evt.keyCode == KeyCode.Space)
- {
- if (!takeAllPressed)
- {
- AutoLootAll();
- }
- CompleteLootingProcess();
- }
- }
- /// <summary>
- /// Populate basic loot information for fallback UI
- /// </summary>
- private void PopulateBasicLootInfo(Label lootInfo)
- {
- var lootText = "Collecting loot from defeated enemies...\n\n";
- int totalGold = 0, totalSilver = 0, totalCopper = 0;
- List<string> allItems = new List<string>();
- foreach (var enemy in lootableEnemies)
- {
- totalGold += enemy.goldReward;
- totalSilver += enemy.silverReward;
- totalCopper += enemy.copperReward;
- allItems.AddRange(enemy.dropItems);
- lootText += $"💀 {enemy.enemyName}: {enemy.goldReward}g {enemy.silverReward}s {enemy.copperReward}c\n";
- foreach (var item in enemy.dropItems)
- {
- lootText += $" 📦 {item}\n";
- }
- }
- lootText += $"\n💰 Total: {totalGold} gold, {totalSilver} silver, {totalCopper} copper\n";
- lootText += $"📦 {allItems.Count} items collected\n\n";
- lootText += "Click Continue to proceed or press SPACE...";
- lootInfo.text = lootText;
- }
- /// <summary>
- /// Show a temporary on-screen message for looting
- /// </summary>
- private System.Collections.IEnumerator ShowLootingMessage()
- {
- // Create a temporary UI GameObject
- GameObject tempUI = new GameObject("TempLootUI");
- tempUI.transform.SetParent(FindFirstObjectByType<Canvas>()?.transform, false);
- // Add background panel
- var canvasGroup = tempUI.AddComponent<CanvasGroup>();
- var image = tempUI.AddComponent<UnityEngine.UI.Image>();
- image.color = new Color(0, 0, 0, 0.8f); // Semi-transparent black
- // Set full screen size
- var rectTransform = tempUI.GetComponent<RectTransform>();
- rectTransform.anchorMin = Vector2.zero;
- rectTransform.anchorMax = Vector2.one;
- rectTransform.offsetMin = Vector2.zero;
- rectTransform.offsetMax = Vector2.zero;
- // Add text
- GameObject textObj = new GameObject("LootText");
- textObj.transform.SetParent(tempUI.transform, false);
- var text = textObj.AddComponent<UnityEngine.UI.Text>();
- text.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
- text.fontSize = 24;
- text.color = Color.white;
- text.alignment = TextAnchor.MiddleCenter;
- // Set text content
- string lootText = "🏆 VICTORY! 🏆\n\n";
- lootText += "Collecting loot from defeated enemies...\n\n";
- int totalGold = 0, totalSilver = 0, totalCopper = 0;
- List<string> allItems = new List<string>();
- foreach (var enemy in lootableEnemies)
- {
- totalGold += enemy.goldReward;
- totalSilver += enemy.silverReward;
- totalCopper += enemy.copperReward;
- allItems.AddRange(enemy.dropItems);
- lootText += $"💀 {enemy.enemyName}: {enemy.goldReward}g {enemy.silverReward}s {enemy.copperReward}c\n";
- foreach (var item in enemy.dropItems)
- {
- lootText += $" 📦 {item}\n";
- }
- }
- lootText += $"\n💰 Total: {totalGold} gold, {totalSilver} silver, {totalCopper} copper\n";
- lootText += $"📦 {allItems.Count} items collected\n\n";
- lootText += "Press SPACE to continue...";
- text.text = lootText;
- // Set text position
- var textRect = textObj.GetComponent<RectTransform>();
- textRect.anchorMin = Vector2.zero;
- textRect.anchorMax = Vector2.one;
- textRect.offsetMin = new Vector2(50, 50);
- textRect.offsetMax = new Vector2(-50, -50);
- // Auto-loot everything
- AutoLootAll();
- // Wait for space key or 5 seconds
- float timer = 0f;
- while (timer < 5f && !Input.GetKeyDown(KeyCode.Space))
- {
- timer += Time.deltaTime;
- yield return null;
- }
- // Cleanup UI
- if (tempUI != null)
- Destroy(tempUI);
- // Complete looting
- CompleteLootingProcess();
- }
- /// <summary>
- /// Complete the looting process and trigger the callback
- /// </summary>
- private void CompleteLootingProcess()
- {
- isLootingActive = false;
- if (showDebugLogs)
- Debug.Log("💰 Looting completed, triggering OnLootingComplete");
- OnLootingComplete?.Invoke();
- }
- /// <summary>
- /// Generate loot for a defeated enemy
- /// </summary>
- private void GenerateEnemyLoot(LootableEnemy lootableEnemy, Character enemyCharacter)
- {
- // Base currency rewards
- lootableEnemy.goldReward = Random.Range(0, baseGoldReward + 1);
- lootableEnemy.silverReward = Random.Range(0, baseSilverReward + 1);
- lootableEnemy.copperReward = Random.Range(baseCopperReward - 5, baseCopperReward + 10);
- // Basic item drops based on enemy type
- GenerateBasicDrops(lootableEnemy, enemyCharacter.CharacterName);
- // Try to get drops from enemy data if available
- TryGetEnemyDataDrops(lootableEnemy, enemyCharacter);
- if (showDebugLogs)
- {
- Debug.Log($"💰 Generated loot for {lootableEnemy.enemyName}: " +
- $"{lootableEnemy.goldReward}g {lootableEnemy.silverReward}s {lootableEnemy.copperReward}c, " +
- $"{lootableEnemy.dropItems.Count} items");
- }
- }
- /// <summary>
- /// Generate basic drops based on enemy name/type
- /// </summary>
- private void GenerateBasicDrops(LootableEnemy lootableEnemy, string enemyName)
- {
- string lowerName = enemyName.ToLower();
- // Skeleton-type enemies
- if (lowerName.Contains("skeleton"))
- {
- if (Random.Range(0f, 1f) < 0.3f) lootableEnemy.dropItems.Add("Bone");
- if (Random.Range(0f, 1f) < 0.2f) lootableEnemy.dropItems.Add("Rusty Sword");
- if (Random.Range(0f, 1f) < 0.15f) lootableEnemy.dropItems.Add("Bone Dust");
- }
- // Bandit-type enemies
- else if (lowerName.Contains("bandit") || lowerName.Contains("thief"))
- {
- if (Random.Range(0f, 1f) < 0.4f) lootableEnemy.dropItems.Add("Thieves' Tools");
- if (Random.Range(0f, 1f) < 0.3f) lootableEnemy.dropItems.Add("Rope");
- if (Random.Range(0f, 1f) < 0.2f) lootableEnemy.dropItems.Add("Dagger");
- // Bandits often have extra coin
- lootableEnemy.copperReward += Random.Range(5, 15);
- }
- // Orc-type enemies
- else if (lowerName.Contains("orc") || lowerName.Contains("goblin"))
- {
- if (Random.Range(0f, 1f) < 0.3f) lootableEnemy.dropItems.Add("Crude Axe");
- if (Random.Range(0f, 1f) < 0.25f) lootableEnemy.dropItems.Add("Hide Armor");
- if (Random.Range(0f, 1f) < 0.2f) lootableEnemy.dropItems.Add("Iron Ration");
- }
- // Default/unknown enemies
- else
- {
- if (Random.Range(0f, 1f) < 0.2f) lootableEnemy.dropItems.Add("Leather Scraps");
- if (Random.Range(0f, 1f) < 0.15f) lootableEnemy.dropItems.Add("Iron Ration");
- }
- // Common drops for all enemies
- if (Random.Range(0f, 1f) < 0.1f) lootableEnemy.dropItems.Add("Health Potion");
- if (Random.Range(0f, 1f) < 0.05f) lootableEnemy.dropItems.Add("Bandage");
- }
- /// <summary>
- /// Try to get drops from EnemyCharacterData if available
- /// </summary>
- private void TryGetEnemyDataDrops(LootableEnemy lootableEnemy, Character enemyCharacter)
- {
- // This would integrate with the EnemyCharacterData system
- // For now, we'll use the basic drop system above
- // TODO: Integrate with EnemyCharacterData.dropTable when available
- }
- /// <summary>
- /// Show the loot UI
- /// </summary>
- private void ShowLootUI()
- {
- if (rootElement != null)
- {
- // Show the UI Toolkit loot interface
- rootElement.style.display = DisplayStyle.Flex;
- PopulateLootUI();
- }
- else
- {
- // Fallback to console-based looting for now
- Debug.Log("💰 === POST-BATTLE LOOT ===");
- foreach (var enemy in lootableEnemies)
- {
- Debug.Log($"💰 {enemy.enemyName}: {enemy.goldReward}g {enemy.silverReward}s {enemy.copperReward}c");
- foreach (var item in enemy.dropItems)
- {
- Debug.Log($"💰 - {item}");
- }
- }
- Debug.Log("💰 ========================");
- // Auto-loot everything for now
- AutoLootAll();
- }
- }
- /// <summary>
- /// Populate the loot UI with available items
- /// </summary>
- private void PopulateLootUI()
- {
- if (rootElement == null) return;
- // Calculate totals first
- int totalGold = 0, totalSilver = 0, totalCopper = 0;
- List<string> allItems = new List<string>();
- foreach (var enemy in lootableEnemies)
- {
- totalGold += enemy.goldReward;
- totalSilver += enemy.silverReward;
- totalCopper += enemy.copperReward;
- allItems.AddRange(enemy.dropItems);
- }
- // Update currency displays
- var goldLabel = rootElement.Q<Label>("GoldAmount");
- var silverLabel = rootElement.Q<Label>("SilverAmount");
- var copperLabel = rootElement.Q<Label>("CopperAmount");
- if (goldLabel != null) goldLabel.text = totalGold.ToString();
- if (silverLabel != null) silverLabel.text = totalSilver.ToString();
- if (copperLabel != null) copperLabel.text = totalCopper.ToString();
- // Update item count
- var itemCountLabel = rootElement.Q<Label>("ItemCount");
- if (itemCountLabel != null)
- itemCountLabel.text = $"{allItems.Count} items";
- // Populate enemy loot sections
- var enemyLootContainer = rootElement.Q<VisualElement>("EnemyLootContainer");
- if (enemyLootContainer != null)
- {
- enemyLootContainer.Clear();
- foreach (var enemy in lootableEnemies)
- {
- var enemySection = new VisualElement();
- enemySection.AddToClassList("enemy-loot-section");
- // Enemy header
- var enemyHeader = new Label($"💀 {enemy.enemyName}");
- enemyHeader.AddToClassList("enemy-name");
- enemySection.Add(enemyHeader);
- // Enemy currency
- if (enemy.goldReward > 0 || enemy.silverReward > 0 || enemy.copperReward > 0)
- {
- var currencyContainer = new VisualElement();
- currencyContainer.AddToClassList("enemy-currency");
- if (enemy.goldReward > 0)
- {
- var enemyGoldLabel = new Label($"🪙 {enemy.goldReward}");
- enemyGoldLabel.AddToClassList("currency-gold");
- currencyContainer.Add(enemyGoldLabel);
- }
- if (enemy.silverReward > 0)
- {
- var enemySilverLabel = new Label($"🪙 {enemy.silverReward}");
- enemySilverLabel.AddToClassList("currency-silver");
- currencyContainer.Add(enemySilverLabel);
- }
- if (enemy.copperReward > 0)
- {
- var enemyCopperLabel = new Label($"🪙 {enemy.copperReward}");
- enemyCopperLabel.AddToClassList("currency-copper");
- currencyContainer.Add(enemyCopperLabel);
- }
- enemySection.Add(currencyContainer);
- }
- // Enemy items
- if (enemy.dropItems != null && enemy.dropItems.Count > 0)
- {
- var itemsContainer = new VisualElement();
- itemsContainer.AddToClassList("enemy-items");
- foreach (var item in enemy.dropItems)
- {
- var itemLabel = new Label($"📦 {item}");
- itemLabel.AddToClassList("item-entry");
- itemsContainer.Add(itemLabel);
- }
- enemySection.Add(itemsContainer);
- }
- enemyLootContainer.Add(enemySection);
- }
- }
- }
- /// <summary>
- /// Auto-loot all items and currency (temporary solution)
- /// </summary>
- private void AutoLootAll()
- {
- int totalGold = 0, totalSilver = 0, totalCopper = 0;
- List<string> allItems = new List<string>();
- foreach (var enemy in lootableEnemies)
- {
- if (!enemy.hasBeenLooted)
- {
- totalGold += enemy.goldReward;
- totalSilver += enemy.silverReward;
- totalCopper += enemy.copperReward;
- allItems.AddRange(enemy.dropItems);
- enemy.hasBeenLooted = true;
- }
- }
- // Distribute rewards to players
- DistributeRewards(totalGold, totalSilver, totalCopper, allItems);
- if (showDebugLogs)
- {
- Debug.Log($"💰 Auto-looted: {totalGold}g {totalSilver}s {totalCopper}c and {allItems.Count} items");
- }
- // End looting phase
- FinishLooting();
- }
- /// <summary>
- /// Distribute looted rewards among surviving players
- /// </summary>
- private void DistributeRewards(int gold, int silver, int copper, List<string> items)
- {
- // Get surviving players
- var survivingPlayers = GetSurvivingPlayers();
- if (survivingPlayers.Count == 0)
- {
- Debug.LogWarning("💰 No surviving players to distribute loot to!");
- return;
- }
- // Distribute currency evenly
- int goldPerPlayer = gold / survivingPlayers.Count;
- int silverPerPlayer = silver / survivingPlayers.Count;
- int copperPerPlayer = copper / survivingPlayers.Count;
- // Handle remainder
- int goldRemainder = gold % survivingPlayers.Count;
- int silverRemainder = silver % survivingPlayers.Count;
- int copperRemainder = copper % survivingPlayers.Count;
- for (int i = 0; i < survivingPlayers.Count; i++)
- {
- var player = survivingPlayers[i];
- Character playerCharacter = player.GetComponent<Character>();
- if (playerCharacter == null) continue;
- // Get player's bank (assuming it exists)
- var bank = playerCharacter.GetComponent<Bank>();
- if (bank != null)
- {
- bank.gold += goldPerPlayer + (i < goldRemainder ? 1 : 0);
- bank.silver += silverPerPlayer + (i < silverRemainder ? 1 : 0);
- bank.copper += copperPerPlayer + (i < copperRemainder ? 1 : 0);
- }
- // Distribute items (simple round-robin for now)
- var inventory = playerCharacter.GetComponent<Inventory>();
- if (inventory != null)
- {
- for (int j = i; j < items.Count; j += survivingPlayers.Count)
- {
- // TODO: Create proper Item objects instead of strings
- // For now, add to string-based inventory if available
- AddItemToPlayer(playerCharacter, items[j]);
- }
- }
- if (showDebugLogs)
- {
- int finalGold = goldPerPlayer + (i < goldRemainder ? 1 : 0);
- int finalSilver = silverPerPlayer + (i < silverRemainder ? 1 : 0);
- int finalCopper = copperPerPlayer + (i < copperRemainder ? 1 : 0);
- Debug.Log($"💰 {playerCharacter.CharacterName} received: {finalGold}g {finalSilver}s {finalCopper}c");
- }
- }
- }
- /// <summary>
- /// Add an item to a player's inventory
- /// </summary>
- private void AddItemToPlayer(Character player, string itemName)
- {
- // Try to add to CombatDataTransfer session data
- if (CombatDataTransfer.HasValidSession())
- {
- var session = CombatDataTransfer.GetCurrentSession();
- var playerData = session.playerTeam.Find(p =>
- p.characterName == player.CharacterName ||
- player.CharacterName.StartsWith(p.characterName));
- if (playerData != null)
- {
- if (playerData.miscItems == null)
- playerData.miscItems = new List<string>();
- playerData.miscItems.Add(itemName);
- if (showDebugLogs)
- Debug.Log($"💰 Added {itemName} to {player.CharacterName}'s inventory");
- return;
- }
- }
- // Fallback: log that item would be added
- if (showDebugLogs)
- Debug.Log($"💰 Would add {itemName} to {player.CharacterName} (no inventory system found)");
- }
- /// <summary>
- /// Get list of surviving player characters
- /// </summary>
- private List<GameObject> GetSurvivingPlayers()
- {
- var gameManager = GameManager.Instance;
- if (gameManager == null) return new List<GameObject>();
- return gameManager.playerCharacters
- .Where(p => p != null)
- .Where(p =>
- {
- var character = p.GetComponent<Character>();
- return character != null && !character.IsDead;
- })
- .ToList();
- }
- /// <summary>
- /// Complete the looting phase
- /// </summary>
- private void FinishLooting()
- {
- isLootingActive = false;
- if (rootElement != null)
- rootElement.style.display = DisplayStyle.None;
- OnLootingComplete?.Invoke();
- if (showDebugLogs)
- Debug.Log("💰 Looting phase completed");
- }
- /// <summary>
- /// Skip looting and proceed to battle end
- /// </summary>
- public void SkipLooting()
- {
- if (showDebugLogs)
- Debug.Log("💰 Skipping looting phase");
- FinishLooting();
- }
- /// <summary>
- /// Check if all enemies have been looted
- /// </summary>
- public bool AllEnemiesLooted()
- {
- return lootableEnemies.All(e => e.hasBeenLooted);
- }
- /// <summary>
- /// Get total weight of all available loot
- /// </summary>
- public int GetTotalLootWeight()
- {
- // TODO: Implement when item weight system is added
- return lootableEnemies.Sum(e => e.dropItems.Count); // Placeholder: 1 weight per item
- }
- /// <summary>
- /// Get total value of all available loot in copper
- /// </summary>
- public int GetTotalLootValue()
- {
- int totalValue = 0;
- foreach (var enemy in lootableEnemies)
- {
- totalValue += enemy.goldReward * 100; // 1 gold = 100 copper
- totalValue += enemy.silverReward * 10; // 1 silver = 10 copper
- totalValue += enemy.copperReward;
- // TODO: Add item values when item system is integrated
- }
- return totalValue;
- }
- }
|