MainTeamSelectScript.cs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  1. using UnityEngine;
  2. using UnityEngine.UIElements; // Make sure you have this using directive
  3. using UnityEngine.SceneManagement; // Added for scene management
  4. using System.Collections.Generic; // Needed for List<>
  5. using System.Linq; // Needed for LINQ operations
  6. using System.Collections; // Needed for coroutines
  7. public class MainTeamSelectScript : MonoBehaviour
  8. {
  9. private UIDocument uiDocument;
  10. private TeamCharacter currentCharacter;
  11. private List<Button> characterSlotButtons = new List<Button>();
  12. private List<Button> createNewCharacterButtons = new List<Button>();
  13. // Character slot management
  14. private TeamCharacter[] characterSlots = new TeamCharacter[4]; // 4 character slots
  15. private int currentSlotIndex = -1; // -1 means no slot selected
  16. // UI elements
  17. private TextField characterNameField;
  18. private Button randomizeNameButton;
  19. private DropdownField genderDropdown;
  20. private IntegerField strengthField, dexterityField, constitutionField, wisdomField, perceptionField;
  21. private IntegerField initField, damageField, spellCastingField, movementSpeedField, hpField, acField;
  22. // Attribute management UI
  23. private Button randomizeAttributesButton;
  24. private Button resetToPointBuyButton;
  25. private Label availablePointsLabel;
  26. private Label creationModeLabel;
  27. // Inventory/Shop UI elements
  28. private Button addWeaponButton;
  29. private Button addArmorButton;
  30. private Button addMiscButton;
  31. private IntegerField goldField;
  32. private IntegerField silverField;
  33. private IntegerField copperField;
  34. private VisualElement weaponsList;
  35. private VisualElement armorList;
  36. private VisualElement miscList;
  37. // Shop reference
  38. private ItemShopManager shopManager;
  39. // Navigation buttons
  40. private Button backToTitleButton;
  41. private Button proceedToBattleButton;
  42. void Awake()
  43. {
  44. uiDocument = GetComponent<UIDocument>();
  45. if (uiDocument == null)
  46. {
  47. Debug.LogError("UIDocument component not found on this GameObject.", this);
  48. return; // Exit if no UIDocument is found
  49. }
  50. // Initialize character slots array
  51. characterSlots = new TeamCharacter[4];
  52. // Clear all existing character equipment to ensure shop-only acquisition
  53. ClearAllCharacterEquipment();
  54. // Start with no character selected (empty character sheet)
  55. currentCharacter = null;
  56. currentSlotIndex = -1;
  57. // Check if team has been finalized (proceeded to map)
  58. bool teamFinalized = IsTeamFinalized();
  59. // Load saved team if available
  60. LoadSavedTeamData();
  61. // Get UI element references
  62. GetUIElementReferences();
  63. // Set up event listeners
  64. SetupEventListeners();
  65. // Try to find missing UI elements one more time after everything is set up
  66. ValidateUIElements();
  67. // If team is finalized, disable editing and show message
  68. if (teamFinalized)
  69. {
  70. SetTeamFinalizedMode();
  71. }
  72. // Initialize UI with character data
  73. UpdateCharacterUI();
  74. UpdateSlotVisualStates();
  75. UpdateNavigationButtons();
  76. }
  77. private void ValidateUIElements()
  78. {
  79. // Final attempt to find critical UI elements that might have been missed
  80. if (proceedToBattleButton == null && uiDocument != null)
  81. {
  82. var root = uiDocument.rootVisualElement;
  83. Debug.LogWarning("Final attempt to find proceedToBattleButton...");
  84. // Try searching with different approaches
  85. proceedToBattleButton = root.Q<Button>("ProceedToBattleButton") ??
  86. root.Q<Button>("ProceedButton") ??
  87. root.Q<Button>("StartButton") ??
  88. root.Q<Button>(className: "proceed-button");
  89. // If still not found, search through all buttons for text matches
  90. if (proceedToBattleButton == null)
  91. {
  92. var allButtons = root.Query<Button>().ToList();
  93. foreach (var button in allButtons)
  94. {
  95. if (button.text.ToLower().Contains("proceed") ||
  96. button.text.ToLower().Contains("start") ||
  97. button.text.ToLower().Contains("battle"))
  98. {
  99. proceedToBattleButton = button;
  100. break;
  101. }
  102. }
  103. }
  104. if (proceedToBattleButton != null)
  105. {
  106. // Set up the event listener since we found it late
  107. proceedToBattleButton.clicked += OnProceedToBattleClicked;
  108. }
  109. else
  110. {
  111. Debug.LogError("CRITICAL: Could not find proceed button in UI! Please check the UI Document.");
  112. }
  113. }
  114. }
  115. private void GetUIElementReferences()
  116. {
  117. var root = uiDocument.rootVisualElement;
  118. // Character info fields
  119. characterNameField = root.Q<TextField>("CharacterNameField");
  120. randomizeNameButton = root.Q<Button>("RandomizeNameButton");
  121. genderDropdown = root.Q<DropdownField>("GenderDropdown");
  122. // Stat fields
  123. strengthField = root.Q<IntegerField>("StrengthValue");
  124. dexterityField = root.Q<IntegerField>("DexterityValue");
  125. constitutionField = root.Q<IntegerField>("ConstitutionValue");
  126. wisdomField = root.Q<IntegerField>("WisdomValue");
  127. perceptionField = root.Q<IntegerField>("PerceptionValue");
  128. // Derived stat fields
  129. initField = root.Q<IntegerField>("InitValue");
  130. damageField = root.Q<IntegerField>("DamageValue");
  131. spellCastingField = root.Q<IntegerField>("SpellCastingValue");
  132. movementSpeedField = root.Q<IntegerField>("MovementSpeedValue");
  133. hpField = root.Q<IntegerField>("HPValue");
  134. acField = root.Q<IntegerField>("ACValue");
  135. // Attribute management UI
  136. randomizeAttributesButton = root.Q<Button>("RandomizeAttributesButton");
  137. resetToPointBuyButton = root.Q<Button>("ResetToPointBuyButton");
  138. availablePointsLabel = root.Q<Label>("AvailablePointsLabel");
  139. creationModeLabel = root.Q<Label>("CreationModeLabel");
  140. // Find all buttons with the name "CreateNewCharacterButton"
  141. createNewCharacterButtons = uiDocument.rootVisualElement.Query<Button>("CreateNewCharacterButton").ToList();
  142. // Find all ViewCharacterButton buttons
  143. characterSlotButtons = uiDocument.rootVisualElement.Query<Button>("ViewCharacterButton").ToList();
  144. // Inventory/Shop UI elements
  145. addWeaponButton = root.Q<Button>("AddWeaponButton");
  146. addArmorButton = root.Q<Button>("AddArmourButton");
  147. addMiscButton = root.Q<Button>("AddMiscButton");
  148. goldField = root.Q<IntegerField>("GoldValue");
  149. silverField = root.Q<IntegerField>("SilverValue");
  150. copperField = root.Q<IntegerField>("CopperValue");
  151. weaponsList = root.Q<VisualElement>("WeaponsList");
  152. armorList = root.Q<VisualElement>("ArmourList");
  153. miscList = root.Q<VisualElement>("MiscList");
  154. // Navigation buttons
  155. backToTitleButton = root.Q<Button>("BackToTitleButton");
  156. proceedToBattleButton = root.Q<Button>("ProceedToBattleButton");
  157. // Debug and fallback for Back to Title button
  158. if (backToTitleButton == null)
  159. {
  160. Debug.LogWarning("BackToTitleButton not found! Creating fallback button...");
  161. // Create a simple fallback button
  162. backToTitleButton = new Button();
  163. backToTitleButton.text = "Back to Title";
  164. backToTitleButton.name = "BackToTitleButton_Fallback";
  165. backToTitleButton.style.position = Position.Absolute;
  166. backToTitleButton.style.top = 10;
  167. backToTitleButton.style.left = 10;
  168. backToTitleButton.style.width = 120;
  169. backToTitleButton.style.height = 30;
  170. root.Add(backToTitleButton);
  171. }
  172. // Find shop manager in scene
  173. shopManager = FindFirstObjectByType<ItemShopManager>();
  174. if (shopManager == null)
  175. {
  176. Debug.LogWarning("No ItemShopManager found in scene. Shop functionality will be limited.");
  177. Debug.LogWarning("Trying to refresh shop manager reference...");
  178. // Try again after a short delay to allow for potential late initialization
  179. StartCoroutine(RefreshShopManagerReference());
  180. }
  181. else
  182. {
  183. SetupShopManagerCallbacks();
  184. }
  185. // Check if any buttons were found
  186. if (createNewCharacterButtons.Count == 0)
  187. {
  188. Debug.LogWarning("No buttons with the name 'CreateNewCharacterButton' found in the UI Document.");
  189. }
  190. else
  191. {
  192. // Add a click listener to each button found
  193. foreach (Button button in createNewCharacterButtons)
  194. {
  195. // Example of passing data (requires adjusting the handler method):
  196. int characterIndex = createNewCharacterButtons.IndexOf(button); // Example data
  197. button.clicked += () => OnCreateNewCharacterButtonClicked(characterIndex);
  198. }
  199. }
  200. // Add click listeners to ViewCharacterButton buttons
  201. for (int i = 0; i < characterSlotButtons.Count; i++)
  202. {
  203. int index = i; // Capture the index for the closure
  204. characterSlotButtons[i].clicked += () => OnViewCharacterButtonClicked(index);
  205. }
  206. }
  207. private void SetupEventListeners()
  208. {
  209. // Name randomization
  210. if (randomizeNameButton != null)
  211. {
  212. randomizeNameButton.clicked += OnRandomizeNameClicked;
  213. }
  214. // Character name change
  215. if (characterNameField != null)
  216. {
  217. characterNameField.RegisterValueChangedCallback(OnCharacterNameChanged);
  218. }
  219. // Gender change
  220. if (genderDropdown != null)
  221. {
  222. genderDropdown.RegisterValueChangedCallback(OnGenderChanged);
  223. }
  224. // Stat changes
  225. if (strengthField != null)
  226. strengthField.RegisterValueChangedCallback(evt => OnStatChanged());
  227. if (dexterityField != null)
  228. dexterityField.RegisterValueChangedCallback(evt => OnStatChanged());
  229. if (constitutionField != null)
  230. constitutionField.RegisterValueChangedCallback(evt => OnStatChanged());
  231. if (wisdomField != null)
  232. wisdomField.RegisterValueChangedCallback(evt => OnStatChanged());
  233. if (perceptionField != null)
  234. perceptionField.RegisterValueChangedCallback(evt => OnStatChanged());
  235. // Attribute management
  236. if (randomizeAttributesButton != null)
  237. randomizeAttributesButton.clicked += OnRandomizeAttributesClicked;
  238. if (resetToPointBuyButton != null)
  239. resetToPointBuyButton.clicked += OnResetToPointBuyClicked;
  240. // Inventory/Shop management
  241. if (addWeaponButton != null)
  242. addWeaponButton.clicked += OnAddWeaponClicked;
  243. if (addArmorButton != null)
  244. addArmorButton.clicked += OnAddArmorClicked;
  245. if (addMiscButton != null)
  246. addMiscButton.clicked += OnAddMiscClicked;
  247. // Bank field changes
  248. if (goldField != null)
  249. goldField.RegisterValueChangedCallback(evt => OnBankChanged());
  250. if (silverField != null)
  251. silverField.RegisterValueChangedCallback(evt => OnBankChanged());
  252. if (copperField != null)
  253. copperField.RegisterValueChangedCallback(evt => OnBankChanged());
  254. // Navigation buttons
  255. if (backToTitleButton != null)
  256. backToTitleButton.clicked += OnBackToTitleClicked;
  257. if (proceedToBattleButton != null)
  258. proceedToBattleButton.clicked += OnProceedToBattleClicked;
  259. else
  260. Debug.LogWarning("proceedToBattleButton is null during SetupEventListeners - will try to set up event listener later");
  261. }
  262. private void OnRandomizeNameClicked()
  263. {
  264. if (currentCharacter == null) return;
  265. currentCharacter.GenerateRandomName();
  266. characterNameField.value = currentCharacter.name;
  267. // Update the slot button and save to slot
  268. UpdateCurrentSlotButton();
  269. SaveCurrentCharacterToSlot();
  270. }
  271. private void OnCharacterNameChanged(ChangeEvent<string> evt)
  272. {
  273. if (currentCharacter == null) return;
  274. currentCharacter.name = evt.newValue;
  275. // Update the slot button and save to slot
  276. UpdateCurrentSlotButton();
  277. SaveCurrentCharacterToSlot();
  278. // Update the character card if we have a current slot
  279. if (currentSlotIndex >= 0)
  280. {
  281. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  282. }
  283. }
  284. private void OnGenderChanged(ChangeEvent<string> evt)
  285. {
  286. if (currentCharacter == null) return;
  287. currentCharacter.SetGender(evt.newValue == "Male");
  288. // Optionally regenerate name when gender changes
  289. // You can remove this if you don't want automatic name regeneration
  290. currentCharacter.GenerateRandomName();
  291. characterNameField.value = currentCharacter.name;
  292. // Update the slot button and save to slot
  293. UpdateCurrentSlotButton();
  294. SaveCurrentCharacterToSlot();
  295. // Update the character card if we have a current slot
  296. if (currentSlotIndex >= 0)
  297. {
  298. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  299. }
  300. }
  301. private void OnStatChanged()
  302. {
  303. if (currentCharacter == null) return;
  304. // Validate point-buy constraints
  305. int newStr = strengthField?.value ?? currentCharacter.strength;
  306. int newDex = dexterityField?.value ?? currentCharacter.dexterity;
  307. int newCon = constitutionField?.value ?? currentCharacter.constitution;
  308. int newWis = wisdomField?.value ?? currentCharacter.wisdom;
  309. int newPer = perceptionField?.value ?? currentCharacter.perception;
  310. // Clamp values to valid range (4-18)
  311. newStr = Mathf.Clamp(newStr, 4, 18);
  312. newDex = Mathf.Clamp(newDex, 4, 18);
  313. newCon = Mathf.Clamp(newCon, 4, 18);
  314. newWis = Mathf.Clamp(newWis, 4, 18);
  315. newPer = Mathf.Clamp(newPer, 4, 18);
  316. // Check if the new combination is affordable
  317. int totalCost = TeamCharacter.GetStatCost(newStr) + TeamCharacter.GetStatCost(newDex) +
  318. TeamCharacter.GetStatCost(newCon) + TeamCharacter.GetStatCost(newWis) + TeamCharacter.GetStatCost(newPer);
  319. if (totalCost <= 22) // Changed from 18 to 22 for 5-stat system
  320. {
  321. // Update character stats from UI
  322. currentCharacter.strength = newStr;
  323. currentCharacter.dexterity = newDex;
  324. currentCharacter.constitution = newCon;
  325. currentCharacter.wisdom = newWis;
  326. currentCharacter.perception = newPer;
  327. currentCharacter.UpdateAvailablePoints();
  328. }
  329. else
  330. {
  331. // Reset to previous valid values
  332. if (strengthField != null) strengthField.value = currentCharacter.strength;
  333. if (dexterityField != null) dexterityField.value = currentCharacter.dexterity;
  334. if (constitutionField != null) constitutionField.value = currentCharacter.constitution;
  335. if (wisdomField != null) wisdomField.value = currentCharacter.wisdom;
  336. if (perceptionField != null) perceptionField.value = currentCharacter.perception;
  337. }
  338. // Update derived stats and point display
  339. UpdateDerivedStats();
  340. UpdateAttributeUI();
  341. SaveCurrentCharacterToSlot();
  342. UpdateNavigationButtons();
  343. // Update the character card if we have a current slot
  344. if (currentSlotIndex >= 0)
  345. {
  346. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  347. }
  348. }
  349. private void OnRandomizeAttributesClicked()
  350. {
  351. if (currentCharacter == null) return;
  352. currentCharacter.RandomizeAttributes();
  353. UpdateCharacterUI();
  354. UpdateAttributeUI();
  355. SaveCurrentCharacterToSlot();
  356. UpdateNavigationButtons();
  357. // Update the character card if we have a current slot
  358. if (currentSlotIndex >= 0)
  359. {
  360. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  361. }
  362. }
  363. private void OnResetToPointBuyClicked()
  364. {
  365. if (currentCharacter == null) return;
  366. currentCharacter.ResetToPointBuy();
  367. UpdateCharacterUI();
  368. UpdateAttributeUI();
  369. SaveCurrentCharacterToSlot();
  370. UpdateNavigationButtons();
  371. // Update the character card if we have a current slot
  372. if (currentSlotIndex >= 0)
  373. {
  374. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  375. }
  376. }
  377. private void OnAddWeaponClicked()
  378. {
  379. if (currentCharacter == null)
  380. {
  381. Debug.LogWarning("OnAddWeaponClicked: No current character selected");
  382. return;
  383. }
  384. // Open weapon shop for this character
  385. OpenWeaponShop();
  386. }
  387. private void OpenWeaponShop()
  388. {
  389. if (shopManager != null)
  390. {
  391. shopManager.OpenShop(currentCharacter);
  392. }
  393. else
  394. {
  395. Debug.LogWarning("No shop manager found - cannot open shop");
  396. }
  397. }
  398. private void AddWeaponToCharacter(string weaponType)
  399. {
  400. // Add weapon to character's inventory (would integrate with real shop/inventory system)
  401. if (currentCharacter.weapons == null)
  402. {
  403. currentCharacter.weapons = new System.Collections.Generic.List<string>();
  404. }
  405. currentCharacter.weapons.Add(weaponType);
  406. SaveCurrentCharacterToSlot();
  407. }
  408. private void OnAddArmorClicked()
  409. {
  410. if (currentCharacter == null) return;
  411. if (shopManager != null)
  412. {
  413. shopManager.OpenShop(currentCharacter);
  414. }
  415. else
  416. {
  417. Debug.LogWarning("No shop manager found - cannot open shop");
  418. }
  419. }
  420. private void OnAddMiscClicked()
  421. {
  422. if (currentCharacter == null) return;
  423. if (shopManager != null)
  424. {
  425. shopManager.OpenShop(currentCharacter);
  426. }
  427. else
  428. {
  429. Debug.LogWarning("No shop manager found - cannot open shop");
  430. }
  431. }
  432. private void AddArmorToCharacter(string armorType)
  433. {
  434. if (currentCharacter.armor == null)
  435. {
  436. currentCharacter.armor = new System.Collections.Generic.List<string>();
  437. }
  438. currentCharacter.armor.Add(armorType);
  439. SaveCurrentCharacterToSlot();
  440. UpdateInventoryUI();
  441. }
  442. private void AddMiscItemToCharacter(string itemType)
  443. {
  444. if (currentCharacter.miscItems == null)
  445. {
  446. currentCharacter.miscItems = new System.Collections.Generic.List<string>();
  447. }
  448. currentCharacter.miscItems.Add(itemType);
  449. SaveCurrentCharacterToSlot();
  450. UpdateInventoryUI();
  451. }
  452. private void OnBankChanged()
  453. {
  454. if (currentCharacter == null) return;
  455. currentCharacter.gold = goldField?.value ?? currentCharacter.gold;
  456. currentCharacter.silver = silverField?.value ?? currentCharacter.silver;
  457. currentCharacter.copper = copperField?.value ?? currentCharacter.copper;
  458. SaveCurrentCharacterToSlot();
  459. }
  460. private void UpdateInventoryUI()
  461. {
  462. if (currentCharacter == null) return;
  463. // Update bank fields
  464. if (goldField != null) goldField.value = currentCharacter.gold;
  465. if (silverField != null) silverField.value = currentCharacter.silver;
  466. if (copperField != null) copperField.value = currentCharacter.copper;
  467. // Update weapon list
  468. UpdateItemList(weaponsList, currentCharacter.weapons, "WeaponItemRow", OnRemoveWeapon);
  469. // Update armor list
  470. UpdateItemList(armorList, currentCharacter.armor, "ArmorItemRow", OnRemoveArmor);
  471. // Update misc list
  472. UpdateItemList(miscList, currentCharacter.miscItems, "MiscItemRow", OnRemoveMisc);
  473. }
  474. private void UpdateItemList(VisualElement container, System.Collections.Generic.List<string> items, string rowClassName, System.Action<string> removeAction)
  475. {
  476. if (container == null || items == null) return;
  477. // Clear existing items (except example rows)
  478. var itemsToRemove = container.Query<VisualElement>(className: "inventory-item-row").ToList()
  479. .Where(item => !item.name.Contains("Example")).ToList();
  480. foreach (var item in itemsToRemove)
  481. {
  482. container.Remove(item);
  483. }
  484. // Add current items
  485. foreach (var itemName in items)
  486. {
  487. var itemRow = new VisualElement();
  488. itemRow.AddToClassList("inventory-item-row");
  489. itemRow.AddToClassList(rowClassName);
  490. var nameLabel = new Label(itemName);
  491. nameLabel.AddToClassList("item-name-label");
  492. itemRow.Add(nameLabel);
  493. var removeButton = new Button(() => removeAction(itemName));
  494. removeButton.text = "Remove (Refund)";
  495. removeButton.AddToClassList("remove-item-button");
  496. // Add tooltip or title to show refund information
  497. string itemType = GetItemTypeFromClassName(rowClassName);
  498. string refundInfo = GetRefundInfo(itemName, itemType);
  499. if (!string.IsNullOrEmpty(refundInfo))
  500. {
  501. removeButton.tooltip = $"Remove and refund: {refundInfo}";
  502. }
  503. itemRow.Add(removeButton);
  504. container.Add(itemRow);
  505. }
  506. }
  507. private string GetItemTypeFromClassName(string className)
  508. {
  509. if (className.Contains("Weapon")) return "weapon";
  510. if (className.Contains("Armor")) return "armor";
  511. if (className.Contains("Misc")) return "misc";
  512. return "";
  513. }
  514. private string GetRefundInfo(string itemName, string itemType)
  515. {
  516. if (shopManager == null) return "";
  517. List<Item> itemList = null;
  518. switch (itemType.ToLower())
  519. {
  520. case "weapon":
  521. itemList = shopManager.GetWeapons();
  522. break;
  523. case "armor":
  524. itemList = shopManager.GetArmor();
  525. break;
  526. case "misc":
  527. itemList = shopManager.GetMiscItems();
  528. break;
  529. }
  530. if (itemList != null)
  531. {
  532. var shopItem = itemList.Find(item => item.itemName == itemName);
  533. if (shopItem != null)
  534. {
  535. return shopItem.GetCostString();
  536. }
  537. }
  538. return "";
  539. }
  540. private void RefundItemPrice(string itemName, string itemType)
  541. {
  542. if (shopManager == null || currentCharacter == null)
  543. {
  544. Debug.LogWarning($"Cannot refund {itemName}: shop manager or current character is null");
  545. return;
  546. }
  547. // Find the item price from the shop manager
  548. int goldRefund = 0;
  549. int silverRefund = 0;
  550. int copperRefund = 0;
  551. // Check the appropriate list based on item type
  552. List<Item> itemList = null;
  553. switch (itemType.ToLower())
  554. {
  555. case "weapon":
  556. itemList = shopManager.GetWeapons();
  557. break;
  558. case "armor":
  559. itemList = shopManager.GetArmor();
  560. break;
  561. case "misc":
  562. itemList = shopManager.GetMiscItems();
  563. break;
  564. }
  565. if (itemList != null)
  566. {
  567. // Find the item in the shop list
  568. var shopItem = itemList.Find(item => item.itemName == itemName);
  569. if (shopItem != null)
  570. {
  571. goldRefund = shopItem.goldCost;
  572. silverRefund = shopItem.silverCost;
  573. copperRefund = shopItem.copperCost;
  574. // Add the refund to the character's money
  575. currentCharacter.gold += goldRefund;
  576. currentCharacter.silver += silverRefund;
  577. currentCharacter.copper += copperRefund;
  578. }
  579. else
  580. {
  581. Debug.LogWarning($"Could not find {itemName} in shop {itemType} list for refund");
  582. }
  583. }
  584. else
  585. {
  586. Debug.LogWarning($"Could not access shop {itemType} list for refund");
  587. }
  588. }
  589. private void OnRemoveWeapon(string weaponName)
  590. {
  591. if (currentCharacter?.weapons != null)
  592. {
  593. currentCharacter.weapons.Remove(weaponName);
  594. // Refund the weapon price
  595. RefundItemPrice(weaponName, "weapon");
  596. SaveCurrentCharacterToSlot();
  597. UpdateInventoryUI();
  598. }
  599. }
  600. private void OnRemoveArmor(string armorName)
  601. {
  602. if (currentCharacter?.armor != null)
  603. {
  604. currentCharacter.armor.Remove(armorName);
  605. // Refund the armor price
  606. RefundItemPrice(armorName, "armor");
  607. SaveCurrentCharacterToSlot();
  608. UpdateInventoryUI();
  609. }
  610. }
  611. private void OnRemoveMisc(string itemName)
  612. {
  613. if (currentCharacter?.miscItems != null)
  614. {
  615. currentCharacter.miscItems.Remove(itemName);
  616. // Refund the misc item price
  617. RefundItemPrice(itemName, "misc");
  618. SaveCurrentCharacterToSlot();
  619. UpdateInventoryUI();
  620. }
  621. }
  622. private void UpdateCharacterUI()
  623. {
  624. if (currentCharacter == null)
  625. {
  626. // Clear the UI when no character is selected
  627. if (characterNameField != null) characterNameField.value = "";
  628. if (genderDropdown != null) genderDropdown.value = "Male";
  629. if (strengthField != null) strengthField.value = 10;
  630. if (dexterityField != null) dexterityField.value = 10;
  631. if (constitutionField != null) constitutionField.value = 10;
  632. if (wisdomField != null) wisdomField.value = 10;
  633. // Clear derived stats
  634. if (initField != null) initField.value = 0;
  635. if (damageField != null) damageField.value = 0;
  636. if (spellCastingField != null) spellCastingField.value = 0;
  637. if (movementSpeedField != null) movementSpeedField.value = 30;
  638. if (hpField != null) hpField.value = 10;
  639. if (acField != null) acField.value = 0;
  640. // Clear attribute UI
  641. if (creationModeLabel != null) creationModeLabel.text = "Mode: None";
  642. if (availablePointsLabel != null) availablePointsLabel.text = "Available Points: 0";
  643. return;
  644. }
  645. // Update UI with current character data
  646. if (characterNameField != null)
  647. characterNameField.value = currentCharacter.name;
  648. if (genderDropdown != null)
  649. genderDropdown.value = currentCharacter.isMale ? "Male" : "Female";
  650. if (strengthField != null) strengthField.value = currentCharacter.strength;
  651. if (dexterityField != null) dexterityField.value = currentCharacter.dexterity;
  652. if (constitutionField != null) constitutionField.value = currentCharacter.constitution;
  653. if (wisdomField != null) wisdomField.value = currentCharacter.wisdom;
  654. if (perceptionField != null) perceptionField.value = currentCharacter.perception;
  655. // Recalculate equipment bonuses from inventory
  656. currentCharacter.RecalculateEquipmentBonuses();
  657. UpdateDerivedStats();
  658. UpdateAttributeUI();
  659. UpdateInventoryUI();
  660. }
  661. private void UpdateAttributeUI()
  662. {
  663. if (currentCharacter == null) return;
  664. // Update creation mode display
  665. if (creationModeLabel != null)
  666. {
  667. creationModeLabel.text = "Mode: Point Buy";
  668. }
  669. // Update available points display
  670. if (availablePointsLabel != null)
  671. {
  672. availablePointsLabel.text = $"Available Points: {currentCharacter.availablePoints}";
  673. }
  674. // All stat fields are always editable in the new system
  675. if (strengthField != null) strengthField.SetEnabled(true);
  676. if (dexterityField != null) dexterityField.SetEnabled(true);
  677. if (constitutionField != null) constitutionField.SetEnabled(true);
  678. if (wisdomField != null) wisdomField.SetEnabled(true);
  679. if (perceptionField != null) perceptionField.SetEnabled(true);
  680. }
  681. private void UpdateDerivedStats()
  682. {
  683. if (currentCharacter == null) return;
  684. // Update the read-only derived stats (uses final stats including equipment modifiers)
  685. if (initField != null) initField.value = currentCharacter.Initiative;
  686. if (damageField != null) damageField.value = currentCharacter.DamageBonus;
  687. if (spellCastingField != null) spellCastingField.value = currentCharacter.SpellAC;
  688. if (movementSpeedField != null) movementSpeedField.value = currentCharacter.MovementSpeed;
  689. if (hpField != null) hpField.value = currentCharacter.HitPoints;
  690. if (acField != null) acField.value = currentCharacter.ArmorClass;
  691. }
  692. private void UpdateCurrentSlotButton()
  693. {
  694. // Update the character card information if we have a current slot selected
  695. if (currentSlotIndex >= 0 && currentSlotIndex < characterSlotButtons.Count && currentCharacter != null)
  696. {
  697. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  698. }
  699. }
  700. private void UpdateCharacterCard(int slotIndex, TeamCharacter character)
  701. {
  702. if (slotIndex < 0 || slotIndex >= 4 || character == null) return;
  703. var root = uiDocument.rootVisualElement;
  704. // Find the character slot instance based on index
  705. string[] slotNames = { "Character1", "Character2", "Character3", "Character4" };
  706. var characterSlot = root.Q<VisualElement>(slotNames[slotIndex]);
  707. if (characterSlot == null) return;
  708. // Find the character card button within this slot
  709. var characterCard = characterSlot.Q<Button>("ViewCharacterButton");
  710. if (characterCard == null) return;
  711. // Update character name
  712. var nameLabel = characterCard.Q<Label>("CharacterNameLabel");
  713. if (nameLabel != null)
  714. {
  715. nameLabel.text = character.name;
  716. }
  717. // Update stats
  718. var strengthLabel = characterCard.Q<Label>("StrengthLabel");
  719. if (strengthLabel != null) strengthLabel.text = character.strength.ToString();
  720. var dexterityLabel = characterCard.Q<Label>("DexterityLabel");
  721. if (dexterityLabel != null) dexterityLabel.text = character.dexterity.ToString();
  722. var constitutionLabel = characterCard.Q<Label>("ConstitutionLabel");
  723. if (constitutionLabel != null) constitutionLabel.text = character.constitution.ToString();
  724. var wisdomLabel = characterCard.Q<Label>("WisdomLabel");
  725. if (wisdomLabel != null) wisdomLabel.text = character.wisdom.ToString();
  726. var perceptionLabel = characterCard.Q<Label>("PerceptionLabel");
  727. if (perceptionLabel != null) perceptionLabel.text = character.perception.ToString();
  728. // Update HP and AC
  729. var hpLabel = characterCard.Q<Label>("HPLabel");
  730. if (hpLabel != null) hpLabel.text = $"HP: {character.HitPoints}";
  731. var acLabel = characterCard.Q<Label>("ACLabel");
  732. if (acLabel != null) acLabel.text = $"AC: {character.ArmorClass}";
  733. // Show the character card and hide the create button
  734. var createButton = characterSlot.Q<Button>("CreateNewCharacterButton");
  735. if (createButton != null)
  736. {
  737. createButton.style.display = DisplayStyle.None;
  738. }
  739. characterCard.RemoveFromClassList("disabled-card");
  740. characterCard.style.display = DisplayStyle.Flex;
  741. characterCard.SetEnabled(true);
  742. }
  743. private void SaveCurrentCharacterToSlot()
  744. {
  745. // Save the current character data back to its slot
  746. if (currentSlotIndex >= 0 && currentSlotIndex < characterSlots.Length && currentCharacter != null)
  747. {
  748. characterSlots[currentSlotIndex] = currentCharacter.CreateCopy();
  749. }
  750. }
  751. private void UpdateSlotVisualStates()
  752. {
  753. var root = uiDocument.rootVisualElement;
  754. string[] slotNames = { "Character1", "Character2", "Character3", "Character4" };
  755. // Update visual states of all character slots
  756. for (int i = 0; i < slotNames.Length; i++)
  757. {
  758. var characterSlot = root.Q<VisualElement>(slotNames[i]);
  759. if (characterSlot == null) continue;
  760. // Remove all visual state classes first
  761. characterSlot.RemoveFromClassList("selected-slot");
  762. // Add selected state if this is the current slot
  763. if (i == currentSlotIndex)
  764. {
  765. characterSlot.AddToClassList("selected-slot");
  766. }
  767. // Update character card visibility and data
  768. if (characterSlots[i] != null)
  769. {
  770. // Character exists in this slot
  771. UpdateCharacterCard(i, characterSlots[i]);
  772. }
  773. else
  774. {
  775. // No character in this slot - show create button
  776. var createButton = characterSlot.Q<Button>("CreateNewCharacterButton");
  777. var characterCard = characterSlot.Q<Button>("ViewCharacterButton");
  778. if (createButton != null)
  779. {
  780. createButton.style.display = DisplayStyle.Flex;
  781. }
  782. if (characterCard != null)
  783. {
  784. characterCard.style.display = DisplayStyle.None;
  785. characterCard.AddToClassList("disabled-card");
  786. characterCard.SetEnabled(false);
  787. }
  788. }
  789. }
  790. }
  791. // Example handler if you need to pass data (like an index)
  792. private void OnCreateNewCharacterButtonClicked(int index)
  793. {
  794. // Create a new character with random name
  795. currentCharacter = new TeamCharacter();
  796. // Generate name after construction to avoid serialization issues
  797. currentCharacter.GenerateRandomName();
  798. // Save character to the slot (create a proper copy)
  799. characterSlots[index] = currentCharacter.CreateCopy();
  800. currentSlotIndex = index;
  801. UpdateCharacterUI();
  802. UpdateSlotVisualStates();
  803. // Update navigation buttons immediately after character creation
  804. UpdateNavigationButtons();
  805. // Update the character card for this slot
  806. UpdateCharacterCard(index, currentCharacter);
  807. // Call UpdateNavigationButtons again after UI updates
  808. UpdateNavigationButtons();
  809. }
  810. private void OnViewCharacterButtonClicked(int index)
  811. {
  812. // Check if there's a character in this slot
  813. if (characterSlots[index] != null)
  814. {
  815. // Create a working copy of the character from the slot
  816. currentCharacter = characterSlots[index].CreateCopy();
  817. currentSlotIndex = index;
  818. UpdateCharacterUI();
  819. UpdateSlotVisualStates();
  820. UpdateNavigationButtons();
  821. }
  822. else
  823. {
  824. // Slot is empty, save current character to this slot if we have one
  825. if (currentCharacter != null)
  826. {
  827. // Create a proper copy of the current character data
  828. characterSlots[index] = currentCharacter.CreateCopy();
  829. currentSlotIndex = index;
  830. // Update the character card for this slot
  831. UpdateCharacterCard(index, currentCharacter);
  832. UpdateSlotVisualStates();
  833. UpdateNavigationButtons();
  834. }
  835. }
  836. }
  837. // Start is called once before the first execution of Update after the MonoBehaviour is created
  838. void Start()
  839. {
  840. // You can keep Start if needed for other initialization
  841. }
  842. // Update is called once per frame
  843. void Update()
  844. {
  845. // Debug keys for testing
  846. if (Input.GetKeyDown(KeyCode.F5))
  847. {
  848. DebugCurrentCharacterSlots();
  849. }
  850. if (Input.GetKeyDown(KeyCode.F6))
  851. {
  852. SaveTeamToGameState();
  853. }
  854. if (Input.GetKeyDown(KeyCode.F7))
  855. {
  856. TestPlayerPrefsData();
  857. }
  858. }
  859. private void DebugCurrentCharacterSlots()
  860. {
  861. for (int i = 0; i < characterSlots.Length; i++)
  862. {
  863. if (characterSlots[i] != null)
  864. {
  865. var character = characterSlots[i];
  866. }
  867. else
  868. {
  869. }
  870. }
  871. }
  872. private void TestPlayerPrefsData()
  873. {
  874. for (int i = 0; i < 4; i++)
  875. {
  876. string existsKey = $"Character{i}_Exists";
  877. if (PlayerPrefs.HasKey(existsKey))
  878. {
  879. int exists = PlayerPrefs.GetInt(existsKey);
  880. if (exists == 1)
  881. {
  882. string prefix = $"Character{i}_";
  883. string name = PlayerPrefs.GetString(prefix + "Name", "UNKNOWN");
  884. int str = PlayerPrefs.GetInt(prefix + "Strength", 0);
  885. int dex = PlayerPrefs.GetInt(prefix + "Dexterity", 0);
  886. int con = PlayerPrefs.GetInt(prefix + "Constitution", 0);
  887. int wis = PlayerPrefs.GetInt(prefix + "Wisdom", 0);
  888. }
  889. }
  890. else
  891. {
  892. }
  893. }
  894. }
  895. void OnDestroy()
  896. {
  897. // Clean up shop manager callbacks to prevent memory leaks
  898. if (shopManager != null)
  899. {
  900. shopManager.OnCharacterDataChanged -= OnShopCharacterDataChanged;
  901. }
  902. }
  903. #region Navigation Methods
  904. private void OnBackToTitleClicked()
  905. {
  906. // Check if team is finalized and this is acting as "New Game" button
  907. if (IsTeamFinalized())
  908. {
  909. // Show confirmation dialog for starting new game
  910. #if UNITY_EDITOR
  911. bool confirmed = UnityEditor.EditorUtility.DisplayDialog(
  912. "Start New Game",
  913. "This will start a completely new game and overwrite your current progress.\n\nAre you sure you want to continue?",
  914. "Start New Game",
  915. "Cancel"
  916. );
  917. if (confirmed)
  918. {
  919. StartNewGame();
  920. }
  921. #else
  922. // In builds, we'll assume user confirms for now
  923. // In a real game, implement a proper UI dialog system
  924. Debug.LogWarning("Starting new game - implement proper dialog for builds");
  925. StartNewGame();
  926. #endif
  927. }
  928. else
  929. {
  930. // Normal back to title behavior
  931. SceneManager.LoadScene("TitleScreenScene");
  932. }
  933. }
  934. private void StartNewGame()
  935. {
  936. // Initialize GameStateManager for new game
  937. if (GameStateManager.Instance != null)
  938. {
  939. GameStateManager.Instance.StartNewGame();
  940. }
  941. // Clear all save data
  942. ClearAllSaveData();
  943. // Reload the scene to start fresh
  944. SceneManager.LoadScene("MainTeamSelectScene");
  945. }
  946. private void ClearAllSaveData()
  947. {
  948. // Clear GameStateManager data
  949. if (GameStateManager.Instance != null)
  950. {
  951. GameStateManager.Instance.teamSetupComplete = false;
  952. GameStateManager.Instance.hasGeneratedMap = false;
  953. }
  954. // Clear PlayerPrefs data
  955. for (int i = 0; i < 4; i++)
  956. {
  957. string prefix = $"Character{i}_";
  958. PlayerPrefs.DeleteKey($"Character{i}_Exists");
  959. PlayerPrefs.DeleteKey(prefix + "Name");
  960. PlayerPrefs.DeleteKey(prefix + "IsMale");
  961. PlayerPrefs.DeleteKey(prefix + "Strength");
  962. PlayerPrefs.DeleteKey(prefix + "Dexterity");
  963. PlayerPrefs.DeleteKey(prefix + "Constitution");
  964. PlayerPrefs.DeleteKey(prefix + "Wisdom");
  965. PlayerPrefs.DeleteKey(prefix + "Gold");
  966. PlayerPrefs.DeleteKey(prefix + "Silver");
  967. PlayerPrefs.DeleteKey(prefix + "Copper");
  968. }
  969. // Clear map data
  970. PlayerPrefs.DeleteKey("HasGeneratedMap");
  971. PlayerPrefs.DeleteKey("MapSeed");
  972. PlayerPrefs.DeleteKey("TeamSize");
  973. PlayerPrefs.DeleteKey("TeamSetupComplete");
  974. PlayerPrefs.DeleteKey("GameSaved");
  975. PlayerPrefs.Save();
  976. }
  977. private void OnProceedToBattleClicked()
  978. {
  979. // Check if team is already finalized
  980. if (IsTeamFinalized())
  981. {
  982. // Team is finalized, return to MapScene2
  983. SceneManager.LoadScene("MapScene2");
  984. return;
  985. }
  986. // Check if we have at least one character
  987. if (!HasAtLeastOneCharacter())
  988. {
  989. Debug.LogWarning("Need at least one character to proceed to battle!");
  990. // TODO: Show message to user
  991. return;
  992. }
  993. // Save all configured characters before proceeding
  994. SaveTeamToGameState();
  995. // Mark that the team has proceeded to the map (finalized)
  996. // Save to both GameStateManager and PlayerPrefs for redundancy
  997. if (GameStateManager.Instance != null)
  998. {
  999. GameStateManager.Instance.teamSetupComplete = true;
  1000. GameStateManager.Instance.SaveGame();
  1001. }
  1002. // Also save to PlayerPrefs as backup
  1003. PlayerPrefs.SetInt("TeamSetupComplete", 1);
  1004. PlayerPrefs.Save();
  1005. SceneManager.LoadScene("MapScene2");
  1006. }
  1007. private void SaveTeamToGameState()
  1008. {
  1009. // Save team data to GameStateManager for persistence
  1010. List<TeamCharacter> configuredCharacters = new List<TeamCharacter>();
  1011. for (int i = 0; i < characterSlots.Length; i++)
  1012. {
  1013. if (characterSlots[i] != null)
  1014. {
  1015. configuredCharacters.Add(characterSlots[i]);
  1016. // Save individual character data
  1017. SaveCharacterToPlayerPrefs(characterSlots[i], i);
  1018. // Verify the save immediately
  1019. PlayerPrefs.SetInt($"Character{i}_Exists", 1);
  1020. string testName = PlayerPrefs.GetString($"Character{i}_Name", "NOT_FOUND");
  1021. }
  1022. else
  1023. {
  1024. // Clear any existing character data for empty slots
  1025. PlayerPrefs.DeleteKey($"Character{i}_Exists");
  1026. }
  1027. }
  1028. // Save team composition info
  1029. PlayerPrefs.SetInt("TeamSize", configuredCharacters.Count);
  1030. // Update GameStateManager if available
  1031. if (GameStateManager.Instance != null)
  1032. {
  1033. // Copy our team to the GameStateManager
  1034. for (int i = 0; i < characterSlots.Length; i++)
  1035. {
  1036. if (characterSlots[i] != null)
  1037. {
  1038. GameStateManager.Instance.savedTeam[i] = characterSlots[i].CreateCopy();
  1039. }
  1040. else
  1041. {
  1042. GameStateManager.Instance.savedTeam[i] = null;
  1043. }
  1044. }
  1045. GameStateManager.Instance.teamSetupComplete = true;
  1046. GameStateManager.Instance.SaveGame();
  1047. }
  1048. else
  1049. {
  1050. Debug.LogWarning("GameStateManager.Instance is null!");
  1051. }
  1052. // Log configured team for MapScene
  1053. foreach (var character in configuredCharacters)
  1054. {
  1055. }
  1056. PlayerPrefs.Save(); // Ensure data is written to disk
  1057. }
  1058. public List<TeamCharacter> GetConfiguredCharacters()
  1059. {
  1060. // Public method to get all configured characters (useful for other scripts)
  1061. List<TeamCharacter> configuredCharacters = new List<TeamCharacter>();
  1062. for (int i = 0; i < characterSlots.Length; i++)
  1063. {
  1064. if (characterSlots[i] != null)
  1065. {
  1066. configuredCharacters.Add(characterSlots[i]);
  1067. }
  1068. }
  1069. return configuredCharacters;
  1070. }
  1071. private void UpdateNavigationButtons()
  1072. {
  1073. // Enable/disable proceed button based on team status
  1074. if (proceedToBattleButton != null)
  1075. {
  1076. bool canProceed = HasAtLeastOneCharacter();
  1077. proceedToBattleButton.SetEnabled(canProceed);
  1078. // Also remove/add visual disabled state
  1079. if (!canProceed)
  1080. {
  1081. proceedToBattleButton.AddToClassList("disabled-button");
  1082. proceedToBattleButton.tooltip = "Create at least one character to proceed";
  1083. }
  1084. else
  1085. {
  1086. proceedToBattleButton.RemoveFromClassList("disabled-button");
  1087. proceedToBattleButton.tooltip = "Start adventure with your team";
  1088. // Force remove any disabled classes that might be interfering
  1089. proceedToBattleButton.RemoveFromClassList("unity-disabled");
  1090. }
  1091. }
  1092. else
  1093. {
  1094. Debug.LogWarning("UpdateNavigationButtons: proceedToBattleButton is null! The button name in the UI might be different than expected.");
  1095. Debug.LogWarning("Please check that a button with name 'ProceedToBattleButton' exists in your UI Document.");
  1096. // Try to find the button again with common alternative names
  1097. var root = uiDocument?.rootVisualElement;
  1098. if (root != null)
  1099. {
  1100. proceedToBattleButton = root.Q<Button>("ProceedButton") ??
  1101. root.Q<Button>("StartButton") ??
  1102. root.Q<Button>("BattleButton") ??
  1103. root.Q<Button>("ProceedToBattleButton");
  1104. if (proceedToBattleButton != null)
  1105. {
  1106. // Recursively call this method now that we found the button
  1107. UpdateNavigationButtons();
  1108. }
  1109. }
  1110. }
  1111. }
  1112. private bool HasAtLeastOneCharacter()
  1113. {
  1114. int characterCount = 0;
  1115. for (int i = 0; i < characterSlots.Length; i++)
  1116. {
  1117. if (characterSlots[i] != null)
  1118. {
  1119. characterCount++;
  1120. }
  1121. else
  1122. {
  1123. }
  1124. }
  1125. bool hasCharacters = characterCount > 0;
  1126. return hasCharacters;
  1127. }
  1128. #endregion
  1129. #region Save/Load Team Data
  1130. private void LoadSavedTeamData()
  1131. {
  1132. // Try to load from GameStateManager first (if available and has data)
  1133. if (GameStateManager.Instance != null && GameStateManager.Instance.savedTeam != null)
  1134. {
  1135. for (int i = 0; i < characterSlots.Length && i < GameStateManager.Instance.savedTeam.Length; i++)
  1136. {
  1137. if (GameStateManager.Instance.savedTeam[i] != null)
  1138. {
  1139. characterSlots[i] = GameStateManager.Instance.savedTeam[i].CreateCopy();
  1140. // Update the slot button
  1141. if (i < characterSlotButtons.Count)
  1142. {
  1143. characterSlotButtons[i].text = characterSlots[i].name;
  1144. characterSlotButtons[i].SetEnabled(true);
  1145. characterSlotButtons[i].RemoveFromClassList("unity-disabled");
  1146. characterSlotButtons[i].RemoveFromClassList("DisabledCharacterCard");
  1147. // Hide the create button
  1148. if (i < createNewCharacterButtons.Count)
  1149. {
  1150. createNewCharacterButtons[i].style.display = DisplayStyle.None;
  1151. }
  1152. }
  1153. }
  1154. }
  1155. }
  1156. // Always also try to load from PlayerPrefs (either as backup or primary)
  1157. for (int i = 0; i < characterSlots.Length; i++)
  1158. {
  1159. // If we haven't loaded this slot from GameStateManager, try PlayerPrefs
  1160. if (characterSlots[i] == null && PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
  1161. {
  1162. // Load character data from PlayerPrefs
  1163. characterSlots[i] = LoadCharacterFromPlayerPrefs(i);
  1164. // Update the slot button
  1165. if (i < characterSlotButtons.Count)
  1166. {
  1167. characterSlotButtons[i].text = characterSlots[i].name;
  1168. characterSlotButtons[i].SetEnabled(true);
  1169. characterSlotButtons[i].RemoveFromClassList("unity-disabled");
  1170. characterSlotButtons[i].RemoveFromClassList("DisabledCharacterCard");
  1171. // Hide the create button
  1172. if (i < createNewCharacterButtons.Count)
  1173. {
  1174. createNewCharacterButtons[i].style.display = DisplayStyle.None;
  1175. }
  1176. }
  1177. }
  1178. }
  1179. // Count loaded characters
  1180. int loadedCount = 0;
  1181. for (int i = 0; i < characterSlots.Length; i++)
  1182. {
  1183. if (characterSlots[i] != null) loadedCount++;
  1184. }
  1185. }
  1186. private void SaveCurrentTeamToGameState()
  1187. {
  1188. // Save the current team using PlayerPrefs for now
  1189. for (int i = 0; i < characterSlots.Length; i++)
  1190. {
  1191. if (characterSlots[i] != null)
  1192. {
  1193. SaveCharacterToPlayerPrefs(characterSlots[i], i);
  1194. PlayerPrefs.SetInt($"Character{i}_Exists", 1);
  1195. }
  1196. else
  1197. {
  1198. PlayerPrefs.SetInt($"Character{i}_Exists", 0);
  1199. }
  1200. }
  1201. PlayerPrefs.Save();
  1202. }
  1203. private TeamCharacter LoadCharacterFromPlayerPrefs(int index)
  1204. {
  1205. string prefix = $"Character{index}_";
  1206. var character = new TeamCharacter();
  1207. character.name = PlayerPrefs.GetString(prefix + "Name", "");
  1208. character.isMale = PlayerPrefs.GetInt(prefix + "IsMale", 1) == 1;
  1209. character.strength = PlayerPrefs.GetInt(prefix + "Strength", 10);
  1210. character.dexterity = PlayerPrefs.GetInt(prefix + "Dexterity", 10);
  1211. character.constitution = PlayerPrefs.GetInt(prefix + "Constitution", 10);
  1212. character.wisdom = PlayerPrefs.GetInt(prefix + "Wisdom", 10);
  1213. character.perception = PlayerPrefs.GetInt(prefix + "Perception", 10);
  1214. character.gold = PlayerPrefs.GetInt(prefix + "Gold", 25);
  1215. character.silver = PlayerPrefs.GetInt(prefix + "Silver", 0);
  1216. character.copper = PlayerPrefs.GetInt(prefix + "Copper", 0);
  1217. // Recalculate equipment bonuses from inventory after loading
  1218. character.RecalculateEquipmentBonuses();
  1219. return character;
  1220. }
  1221. private void SaveCharacterToPlayerPrefs(TeamCharacter character, int index)
  1222. {
  1223. string prefix = $"Character{index}_";
  1224. PlayerPrefs.SetString(prefix + "Name", character.name);
  1225. PlayerPrefs.SetInt(prefix + "IsMale", character.isMale ? 1 : 0);
  1226. PlayerPrefs.SetInt(prefix + "Strength", character.strength);
  1227. PlayerPrefs.SetInt(prefix + "Dexterity", character.dexterity);
  1228. PlayerPrefs.SetInt(prefix + "Constitution", character.constitution);
  1229. PlayerPrefs.SetInt(prefix + "Wisdom", character.wisdom);
  1230. PlayerPrefs.SetInt(prefix + "Perception", character.perception);
  1231. PlayerPrefs.SetInt(prefix + "Gold", character.gold);
  1232. PlayerPrefs.SetInt(prefix + "Silver", character.silver);
  1233. PlayerPrefs.SetInt(prefix + "Copper", character.copper);
  1234. // Immediately verify what was saved
  1235. string savedName = PlayerPrefs.GetString(prefix + "Name", "FAILED_TO_SAVE");
  1236. int savedStr = PlayerPrefs.GetInt(prefix + "Strength", -1);
  1237. if (savedName != character.name)
  1238. {
  1239. Debug.LogError($" ERROR: Name save failed! Expected '{character.name}', got '{savedName}'");
  1240. }
  1241. }
  1242. #endregion
  1243. #region Team Finalization
  1244. private bool IsTeamFinalized()
  1245. {
  1246. // Check if the team has been finalized (player clicked "Proceed to Battle" and went to MapScene)
  1247. // This is indicated by TeamSetupComplete being true or HasGeneratedMap being true
  1248. bool hasGeneratedMap = PlayerPrefs.HasKey("HasGeneratedMap") && PlayerPrefs.GetInt("HasGeneratedMap") == 1;
  1249. bool teamSetupCompletePrefs = PlayerPrefs.HasKey("TeamSetupComplete") && PlayerPrefs.GetInt("TeamSetupComplete") == 1;
  1250. bool teamSetupCompleteGameState = false;
  1251. if (GameStateManager.Instance != null)
  1252. {
  1253. teamSetupCompleteGameState = GameStateManager.Instance.teamSetupComplete;
  1254. }
  1255. bool finalized = hasGeneratedMap || teamSetupCompletePrefs || teamSetupCompleteGameState;
  1256. return finalized;
  1257. }
  1258. private void SetTeamFinalizedMode()
  1259. {
  1260. // Disable all character creation and editing
  1261. foreach (var button in createNewCharacterButtons)
  1262. {
  1263. button.SetEnabled(false);
  1264. button.style.opacity = 0.5f;
  1265. button.tooltip = "Team has been finalized - cannot create new characters";
  1266. }
  1267. // Disable character editing fields
  1268. DisableCharacterEditingFields();
  1269. // Change the proceed button to "Return to Adventure"
  1270. if (proceedToBattleButton != null)
  1271. {
  1272. proceedToBattleButton.text = "Return to Adventure";
  1273. proceedToBattleButton.tooltip = "Return to your ongoing adventure";
  1274. }
  1275. // Change the back button to offer new game option
  1276. if (backToTitleButton != null)
  1277. {
  1278. backToTitleButton.text = "New Game";
  1279. backToTitleButton.tooltip = "Start a completely new game (will overwrite current save)";
  1280. }
  1281. // Show a message that team is finalized
  1282. }
  1283. private void DisableCharacterEditingFields()
  1284. {
  1285. // Disable name editing
  1286. if (characterNameField != null)
  1287. {
  1288. characterNameField.SetEnabled(false);
  1289. characterNameField.style.opacity = 0.7f;
  1290. }
  1291. if (randomizeNameButton != null)
  1292. {
  1293. randomizeNameButton.SetEnabled(false);
  1294. randomizeNameButton.style.opacity = 0.5f;
  1295. }
  1296. if (genderDropdown != null)
  1297. {
  1298. genderDropdown.SetEnabled(false);
  1299. genderDropdown.style.opacity = 0.7f;
  1300. }
  1301. // Disable stat editing
  1302. if (strengthField != null) strengthField.SetEnabled(false);
  1303. if (dexterityField != null) dexterityField.SetEnabled(false);
  1304. if (constitutionField != null) constitutionField.SetEnabled(false);
  1305. if (wisdomField != null) wisdomField.SetEnabled(false);
  1306. // Disable attribute buttons
  1307. if (randomizeAttributesButton != null)
  1308. {
  1309. randomizeAttributesButton.SetEnabled(false);
  1310. randomizeAttributesButton.style.opacity = 0.5f;
  1311. }
  1312. if (resetToPointBuyButton != null)
  1313. {
  1314. resetToPointBuyButton.SetEnabled(false);
  1315. resetToPointBuyButton.style.opacity = 0.5f;
  1316. }
  1317. // Disable inventory management
  1318. if (addWeaponButton != null)
  1319. {
  1320. addWeaponButton.SetEnabled(false);
  1321. addWeaponButton.style.opacity = 0.5f;
  1322. }
  1323. if (addArmorButton != null)
  1324. {
  1325. addArmorButton.SetEnabled(false);
  1326. addArmorButton.style.opacity = 0.5f;
  1327. }
  1328. if (addMiscButton != null)
  1329. {
  1330. addMiscButton.SetEnabled(false);
  1331. addMiscButton.style.opacity = 0.5f;
  1332. }
  1333. // Disable bank editing
  1334. if (goldField != null) goldField.SetEnabled(false);
  1335. if (silverField != null) silverField.SetEnabled(false);
  1336. if (copperField != null) copperField.SetEnabled(false);
  1337. }
  1338. #endregion
  1339. private System.Collections.IEnumerator RefreshShopManagerReference()
  1340. {
  1341. // Wait for a short delay to allow for potential late initialization
  1342. yield return new WaitForSeconds(0.1f);
  1343. // Try to find the shop manager again
  1344. var newShopManager = FindFirstObjectByType<ItemShopManager>();
  1345. if (newShopManager != null)
  1346. {
  1347. shopManager = newShopManager;
  1348. SetupShopManagerCallbacks();
  1349. }
  1350. else
  1351. {
  1352. Debug.LogWarning("Still no ItemShopManager found after delay. You may need to create one manually using the ShopSystemSetup component.");
  1353. }
  1354. }
  1355. private void SetupShopManagerCallbacks()
  1356. {
  1357. if (shopManager != null)
  1358. {
  1359. // Subscribe to character data changes from the shop
  1360. shopManager.OnCharacterDataChanged += OnShopCharacterDataChanged;
  1361. }
  1362. }
  1363. private void OnShopCharacterDataChanged(TeamCharacter updatedCharacter)
  1364. {
  1365. if (updatedCharacter == null || currentCharacter == null)
  1366. {
  1367. Debug.LogWarning("OnShopCharacterDataChanged: updatedCharacter or currentCharacter is null");
  1368. return;
  1369. }
  1370. // Copy the updated data back to the current character
  1371. // This ensures the character object reference remains the same but data is updated
  1372. currentCharacter.gold = updatedCharacter.gold;
  1373. currentCharacter.silver = updatedCharacter.silver;
  1374. currentCharacter.copper = updatedCharacter.copper;
  1375. // Update inventory lists (create new lists to avoid reference issues)
  1376. currentCharacter.weapons = new System.Collections.Generic.List<string>(updatedCharacter.weapons);
  1377. currentCharacter.armor = new System.Collections.Generic.List<string>(updatedCharacter.armor);
  1378. currentCharacter.miscItems = new System.Collections.Generic.List<string>(updatedCharacter.miscItems);
  1379. // Update the UI to reflect the changes
  1380. UpdateInventoryUI();
  1381. // Save the updated character to the slot
  1382. SaveCurrentCharacterToSlot();
  1383. }
  1384. // Clear all equipment from existing characters to ensure shop-only acquisition
  1385. private void ClearAllCharacterEquipment()
  1386. {
  1387. // Clear equipment from any existing characters in slots
  1388. for (int i = 0; i < characterSlots.Length; i++)
  1389. {
  1390. if (characterSlots[i] != null)
  1391. {
  1392. characterSlots[i].weapons.Clear();
  1393. characterSlots[i].armor.Clear();
  1394. characterSlots[i].miscItems.Clear();
  1395. characterSlots[i].equippedWeapon = "";
  1396. characterSlots[i].equippedArmor = "";
  1397. }
  1398. }
  1399. // Also clear equipment from current character if it exists
  1400. if (currentCharacter != null)
  1401. {
  1402. currentCharacter.weapons.Clear();
  1403. currentCharacter.armor.Clear();
  1404. currentCharacter.miscItems.Clear();
  1405. currentCharacter.equippedWeapon = "";
  1406. currentCharacter.equippedArmor = "";
  1407. }
  1408. }
  1409. }
  1410. [System.Serializable]
  1411. public class TeamCharacter
  1412. {
  1413. public string name = "";
  1414. public bool isMale = true;
  1415. // Base attributes (can be modified by equipment in the future)
  1416. public int strength = 10;
  1417. public int dexterity = 10;
  1418. public int constitution = 10;
  1419. public int wisdom = 10;
  1420. public int perception = 10;
  1421. // Character creation mode
  1422. public bool isRandomized = false; // Track if stats were randomized
  1423. public int availablePoints = 22; // Point-buy system (adjusted for 5 stats instead of 4)
  1424. // Equipment modifiers (for future use)
  1425. public int strengthModifier = 0;
  1426. public int dexterityModifier = 0;
  1427. public int constitutionModifier = 0;
  1428. public int wisdomModifier = 0;
  1429. public int perceptionModifier = 0;
  1430. public int acModifier = 0; // Direct AC bonuses from equipment
  1431. // Currency
  1432. public int gold = 25; // Reduced starting money to make shop purchases more strategic
  1433. public int silver = 0;
  1434. public int copper = 0;
  1435. // Equipment/Inventory (simple string-based for now)
  1436. public System.Collections.Generic.List<string> weapons = new System.Collections.Generic.List<string>();
  1437. public System.Collections.Generic.List<string> armor = new System.Collections.Generic.List<string>();
  1438. public System.Collections.Generic.List<string> miscItems = new System.Collections.Generic.List<string>();
  1439. public string equippedWeapon = "";
  1440. public string equippedArmor = "";
  1441. // Final attributes (base + equipment modifiers)
  1442. public int FinalStrength => strength + strengthModifier;
  1443. public int FinalDexterity => dexterity + dexterityModifier;
  1444. public int FinalConstitution => constitution + constitutionModifier;
  1445. public int FinalWisdom => wisdom + wisdomModifier;
  1446. public int FinalPerception => perception + perceptionModifier;
  1447. // Derived stats (calculated from final stats)
  1448. public int Initiative => FinalDexterity - 10;
  1449. public int DamageBonus => (FinalStrength - 10) / 2;
  1450. public int SpellAC => FinalWisdom - 10; // Renamed from SpellCastingBonus
  1451. public int MovementSpeed => 30 + (int)(Mathf.Ceil((FinalDexterity - 10) / 5.0f) * 5); // Rounded to closest 5 above
  1452. public int HitPoints => Mathf.Max(10, 10 + (FinalConstitution - 10) * 2 + (FinalStrength - 10) + (FinalDexterity - 10) / 2);
  1453. public int ArmorClass => 10 + (FinalDexterity - 10) / 2 + (FinalConstitution - 10) / 3 + acModifier; // Base 10 + DEX bonus + small CON bonus + equipment AC
  1454. public TeamCharacter()
  1455. {
  1456. // Don't generate random name in constructor to avoid serialization issues
  1457. // Name will be generated explicitly when needed
  1458. }
  1459. public TeamCharacter(string characterName, bool male = true)
  1460. {
  1461. name = characterName;
  1462. isMale = male;
  1463. }
  1464. public void GenerateRandomName()
  1465. {
  1466. // Only generate names when the application is playing to avoid serialization issues
  1467. if (Application.isPlaying)
  1468. {
  1469. name = FantasyNameGenerator.GenerateCharacterName(isMale);
  1470. }
  1471. else
  1472. {
  1473. // Fallback name for serialization/design time
  1474. name = isMale ? "New Male Character" : "New Female Character";
  1475. }
  1476. }
  1477. public void SetGender(bool male)
  1478. {
  1479. isMale = male;
  1480. }
  1481. // Randomize all attributes using point-buy system (22 points)
  1482. public void RandomizeAttributes()
  1483. {
  1484. if (Application.isPlaying)
  1485. {
  1486. // Start with random base values (4-12 range for variety)
  1487. int[] stats = new int[5];
  1488. for (int i = 0; i < 5; i++)
  1489. {
  1490. stats[i] = UnityEngine.Random.Range(4, 13); // Random start between 4-12
  1491. }
  1492. // Calculate how many points we've spent so far
  1493. int pointsSpent = 0;
  1494. for (int i = 0; i < 5; i++)
  1495. {
  1496. pointsSpent += GetStatCost(stats[i]);
  1497. }
  1498. int pointsRemaining = 22 - pointsSpent; // Changed from 18 to 22 for 5 stats
  1499. // If we're over budget, reduce some stats
  1500. while (pointsRemaining < 0)
  1501. {
  1502. int randomStat = UnityEngine.Random.Range(0, 5);
  1503. if (stats[randomStat] > 4) // Don't go below 4
  1504. {
  1505. int oldCost = GetStatCost(stats[randomStat]);
  1506. stats[randomStat]--;
  1507. int newCost = GetStatCost(stats[randomStat]);
  1508. pointsRemaining += (oldCost - newCost);
  1509. }
  1510. }
  1511. // Now spend remaining points randomly
  1512. while (pointsRemaining > 0)
  1513. {
  1514. // Pick a random stat to increase
  1515. int randomStat = UnityEngine.Random.Range(0, 5);
  1516. // Check if we can afford to increase this stat
  1517. int currentValue = stats[randomStat];
  1518. if (currentValue >= 18) continue; // Can't go higher than 18
  1519. int currentCost = GetStatCost(currentValue);
  1520. int newCost = GetStatCost(currentValue + 1);
  1521. int costDifference = newCost - currentCost;
  1522. if (pointsRemaining >= costDifference)
  1523. {
  1524. stats[randomStat]++;
  1525. pointsRemaining -= costDifference;
  1526. }
  1527. else
  1528. {
  1529. // If we can't afford any increases, try to find a stat we can afford
  1530. bool foundAffordable = false;
  1531. for (int i = 0; i < 5; i++)
  1532. {
  1533. if (stats[i] < 18)
  1534. {
  1535. int testCurrentCost = GetStatCost(stats[i]);
  1536. int testNewCost = GetStatCost(stats[i] + 1);
  1537. int testCostDiff = testNewCost - testCurrentCost;
  1538. if (pointsRemaining >= testCostDiff)
  1539. {
  1540. foundAffordable = true;
  1541. break;
  1542. }
  1543. }
  1544. }
  1545. // If no affordable increases, break out
  1546. if (!foundAffordable) break;
  1547. }
  1548. }
  1549. // Assign back to properties
  1550. strength = stats[0];
  1551. dexterity = stats[1];
  1552. constitution = stats[2];
  1553. wisdom = stats[3];
  1554. perception = stats[4];
  1555. // Set as point-buy mode (not locked like true random)
  1556. isRandomized = false;
  1557. UpdateAvailablePoints();
  1558. }
  1559. } // Alternative: Truly random stats (2-18, locked from editing)
  1560. public void RandomizeAttributesWild()
  1561. {
  1562. if (Application.isPlaying)
  1563. {
  1564. strength = UnityEngine.Random.Range(2, 19); // 2-18 inclusive
  1565. dexterity = UnityEngine.Random.Range(2, 19);
  1566. constitution = UnityEngine.Random.Range(2, 19);
  1567. wisdom = UnityEngine.Random.Range(2, 19);
  1568. perception = UnityEngine.Random.Range(2, 19);
  1569. isRandomized = true;
  1570. availablePoints = 0; // No points available when randomized
  1571. }
  1572. }
  1573. // Reset attributes to default for point-buy
  1574. public void ResetToPointBuy()
  1575. {
  1576. strength = 10;
  1577. dexterity = 10;
  1578. constitution = 10;
  1579. wisdom = 10;
  1580. perception = 10;
  1581. isRandomized = false;
  1582. availablePoints = 22; // Reset to full point pool (adjusted for 5 stats)
  1583. }
  1584. // Calculate point cost for a stat value (point-buy system)
  1585. public static int GetStatCost(int statValue)
  1586. {
  1587. // Point-buy costs: 4=-4pts, 5=-2pts, 6=-1pts, 7=-1pts, 8=0pts, 9=1pt, 10=2pts, 11=3pts, 12=4pts, 13=5pts, 14=7pts, 15=9pts, 16=12pts, 17=16pts, 18=21pts
  1588. switch (statValue)
  1589. {
  1590. case 4: return -4;
  1591. case 5: return -2;
  1592. case 6: return -1;
  1593. case 7: return -1;
  1594. case 8: return 0;
  1595. case 9: return 1;
  1596. case 10: return 2;
  1597. case 11: return 3;
  1598. case 12: return 4;
  1599. case 13: return 5;
  1600. case 14: return 7;
  1601. case 15: return 9;
  1602. case 16: return 12;
  1603. case 17: return 16;
  1604. case 18: return 21;
  1605. default: return statValue < 4 ? -4 : 25; // Invalid values
  1606. }
  1607. }
  1608. // Calculate total points spent
  1609. public int GetTotalPointsSpent()
  1610. {
  1611. return GetStatCost(strength) + GetStatCost(dexterity) + GetStatCost(constitution) + GetStatCost(wisdom) + GetStatCost(perception);
  1612. }
  1613. // Update available points based on current stats
  1614. public void UpdateAvailablePoints()
  1615. {
  1616. if (!isRandomized)
  1617. {
  1618. availablePoints = 22 - GetTotalPointsSpent(); // Changed from 18 to 22 for 5 stats
  1619. }
  1620. }
  1621. // Check if we can afford to increase a stat
  1622. public bool CanIncreaseStat(int currentValue)
  1623. {
  1624. if (isRandomized) return false; // Can't change randomized stats
  1625. if (currentValue >= 18) return false; // Max value
  1626. int currentCost = GetStatCost(currentValue);
  1627. int newCost = GetStatCost(currentValue + 1);
  1628. int costDifference = newCost - currentCost;
  1629. return availablePoints >= costDifference;
  1630. }
  1631. // Create a deep copy of this character
  1632. public TeamCharacter CreateCopy()
  1633. {
  1634. var copy = new TeamCharacter(name, isMale)
  1635. {
  1636. strength = this.strength,
  1637. dexterity = this.dexterity,
  1638. constitution = this.constitution,
  1639. wisdom = this.wisdom,
  1640. perception = this.perception,
  1641. isRandomized = this.isRandomized,
  1642. availablePoints = this.availablePoints,
  1643. gold = this.gold,
  1644. silver = this.silver,
  1645. copper = this.copper,
  1646. equippedWeapon = this.equippedWeapon,
  1647. equippedArmor = this.equippedArmor
  1648. };
  1649. // Deep copy the lists
  1650. copy.weapons = new System.Collections.Generic.List<string>(this.weapons);
  1651. copy.armor = new System.Collections.Generic.List<string>(this.armor);
  1652. copy.miscItems = new System.Collections.Generic.List<string>(this.miscItems);
  1653. return copy;
  1654. }
  1655. // Recalculate all equipment modifiers from items in inventory (temporary solution)
  1656. public void RecalculateEquipmentBonuses()
  1657. {
  1658. // Reset all modifiers to zero
  1659. strengthModifier = 0;
  1660. dexterityModifier = 0;
  1661. constitutionModifier = 0;
  1662. wisdomModifier = 0;
  1663. perceptionModifier = 0;
  1664. acModifier = 0;
  1665. // Get reference to the shop manager to access item definitions
  1666. var shopManager = UnityEngine.Object.FindFirstObjectByType<ItemShopManager>();
  1667. if (shopManager == null) return;
  1668. // Apply bonuses from all items in inventory
  1669. ApplyBonusesFromItemList(shopManager.GetWeapons(), weapons);
  1670. ApplyBonusesFromItemList(shopManager.GetArmor(), armor);
  1671. ApplyBonusesFromItemList(shopManager.GetMiscItems(), miscItems);
  1672. }
  1673. private void ApplyBonusesFromItemList(System.Collections.Generic.List<Item> shopItems, System.Collections.Generic.List<string> ownedItems)
  1674. {
  1675. foreach (string itemName in ownedItems)
  1676. {
  1677. var shopItem = shopItems.Find(item => item.itemName == itemName);
  1678. if (shopItem != null)
  1679. {
  1680. // Apply bonuses based on item type
  1681. if (shopItem is WeaponItem weapon)
  1682. {
  1683. // Weapons might provide damage bonuses, but character stats are typically different
  1684. // For now, we'll focus on armor and misc items for stat bonuses
  1685. }
  1686. else if (shopItem is ArmorItem armor)
  1687. {
  1688. strengthModifier += armor.strengthModifier;
  1689. dexterityModifier += armor.dexterityModifier;
  1690. constitutionModifier += armor.constitutionModifier;
  1691. wisdomModifier += armor.wisdomModifier;
  1692. acModifier += armor.armorClass;
  1693. }
  1694. else if (shopItem is MiscellaneousItem misc)
  1695. {
  1696. // Miscellaneous items might provide stat bonuses if they're permanent equipment
  1697. // For consumables, bonuses would typically be applied when used, not while owned
  1698. if (!misc.isConsumable)
  1699. {
  1700. // Add any permanent stat bonuses from misc items here
  1701. // This would need to be extended based on your specific misc item properties
  1702. }
  1703. }
  1704. }
  1705. }
  1706. }
  1707. // Copy data from another character into this one
  1708. public void CopyFrom(TeamCharacter other)
  1709. {
  1710. if (other == null) return;
  1711. name = other.name;
  1712. isMale = other.isMale;
  1713. strength = other.strength;
  1714. dexterity = other.dexterity;
  1715. constitution = other.constitution;
  1716. wisdom = other.wisdom;
  1717. }
  1718. }