CombatDataTransfer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. /// <summary>
  4. /// Static data transfer class for passing combat-related data between scenes
  5. /// Handles team data, enemy data, terrain information, and battle context
  6. /// </summary>
  7. public static class CombatDataTransfer
  8. {
  9. [System.Serializable]
  10. public class CombatSessionData
  11. {
  12. [Header("Battle Context")]
  13. public string battleDescription = "";
  14. public Vector2Int battleLocation = Vector2Int.zero;
  15. public TerrainType battleTerrain = TerrainType.Plains;
  16. public FeatureType battleFeature = FeatureType.None;
  17. [Header("Team Data")]
  18. public List<TeamCharacterCombatData> playerTeam = new List<TeamCharacterCombatData>();
  19. [Header("Enemy Data")]
  20. public List<EnemyCombatData> enemies = new List<EnemyCombatData>();
  21. [Header("Environmental Settings")]
  22. public Weather weather = Weather.Clear;
  23. public float timeOfDay = 12f; // 0-24 hours
  24. public CombatSessionData()
  25. {
  26. playerTeam = new List<TeamCharacterCombatData>();
  27. enemies = new List<EnemyCombatData>();
  28. }
  29. }
  30. [System.Serializable]
  31. public class TeamCharacterCombatData
  32. {
  33. public string characterName = "";
  34. public bool isMale = true;
  35. // Core stats
  36. public int strength = 10;
  37. public int dexterity = 10;
  38. public int constitution = 10;
  39. public int wisdom = 10;
  40. public int perception = 10;
  41. // Combat stats
  42. public int maxHealth = 20;
  43. public int currentHealth = 20;
  44. public int armorClass = 10;
  45. // Equipment
  46. public string equippedWeapon = "Sword"; // Keep for backward compatibility
  47. public WeaponItem equippedWeaponItem = null; // NEW: Actual weapon item reference
  48. public string equippedArmor = "";
  49. public List<string> availableWeapons = new List<string>();
  50. public List<string> availableArmor = new List<string>();
  51. // Resources
  52. public int gold = 25;
  53. public int silver = 0;
  54. public int copper = 0;
  55. public TeamCharacterCombatData()
  56. {
  57. availableWeapons = new List<string>();
  58. availableArmor = new List<string>();
  59. }
  60. /// <summary>
  61. /// Create combat data from a TeamCharacter
  62. /// </summary>
  63. public static TeamCharacterCombatData FromTeamCharacter(TeamCharacter teamChar)
  64. {
  65. var combatData = new TeamCharacterCombatData();
  66. if (teamChar != null)
  67. {
  68. combatData.characterName = teamChar.name;
  69. combatData.isMale = teamChar.isMale;
  70. combatData.strength = teamChar.strength;
  71. combatData.dexterity = teamChar.dexterity;
  72. combatData.constitution = teamChar.constitution;
  73. combatData.wisdom = teamChar.wisdom;
  74. combatData.perception = teamChar.perception;
  75. combatData.gold = teamChar.gold;
  76. combatData.silver = teamChar.silver;
  77. combatData.copper = teamChar.copper;
  78. // Ensure equipped weapon is not empty, fallback to first available or "Fists"
  79. combatData.equippedWeapon = !string.IsNullOrEmpty(teamChar.equippedWeapon)
  80. ? teamChar.equippedWeapon
  81. : (teamChar.weapons != null && teamChar.weapons.Count > 0)
  82. ? teamChar.weapons[0]
  83. : "Fists";
  84. Debug.Log($"🔧 FromTeamCharacter: Character '{teamChar.name}' - equippedWeapon: '{teamChar.equippedWeapon}', weapons list: [{(teamChar.weapons != null ? string.Join(", ", teamChar.weapons) : "null")}], resolved to: '{combatData.equippedWeapon}'");
  85. // Try to find the actual WeaponItem for the equipped weapon
  86. combatData.equippedWeaponItem = FindWeaponItem(combatData.equippedWeapon);
  87. if (combatData.equippedWeaponItem != null)
  88. {
  89. Debug.Log($"🔧 Team character {teamChar.name}: Found WeaponItem '{combatData.equippedWeaponItem.itemName}' for weapon '{combatData.equippedWeapon}'");
  90. }
  91. else if (combatData.equippedWeapon != "Fists")
  92. {
  93. Debug.LogWarning($"⚠️ Team character {teamChar.name}: Could not find WeaponItem for '{combatData.equippedWeapon}' - will use string fallback");
  94. }
  95. combatData.equippedArmor = teamChar.equippedArmor;
  96. // Calculate derived stats
  97. combatData.maxHealth = 10 + (teamChar.constitution * 2); // HP formula
  98. combatData.currentHealth = combatData.maxHealth; // Start at full health
  99. combatData.armorClass = 10 + (teamChar.dexterity / 2 - 5); // AC formula
  100. // Copy equipment lists
  101. if (teamChar.weapons != null)
  102. combatData.availableWeapons.AddRange(teamChar.weapons);
  103. if (teamChar.armor != null)
  104. combatData.availableArmor.AddRange(teamChar.armor);
  105. }
  106. return combatData;
  107. }
  108. }
  109. [System.Serializable]
  110. public class EnemyCombatData
  111. {
  112. public string enemyName = "Bandit";
  113. public string enemyType = "Humanoid";
  114. public int maxHealth = 15;
  115. public int currentHealth = 15;
  116. public int armorClass = 12;
  117. public int threatLevel = 2;
  118. public string preferredWeapon = "Sword"; // Keep for backward compatibility
  119. public WeaponItem preferredWeaponItem = null; // NEW: Actual weapon item reference
  120. public EnemyCharacterData sourceData = null; // Reference to original data
  121. /// <summary>
  122. /// Create combat data from EnemyCharacterData
  123. /// </summary>
  124. public static EnemyCombatData FromEnemyData(EnemyCharacterData enemyData, int instanceNumber = 1)
  125. {
  126. var combatData = new EnemyCombatData();
  127. if (enemyData != null)
  128. {
  129. combatData.enemyName = $"{enemyData.enemyName}_{instanceNumber}";
  130. combatData.enemyType = enemyData.enemyName;
  131. combatData.maxHealth = enemyData.maxHealth;
  132. combatData.currentHealth = enemyData.maxHealth;
  133. combatData.armorClass = enemyData.armorClass;
  134. combatData.threatLevel = enemyData.threatLevel;
  135. // Extract weapon type properly from WeaponItem
  136. if (enemyData.preferredWeapon != null)
  137. {
  138. combatData.preferredWeapon = enemyData.preferredWeapon.weaponType.ToString();
  139. combatData.preferredWeaponItem = enemyData.preferredWeapon; // Store actual WeaponItem
  140. Debug.Log($"🔧 Enemy {enemyData.enemyName}: WeaponItem.weaponType = {enemyData.preferredWeapon.weaponType} -> '{combatData.preferredWeapon}'");
  141. }
  142. else
  143. {
  144. combatData.preferredWeapon = "Fists"; // Default fallback
  145. combatData.preferredWeaponItem = null;
  146. Debug.Log($"🔧 Enemy {enemyData.enemyName}: No preferredWeapon assigned -> defaulting to 'Fists'");
  147. }
  148. combatData.sourceData = enemyData;
  149. }
  150. return combatData;
  151. }
  152. }
  153. // Current combat session data
  154. private static CombatSessionData currentSession = null;
  155. /// <summary>
  156. /// Initialize a new combat session with the given data
  157. /// </summary>
  158. public static void InitializeCombatSession(BattleEventData battleData, TravelEventContext context, List<TeamCharacter> teamMembers)
  159. {
  160. currentSession = new CombatSessionData();
  161. // Set battle context
  162. if (context != null)
  163. {
  164. currentSession.battleLocation = context.currentPosition;
  165. currentSession.battleTerrain = context.currentTile?.terrainType ?? TerrainType.Plains;
  166. currentSession.battleFeature = context.currentTile?.featureType ?? FeatureType.None;
  167. currentSession.weather = context.currentWeather;
  168. currentSession.timeOfDay = context.timeOfDay;
  169. }
  170. // Set battle description
  171. if (battleData != null)
  172. {
  173. currentSession.battleDescription = battleData.battleDescription;
  174. }
  175. // Convert team members to combat data
  176. if (teamMembers != null)
  177. {
  178. foreach (var teamMember in teamMembers)
  179. {
  180. if (teamMember != null)
  181. {
  182. currentSession.playerTeam.Add(TeamCharacterCombatData.FromTeamCharacter(teamMember));
  183. }
  184. }
  185. }
  186. // Create enemy combat data
  187. if (battleData != null && battleData.enemyCharacterData != null)
  188. {
  189. for (int i = 0; i < battleData.enemyCount; i++)
  190. {
  191. currentSession.enemies.Add(EnemyCombatData.FromEnemyData(battleData.enemyCharacterData, i + 1));
  192. }
  193. }
  194. Debug.Log($"🎯 Combat session initialized: {currentSession.playerTeam.Count} players vs {currentSession.enemies.Count} enemies on {currentSession.battleTerrain} terrain");
  195. }
  196. /// <summary>
  197. /// Get the current combat session data
  198. /// </summary>
  199. public static CombatSessionData GetCurrentSession()
  200. {
  201. return currentSession;
  202. }
  203. /// <summary>
  204. /// Check if there's a valid combat session
  205. /// </summary>
  206. public static bool HasValidSession()
  207. {
  208. return currentSession != null &&
  209. currentSession.playerTeam.Count > 0 &&
  210. currentSession.enemies.Count > 0;
  211. }
  212. /// <summary>
  213. /// Clear the current combat session (call after battle ends)
  214. /// </summary>
  215. public static void ClearSession()
  216. {
  217. currentSession = null;
  218. Debug.Log("🧹 Combat session cleared");
  219. }
  220. /// <summary>
  221. /// Get terrain-appropriate description for battle setup
  222. /// </summary>
  223. public static string GetTerrainDescription(TerrainType terrain, FeatureType feature)
  224. {
  225. string baseDescription = terrain switch
  226. {
  227. TerrainType.Plains => "open grasslands",
  228. TerrainType.Forest => "dense woodland",
  229. TerrainType.Mountain => "rocky mountain terrain",
  230. TerrainType.River => "along a flowing river",
  231. TerrainType.Lake => "near a peaceful lake",
  232. TerrainType.Ocean => "along the coastline",
  233. TerrainType.Shore => "on sandy shores",
  234. _ => "unknown terrain"
  235. };
  236. string featureDescription = feature switch
  237. {
  238. FeatureType.Road => "on a well-traveled road",
  239. FeatureType.Bridge => "at a stone bridge",
  240. FeatureType.Town => "within town limits",
  241. FeatureType.Village => "near a small village",
  242. FeatureType.Tunnel => "in a dark tunnel",
  243. FeatureType.Ferry => "at a ferry crossing",
  244. FeatureType.Harbour => "at a busy harbor",
  245. _ => ""
  246. };
  247. if (!string.IsNullOrEmpty(featureDescription))
  248. {
  249. return $"{featureDescription} in {baseDescription}";
  250. }
  251. return $"in {baseDescription}";
  252. }
  253. /// <summary>
  254. /// Create legacy BattleSetupData for compatibility with existing battle scene
  255. /// </summary>
  256. public static void PopulateLegacyBattleSetupData()
  257. {
  258. if (!HasValidSession())
  259. {
  260. Debug.LogError("❌ No valid combat session to populate legacy battle setup data");
  261. return;
  262. }
  263. // Clear existing data
  264. BattleSetupData.playerSelections.Clear();
  265. BattleSetupData.enemySelections.Clear();
  266. // Populate player selections
  267. foreach (var player in currentSession.playerTeam)
  268. {
  269. string weaponType = !string.IsNullOrEmpty(player.equippedWeapon) ? player.equippedWeapon : "Fists";
  270. Debug.Log($"🔧 Player {player.characterName}: equippedWeapon='{player.equippedWeapon}' -> weaponType='{weaponType}'");
  271. BattleSetupData.playerSelections.Add(new CharacterSelection
  272. {
  273. characterName = player.characterName,
  274. weaponType = weaponType
  275. });
  276. }
  277. // Populate enemy selections
  278. foreach (var enemy in currentSession.enemies)
  279. {
  280. string weaponType = !string.IsNullOrEmpty(enemy.preferredWeapon) ? enemy.preferredWeapon : "Fists";
  281. Debug.Log($"🔧 Enemy {enemy.enemyName}: preferredWeapon='{enemy.preferredWeapon}' -> weaponType='{weaponType}'");
  282. BattleSetupData.enemySelections.Add(new CharacterSelection
  283. {
  284. characterName = enemy.enemyName,
  285. weaponType = weaponType
  286. });
  287. }
  288. Debug.Log($"✅ Legacy battle setup data populated: {BattleSetupData.playerSelections.Count} players, {BattleSetupData.enemySelections.Count} enemies");
  289. }
  290. /// <summary>
  291. /// Debug method to log current session information
  292. /// </summary>
  293. [System.Diagnostics.Conditional("UNITY_EDITOR")]
  294. public static void DebugLogSession()
  295. {
  296. if (currentSession == null)
  297. {
  298. Debug.Log("🔍 No active combat session");
  299. return;
  300. }
  301. Debug.Log("=== COMBAT SESSION DEBUG ===");
  302. Debug.Log($"📍 Location: {currentSession.battleLocation}");
  303. Debug.Log($"🌍 Terrain: {currentSession.battleTerrain} / {currentSession.battleFeature}");
  304. Debug.Log($"🌤️ Weather: {currentSession.weather} at {currentSession.timeOfDay:F1}h");
  305. Debug.Log($"👥 Players: {currentSession.playerTeam.Count}");
  306. foreach (var player in currentSession.playerTeam)
  307. {
  308. Debug.Log($" - {player.characterName} (HP: {player.currentHealth}/{player.maxHealth}, AC: {player.armorClass}, Weapon: {player.equippedWeapon})");
  309. }
  310. Debug.Log($"👹 Enemies: {currentSession.enemies.Count}");
  311. foreach (var enemy in currentSession.enemies)
  312. {
  313. Debug.Log($" - {enemy.enemyName} (HP: {enemy.currentHealth}/{enemy.maxHealth}, AC: {enemy.armorClass}, Threat: {enemy.threatLevel})");
  314. }
  315. Debug.Log("=== END COMBAT SESSION ===");
  316. }
  317. /// <summary>
  318. /// Helper method to find a WeaponItem by name or type
  319. /// </summary>
  320. private static WeaponItem FindWeaponItem(string weaponIdentifier)
  321. {
  322. if (string.IsNullOrEmpty(weaponIdentifier) || weaponIdentifier == "Fists")
  323. {
  324. Debug.Log($"🔍 FindWeaponItem: Skipping '{weaponIdentifier}' (null/empty/Fists)");
  325. return null;
  326. }
  327. Debug.Log($"🔍 FindWeaponItem: Looking for weapon '{weaponIdentifier}'");
  328. // Load all WeaponItem assets from Resources folders
  329. WeaponItem[] allWeapons = Resources.LoadAll<WeaponItem>("");
  330. Debug.Log($"🔍 FindWeaponItem: Found {allWeapons.Length} WeaponItem assets in Resources");
  331. // Debug: List all available weapons
  332. foreach (var weapon in allWeapons)
  333. {
  334. if (weapon != null)
  335. {
  336. Debug.Log($" 📋 Available weapon: '{weapon.itemName}' (type: {weapon.weaponType})");
  337. }
  338. }
  339. // First try exact name match
  340. foreach (var weapon in allWeapons)
  341. {
  342. if (weapon != null && string.Equals(weapon.itemName, weaponIdentifier, System.StringComparison.OrdinalIgnoreCase))
  343. {
  344. Debug.Log($"✅ FindWeaponItem: Found exact match for '{weaponIdentifier}' -> '{weapon.itemName}'");
  345. return weapon;
  346. }
  347. }
  348. Debug.Log($"⚠️ FindWeaponItem: No exact name match for '{weaponIdentifier}', trying weapon type match...");
  349. // Then try weapon type match
  350. if (System.Enum.TryParse<WeaponType>(weaponIdentifier, true, out WeaponType weaponType))
  351. {
  352. Debug.Log($"🔍 FindWeaponItem: Parsed '{weaponIdentifier}' as WeaponType.{weaponType}");
  353. // Look for a weapon of this type, prefer "Simple" variants
  354. WeaponItem simpleWeapon = null;
  355. WeaponItem anyWeapon = null;
  356. foreach (var weapon in allWeapons)
  357. {
  358. if (weapon != null && weapon.weaponType == weaponType)
  359. {
  360. anyWeapon = weapon; // Keep track of any weapon of this type
  361. Debug.Log($" 🎯 Found weapon of type {weaponType}: '{weapon.itemName}'");
  362. // Prefer simple/basic weapons
  363. if (weapon.itemName.ToLower().Contains("simple") || weapon.itemName.ToLower().Contains("basic"))
  364. {
  365. simpleWeapon = weapon;
  366. Debug.Log($" ⭐ Preferred simple weapon: '{weapon.itemName}'");
  367. break; // Found preferred weapon, stop searching
  368. }
  369. }
  370. }
  371. WeaponItem result = simpleWeapon ?? anyWeapon;
  372. if (result != null)
  373. {
  374. Debug.Log($"✅ FindWeaponItem: Found weapon by type '{weaponIdentifier}' -> '{result.itemName}'");
  375. }
  376. else
  377. {
  378. Debug.LogWarning($"❌ FindWeaponItem: No weapon found for type '{weaponType}'");
  379. }
  380. return result;
  381. }
  382. else
  383. {
  384. Debug.LogWarning($"❌ FindWeaponItem: Could not parse '{weaponIdentifier}' as WeaponType enum");
  385. }
  386. Debug.LogError($"❌ FindWeaponItem: No weapon found for '{weaponIdentifier}'");
  387. return null;
  388. }
  389. }