MainTeamSelectScript.cs 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271
  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. // If this is the first weapon, equip it automatically
  407. if (string.IsNullOrEmpty(currentCharacter.equippedWeapon))
  408. {
  409. currentCharacter.equippedWeapon = weaponType;
  410. Debug.Log($"🔧 MainTeamSelect: Auto-equipped first weapon '{weaponType}' for {currentCharacter.name}");
  411. }
  412. SaveCurrentCharacterToSlot();
  413. }
  414. private void OnAddArmorClicked()
  415. {
  416. if (currentCharacter == null) return;
  417. if (shopManager != null)
  418. {
  419. shopManager.OpenShop(currentCharacter);
  420. }
  421. else
  422. {
  423. Debug.LogWarning("No shop manager found - cannot open shop");
  424. }
  425. }
  426. private void OnAddMiscClicked()
  427. {
  428. if (currentCharacter == null) return;
  429. if (shopManager != null)
  430. {
  431. shopManager.OpenShop(currentCharacter);
  432. }
  433. else
  434. {
  435. Debug.LogWarning("No shop manager found - cannot open shop");
  436. }
  437. }
  438. private void AddArmorToCharacter(string armorType)
  439. {
  440. if (currentCharacter.armor == null)
  441. {
  442. currentCharacter.armor = new System.Collections.Generic.List<string>();
  443. }
  444. currentCharacter.armor.Add(armorType);
  445. SaveCurrentCharacterToSlot();
  446. UpdateInventoryUI();
  447. }
  448. private void AddMiscItemToCharacter(string itemType)
  449. {
  450. if (currentCharacter.miscItems == null)
  451. {
  452. currentCharacter.miscItems = new System.Collections.Generic.List<string>();
  453. }
  454. currentCharacter.miscItems.Add(itemType);
  455. SaveCurrentCharacterToSlot();
  456. UpdateInventoryUI();
  457. }
  458. private void OnBankChanged()
  459. {
  460. if (currentCharacter == null) return;
  461. currentCharacter.gold = goldField?.value ?? currentCharacter.gold;
  462. currentCharacter.silver = silverField?.value ?? currentCharacter.silver;
  463. currentCharacter.copper = copperField?.value ?? currentCharacter.copper;
  464. SaveCurrentCharacterToSlot();
  465. }
  466. private void UpdateInventoryUI()
  467. {
  468. if (currentCharacter == null) return;
  469. // Update bank fields
  470. if (goldField != null) goldField.value = currentCharacter.gold;
  471. if (silverField != null) silverField.value = currentCharacter.silver;
  472. if (copperField != null) copperField.value = currentCharacter.copper;
  473. // Update weapon list with equip status
  474. UpdateWeaponListWithEquipStatus(weaponsList, currentCharacter.weapons, currentCharacter.equippedWeapon);
  475. // Update armor list
  476. UpdateItemList(armorList, currentCharacter.armor, "ArmorItemRow", OnRemoveArmor);
  477. // Update misc list
  478. UpdateItemList(miscList, currentCharacter.miscItems, "MiscItemRow", OnRemoveMisc);
  479. }
  480. private void UpdateWeaponListWithEquipStatus(VisualElement container, System.Collections.Generic.List<string> weapons, string equippedWeapon)
  481. {
  482. if (container == null || weapons == null) return;
  483. // Clear existing items (except example rows)
  484. var itemsToRemove = container.Query<VisualElement>(className: "inventory-item-row").ToList()
  485. .Where(item => !item.name.Contains("Example")).ToList();
  486. foreach (var item in itemsToRemove)
  487. {
  488. container.Remove(item);
  489. }
  490. // Add current weapons with equip status
  491. foreach (var weaponName in weapons)
  492. {
  493. var itemRow = new VisualElement();
  494. itemRow.AddToClassList("inventory-item-row");
  495. itemRow.AddToClassList("WeaponItemRow");
  496. bool isEquipped = weaponName == equippedWeapon;
  497. var nameLabel = new Label(isEquipped ? $"[EQUIPPED] {weaponName}" : weaponName);
  498. nameLabel.AddToClassList("item-name-label");
  499. if (isEquipped)
  500. {
  501. nameLabel.style.color = UnityEngine.Color.green;
  502. nameLabel.style.unityFontStyleAndWeight = UnityEngine.FontStyle.Bold;
  503. }
  504. itemRow.Add(nameLabel);
  505. // Equip button (only show if not already equipped)
  506. if (!isEquipped)
  507. {
  508. var equipButton = new Button(() => OnEquipWeapon(weaponName));
  509. equipButton.text = "Equip";
  510. equipButton.AddToClassList("equip-item-button");
  511. itemRow.Add(equipButton);
  512. }
  513. var removeButton = new Button(() => OnRemoveWeapon(weaponName));
  514. removeButton.text = "Remove (Refund)";
  515. removeButton.AddToClassList("remove-item-button");
  516. // Add tooltip for refund information
  517. string refundInfo = GetRefundInfo(weaponName, "weapon");
  518. if (!string.IsNullOrEmpty(refundInfo))
  519. {
  520. removeButton.tooltip = $"Remove and refund: {refundInfo}";
  521. }
  522. itemRow.Add(removeButton);
  523. container.Add(itemRow);
  524. }
  525. }
  526. private void OnEquipWeapon(string weaponName)
  527. {
  528. if (currentCharacter != null && currentCharacter.weapons.Contains(weaponName))
  529. {
  530. currentCharacter.equippedWeapon = weaponName;
  531. Debug.Log($"🔧 MainTeamSelect: Equipped weapon '{weaponName}' for {currentCharacter.name}");
  532. SaveCurrentCharacterToSlot();
  533. UpdateInventoryUI();
  534. }
  535. }
  536. private void UpdateItemList(VisualElement container, System.Collections.Generic.List<string> items, string rowClassName, System.Action<string> removeAction)
  537. {
  538. if (container == null || items == null) return;
  539. // Clear existing items (except example rows)
  540. var itemsToRemove = container.Query<VisualElement>(className: "inventory-item-row").ToList()
  541. .Where(item => !item.name.Contains("Example")).ToList();
  542. foreach (var item in itemsToRemove)
  543. {
  544. container.Remove(item);
  545. }
  546. // Add current items
  547. foreach (var itemName in items)
  548. {
  549. var itemRow = new VisualElement();
  550. itemRow.AddToClassList("inventory-item-row");
  551. itemRow.AddToClassList(rowClassName);
  552. var nameLabel = new Label(itemName);
  553. nameLabel.AddToClassList("item-name-label");
  554. itemRow.Add(nameLabel);
  555. var removeButton = new Button(() => removeAction(itemName));
  556. removeButton.text = "Remove (Refund)";
  557. removeButton.AddToClassList("remove-item-button");
  558. // Add tooltip or title to show refund information
  559. string itemType = GetItemTypeFromClassName(rowClassName);
  560. string refundInfo = GetRefundInfo(itemName, itemType);
  561. if (!string.IsNullOrEmpty(refundInfo))
  562. {
  563. removeButton.tooltip = $"Remove and refund: {refundInfo}";
  564. }
  565. itemRow.Add(removeButton);
  566. container.Add(itemRow);
  567. }
  568. }
  569. private string GetItemTypeFromClassName(string className)
  570. {
  571. if (className.Contains("Weapon")) return "weapon";
  572. if (className.Contains("Armor")) return "armor";
  573. if (className.Contains("Misc")) return "misc";
  574. return "";
  575. }
  576. private string GetRefundInfo(string itemName, string itemType)
  577. {
  578. if (shopManager == null) return "";
  579. List<Item> itemList = null;
  580. switch (itemType.ToLower())
  581. {
  582. case "weapon":
  583. itemList = shopManager.GetWeapons();
  584. break;
  585. case "armor":
  586. itemList = shopManager.GetArmor();
  587. break;
  588. case "misc":
  589. itemList = shopManager.GetMiscItems();
  590. break;
  591. }
  592. if (itemList != null)
  593. {
  594. var shopItem = itemList.Find(item => item.itemName == itemName);
  595. if (shopItem != null)
  596. {
  597. return shopItem.GetCostString();
  598. }
  599. }
  600. return "";
  601. }
  602. private void RefundItemPrice(string itemName, string itemType)
  603. {
  604. if (shopManager == null || currentCharacter == null)
  605. {
  606. Debug.LogWarning($"Cannot refund {itemName}: shop manager or current character is null");
  607. return;
  608. }
  609. // Find the item price from the shop manager
  610. int goldRefund = 0;
  611. int silverRefund = 0;
  612. int copperRefund = 0;
  613. // Check the appropriate list based on item type
  614. List<Item> itemList = null;
  615. switch (itemType.ToLower())
  616. {
  617. case "weapon":
  618. itemList = shopManager.GetWeapons();
  619. break;
  620. case "armor":
  621. itemList = shopManager.GetArmor();
  622. break;
  623. case "misc":
  624. itemList = shopManager.GetMiscItems();
  625. break;
  626. }
  627. if (itemList != null)
  628. {
  629. // Find the item in the shop list
  630. var shopItem = itemList.Find(item => item.itemName == itemName);
  631. if (shopItem != null)
  632. {
  633. goldRefund = shopItem.goldCost;
  634. silverRefund = shopItem.silverCost;
  635. copperRefund = shopItem.copperCost;
  636. // Add the refund to the character's money
  637. currentCharacter.gold += goldRefund;
  638. currentCharacter.silver += silverRefund;
  639. currentCharacter.copper += copperRefund;
  640. }
  641. else
  642. {
  643. Debug.LogWarning($"Could not find {itemName} in shop {itemType} list for refund");
  644. }
  645. }
  646. else
  647. {
  648. Debug.LogWarning($"Could not access shop {itemType} list for refund");
  649. }
  650. }
  651. private void OnRemoveWeapon(string weaponName)
  652. {
  653. if (currentCharacter?.weapons != null)
  654. {
  655. currentCharacter.weapons.Remove(weaponName);
  656. // If this was the equipped weapon, unequip it and equip the first remaining weapon if any
  657. if (currentCharacter.equippedWeapon == weaponName)
  658. {
  659. if (currentCharacter.weapons.Count > 0)
  660. {
  661. currentCharacter.equippedWeapon = currentCharacter.weapons[0];
  662. Debug.Log($"🔧 MainTeamSelect: Equipped new weapon '{currentCharacter.equippedWeapon}' after removing '{weaponName}'");
  663. }
  664. else
  665. {
  666. currentCharacter.equippedWeapon = "";
  667. Debug.Log($"🔧 MainTeamSelect: No weapons left, unequipped '{weaponName}'");
  668. }
  669. }
  670. // Refund the weapon price
  671. RefundItemPrice(weaponName, "weapon");
  672. SaveCurrentCharacterToSlot();
  673. UpdateInventoryUI();
  674. }
  675. }
  676. private void OnRemoveArmor(string armorName)
  677. {
  678. if (currentCharacter?.armor != null)
  679. {
  680. currentCharacter.armor.Remove(armorName);
  681. // Refund the armor price
  682. RefundItemPrice(armorName, "armor");
  683. SaveCurrentCharacterToSlot();
  684. UpdateInventoryUI();
  685. }
  686. }
  687. private void OnRemoveMisc(string itemName)
  688. {
  689. if (currentCharacter?.miscItems != null)
  690. {
  691. currentCharacter.miscItems.Remove(itemName);
  692. // Refund the misc item price
  693. RefundItemPrice(itemName, "misc");
  694. SaveCurrentCharacterToSlot();
  695. UpdateInventoryUI();
  696. }
  697. }
  698. private void UpdateCharacterUI()
  699. {
  700. if (currentCharacter == null)
  701. {
  702. // Clear the UI when no character is selected
  703. if (characterNameField != null) characterNameField.value = "";
  704. if (genderDropdown != null) genderDropdown.value = "Male";
  705. if (strengthField != null) strengthField.value = 10;
  706. if (dexterityField != null) dexterityField.value = 10;
  707. if (constitutionField != null) constitutionField.value = 10;
  708. if (wisdomField != null) wisdomField.value = 10;
  709. // Clear derived stats
  710. if (initField != null) initField.value = 0;
  711. if (damageField != null) damageField.value = 0;
  712. if (spellCastingField != null) spellCastingField.value = 0;
  713. if (movementSpeedField != null) movementSpeedField.value = 30;
  714. if (hpField != null) hpField.value = 10;
  715. if (acField != null) acField.value = 0;
  716. // Clear attribute UI
  717. if (creationModeLabel != null) creationModeLabel.text = "Mode: None";
  718. if (availablePointsLabel != null) availablePointsLabel.text = "Available Points: 0";
  719. return;
  720. }
  721. // Update UI with current character data
  722. if (characterNameField != null)
  723. characterNameField.value = currentCharacter.name;
  724. if (genderDropdown != null)
  725. genderDropdown.value = currentCharacter.isMale ? "Male" : "Female";
  726. if (strengthField != null) strengthField.value = currentCharacter.strength;
  727. if (dexterityField != null) dexterityField.value = currentCharacter.dexterity;
  728. if (constitutionField != null) constitutionField.value = currentCharacter.constitution;
  729. if (wisdomField != null) wisdomField.value = currentCharacter.wisdom;
  730. if (perceptionField != null) perceptionField.value = currentCharacter.perception;
  731. // Recalculate equipment bonuses from inventory
  732. currentCharacter.RecalculateEquipmentBonuses();
  733. UpdateDerivedStats();
  734. UpdateAttributeUI();
  735. UpdateInventoryUI();
  736. }
  737. private void UpdateAttributeUI()
  738. {
  739. if (currentCharacter == null) return;
  740. // Update creation mode display
  741. if (creationModeLabel != null)
  742. {
  743. creationModeLabel.text = "Mode: Point Buy";
  744. }
  745. // Update available points display
  746. if (availablePointsLabel != null)
  747. {
  748. availablePointsLabel.text = $"Available Points: {currentCharacter.availablePoints}";
  749. }
  750. // All stat fields are always editable in the new system
  751. if (strengthField != null) strengthField.SetEnabled(true);
  752. if (dexterityField != null) dexterityField.SetEnabled(true);
  753. if (constitutionField != null) constitutionField.SetEnabled(true);
  754. if (wisdomField != null) wisdomField.SetEnabled(true);
  755. if (perceptionField != null) perceptionField.SetEnabled(true);
  756. }
  757. private void UpdateDerivedStats()
  758. {
  759. if (currentCharacter == null) return;
  760. // Update the read-only derived stats (uses final stats including equipment modifiers)
  761. if (initField != null) initField.value = currentCharacter.Initiative;
  762. if (damageField != null) damageField.value = currentCharacter.DamageBonus;
  763. if (spellCastingField != null) spellCastingField.value = currentCharacter.SpellAC;
  764. if (movementSpeedField != null) movementSpeedField.value = currentCharacter.MovementSpeed;
  765. if (hpField != null) hpField.value = currentCharacter.HitPoints;
  766. if (acField != null) acField.value = currentCharacter.ArmorClass;
  767. }
  768. private void UpdateCurrentSlotButton()
  769. {
  770. // Update the character card information if we have a current slot selected
  771. if (currentSlotIndex >= 0 && currentSlotIndex < characterSlotButtons.Count && currentCharacter != null)
  772. {
  773. UpdateCharacterCard(currentSlotIndex, currentCharacter);
  774. }
  775. }
  776. private void UpdateCharacterCard(int slotIndex, TeamCharacter character)
  777. {
  778. if (slotIndex < 0 || slotIndex >= 4 || character == null) return;
  779. var root = uiDocument.rootVisualElement;
  780. // Find the character slot instance based on index
  781. string[] slotNames = { "Character1", "Character2", "Character3", "Character4" };
  782. var characterSlot = root.Q<VisualElement>(slotNames[slotIndex]);
  783. if (characterSlot == null) return;
  784. // Find the character card button within this slot
  785. var characterCard = characterSlot.Q<Button>("ViewCharacterButton");
  786. if (characterCard == null) return;
  787. // Update character name
  788. var nameLabel = characterCard.Q<Label>("CharacterNameLabel");
  789. if (nameLabel != null)
  790. {
  791. nameLabel.text = character.name;
  792. }
  793. // Update stats
  794. var strengthLabel = characterCard.Q<Label>("StrengthLabel");
  795. if (strengthLabel != null) strengthLabel.text = character.strength.ToString();
  796. var dexterityLabel = characterCard.Q<Label>("DexterityLabel");
  797. if (dexterityLabel != null) dexterityLabel.text = character.dexterity.ToString();
  798. var constitutionLabel = characterCard.Q<Label>("ConstitutionLabel");
  799. if (constitutionLabel != null) constitutionLabel.text = character.constitution.ToString();
  800. var wisdomLabel = characterCard.Q<Label>("WisdomLabel");
  801. if (wisdomLabel != null) wisdomLabel.text = character.wisdom.ToString();
  802. var perceptionLabel = characterCard.Q<Label>("PerceptionLabel");
  803. if (perceptionLabel != null) perceptionLabel.text = character.perception.ToString();
  804. // Update HP and AC
  805. var hpLabel = characterCard.Q<Label>("HPLabel");
  806. if (hpLabel != null) hpLabel.text = $"HP: {character.HitPoints}";
  807. var acLabel = characterCard.Q<Label>("ACLabel");
  808. if (acLabel != null) acLabel.text = $"AC: {character.ArmorClass}";
  809. // Show the character card and hide the create button
  810. var createButton = characterSlot.Q<Button>("CreateNewCharacterButton");
  811. if (createButton != null)
  812. {
  813. createButton.style.display = DisplayStyle.None;
  814. }
  815. characterCard.RemoveFromClassList("disabled-card");
  816. characterCard.style.display = DisplayStyle.Flex;
  817. characterCard.SetEnabled(true);
  818. }
  819. private void SaveCurrentCharacterToSlot()
  820. {
  821. // Save the current character data back to its slot
  822. if (currentSlotIndex >= 0 && currentSlotIndex < characterSlots.Length && currentCharacter != null)
  823. {
  824. characterSlots[currentSlotIndex] = currentCharacter.CreateCopy();
  825. }
  826. }
  827. private void UpdateSlotVisualStates()
  828. {
  829. var root = uiDocument.rootVisualElement;
  830. string[] slotNames = { "Character1", "Character2", "Character3", "Character4" };
  831. // Update visual states of all character slots
  832. for (int i = 0; i < slotNames.Length; i++)
  833. {
  834. var characterSlot = root.Q<VisualElement>(slotNames[i]);
  835. if (characterSlot == null) continue;
  836. // Remove all visual state classes first
  837. characterSlot.RemoveFromClassList("selected-slot");
  838. // Add selected state if this is the current slot
  839. if (i == currentSlotIndex)
  840. {
  841. characterSlot.AddToClassList("selected-slot");
  842. }
  843. // Update character card visibility and data
  844. if (characterSlots[i] != null)
  845. {
  846. // Character exists in this slot
  847. UpdateCharacterCard(i, characterSlots[i]);
  848. }
  849. else
  850. {
  851. // No character in this slot - show create button
  852. var createButton = characterSlot.Q<Button>("CreateNewCharacterButton");
  853. var characterCard = characterSlot.Q<Button>("ViewCharacterButton");
  854. if (createButton != null)
  855. {
  856. createButton.style.display = DisplayStyle.Flex;
  857. }
  858. if (characterCard != null)
  859. {
  860. characterCard.style.display = DisplayStyle.None;
  861. characterCard.AddToClassList("disabled-card");
  862. characterCard.SetEnabled(false);
  863. }
  864. }
  865. }
  866. }
  867. // Example handler if you need to pass data (like an index)
  868. private void OnCreateNewCharacterButtonClicked(int index)
  869. {
  870. // Create a new character with random name
  871. currentCharacter = new TeamCharacter();
  872. // Generate name after construction to avoid serialization issues
  873. currentCharacter.GenerateRandomName();
  874. // Save character to the slot (create a proper copy)
  875. characterSlots[index] = currentCharacter.CreateCopy();
  876. currentSlotIndex = index;
  877. UpdateCharacterUI();
  878. UpdateSlotVisualStates();
  879. // Update navigation buttons immediately after character creation
  880. UpdateNavigationButtons();
  881. // Update the character card for this slot
  882. UpdateCharacterCard(index, currentCharacter);
  883. // Call UpdateNavigationButtons again after UI updates
  884. UpdateNavigationButtons();
  885. }
  886. private void OnViewCharacterButtonClicked(int index)
  887. {
  888. // Check if there's a character in this slot
  889. if (characterSlots[index] != null)
  890. {
  891. // Create a working copy of the character from the slot
  892. currentCharacter = characterSlots[index].CreateCopy();
  893. currentSlotIndex = index;
  894. UpdateCharacterUI();
  895. UpdateSlotVisualStates();
  896. UpdateNavigationButtons();
  897. }
  898. else
  899. {
  900. // Slot is empty, save current character to this slot if we have one
  901. if (currentCharacter != null)
  902. {
  903. // Create a proper copy of the current character data
  904. characterSlots[index] = currentCharacter.CreateCopy();
  905. currentSlotIndex = index;
  906. // Update the character card for this slot
  907. UpdateCharacterCard(index, currentCharacter);
  908. UpdateSlotVisualStates();
  909. UpdateNavigationButtons();
  910. }
  911. }
  912. }
  913. // Start is called once before the first execution of Update after the MonoBehaviour is created
  914. void Start()
  915. {
  916. // You can keep Start if needed for other initialization
  917. }
  918. // Update is called once per frame
  919. void Update()
  920. {
  921. // Debug keys for testing
  922. if (Input.GetKeyDown(KeyCode.F5))
  923. {
  924. DebugCurrentCharacterSlots();
  925. }
  926. if (Input.GetKeyDown(KeyCode.F6))
  927. {
  928. SaveTeamToGameState();
  929. }
  930. if (Input.GetKeyDown(KeyCode.F7))
  931. {
  932. TestPlayerPrefsData();
  933. }
  934. }
  935. private void DebugCurrentCharacterSlots()
  936. {
  937. for (int i = 0; i < characterSlots.Length; i++)
  938. {
  939. if (characterSlots[i] != null)
  940. {
  941. var character = characterSlots[i];
  942. }
  943. else
  944. {
  945. }
  946. }
  947. }
  948. private void TestPlayerPrefsData()
  949. {
  950. for (int i = 0; i < 4; i++)
  951. {
  952. string existsKey = $"Character{i}_Exists";
  953. if (PlayerPrefs.HasKey(existsKey))
  954. {
  955. int exists = PlayerPrefs.GetInt(existsKey);
  956. if (exists == 1)
  957. {
  958. string prefix = $"Character{i}_";
  959. string name = PlayerPrefs.GetString(prefix + "Name", "UNKNOWN");
  960. int str = PlayerPrefs.GetInt(prefix + "Strength", 0);
  961. int dex = PlayerPrefs.GetInt(prefix + "Dexterity", 0);
  962. int con = PlayerPrefs.GetInt(prefix + "Constitution", 0);
  963. int wis = PlayerPrefs.GetInt(prefix + "Wisdom", 0);
  964. }
  965. }
  966. else
  967. {
  968. }
  969. }
  970. }
  971. void OnDestroy()
  972. {
  973. // Clean up shop manager callbacks to prevent memory leaks
  974. if (shopManager != null)
  975. {
  976. shopManager.OnCharacterDataChanged -= OnShopCharacterDataChanged;
  977. }
  978. }
  979. #region Navigation Methods
  980. private void OnBackToTitleClicked()
  981. {
  982. // Check if team is finalized and this is acting as "New Game" button
  983. if (IsTeamFinalized())
  984. {
  985. // Show confirmation dialog for starting new game
  986. #if UNITY_EDITOR
  987. bool confirmed = UnityEditor.EditorUtility.DisplayDialog(
  988. "Start New Game",
  989. "This will start a completely new game and overwrite your current progress.\n\nAre you sure you want to continue?",
  990. "Start New Game",
  991. "Cancel"
  992. );
  993. if (confirmed)
  994. {
  995. StartNewGame();
  996. }
  997. #else
  998. // In builds, we'll assume user confirms for now
  999. // In a real game, implement a proper UI dialog system
  1000. Debug.LogWarning("Starting new game - implement proper dialog for builds");
  1001. StartNewGame();
  1002. #endif
  1003. }
  1004. else
  1005. {
  1006. // Normal back to title behavior
  1007. SceneManager.LoadScene("TitleScreenScene");
  1008. }
  1009. }
  1010. private void StartNewGame()
  1011. {
  1012. // Initialize GameStateManager for new game
  1013. if (GameStateManager.Instance != null)
  1014. {
  1015. GameStateManager.Instance.StartNewGame();
  1016. }
  1017. // Clear all save data
  1018. ClearAllSaveData();
  1019. // Reload the scene to start fresh
  1020. SceneManager.LoadScene("MainTeamSelectScene");
  1021. }
  1022. private void ClearAllSaveData()
  1023. {
  1024. // Clear GameStateManager data
  1025. if (GameStateManager.Instance != null)
  1026. {
  1027. GameStateManager.Instance.teamSetupComplete = false;
  1028. GameStateManager.Instance.hasGeneratedMap = false;
  1029. }
  1030. // Clear PlayerPrefs data
  1031. for (int i = 0; i < 4; i++)
  1032. {
  1033. string prefix = $"Character{i}_";
  1034. PlayerPrefs.DeleteKey($"Character{i}_Exists");
  1035. PlayerPrefs.DeleteKey(prefix + "Name");
  1036. PlayerPrefs.DeleteKey(prefix + "IsMale");
  1037. PlayerPrefs.DeleteKey(prefix + "Strength");
  1038. PlayerPrefs.DeleteKey(prefix + "Dexterity");
  1039. PlayerPrefs.DeleteKey(prefix + "Constitution");
  1040. PlayerPrefs.DeleteKey(prefix + "Wisdom");
  1041. PlayerPrefs.DeleteKey(prefix + "Gold");
  1042. PlayerPrefs.DeleteKey(prefix + "Silver");
  1043. PlayerPrefs.DeleteKey(prefix + "Copper");
  1044. }
  1045. // Clear map data
  1046. PlayerPrefs.DeleteKey("HasGeneratedMap");
  1047. PlayerPrefs.DeleteKey("MapSeed");
  1048. PlayerPrefs.DeleteKey("TeamSize");
  1049. PlayerPrefs.DeleteKey("TeamSetupComplete");
  1050. PlayerPrefs.DeleteKey("GameSaved");
  1051. PlayerPrefs.Save();
  1052. }
  1053. private void OnProceedToBattleClicked()
  1054. {
  1055. // Check if team is already finalized
  1056. if (IsTeamFinalized())
  1057. {
  1058. // Team is finalized, return to MapScene2
  1059. SceneManager.LoadScene("MapScene2");
  1060. return;
  1061. }
  1062. // Check if we have at least one character
  1063. if (!HasAtLeastOneCharacter())
  1064. {
  1065. Debug.LogWarning("Need at least one character to proceed to battle!");
  1066. // TODO: Show message to user
  1067. return;
  1068. }
  1069. // Save all configured characters before proceeding
  1070. SaveTeamToGameState();
  1071. // Mark that the team has proceeded to the map (finalized)
  1072. // Save to both GameStateManager and PlayerPrefs for redundancy
  1073. if (GameStateManager.Instance != null)
  1074. {
  1075. GameStateManager.Instance.teamSetupComplete = true;
  1076. GameStateManager.Instance.SaveGame();
  1077. }
  1078. // Also save to PlayerPrefs as backup
  1079. PlayerPrefs.SetInt("TeamSetupComplete", 1);
  1080. PlayerPrefs.Save();
  1081. SceneManager.LoadScene("MapScene2");
  1082. }
  1083. private void SaveTeamToGameState()
  1084. {
  1085. // Save team data to GameStateManager for persistence
  1086. List<TeamCharacter> configuredCharacters = new List<TeamCharacter>();
  1087. for (int i = 0; i < characterSlots.Length; i++)
  1088. {
  1089. if (characterSlots[i] != null)
  1090. {
  1091. configuredCharacters.Add(characterSlots[i]);
  1092. // Save individual character data
  1093. SaveCharacterToPlayerPrefs(characterSlots[i], i);
  1094. // Verify the save immediately
  1095. PlayerPrefs.SetInt($"Character{i}_Exists", 1);
  1096. string testName = PlayerPrefs.GetString($"Character{i}_Name", "NOT_FOUND");
  1097. }
  1098. else
  1099. {
  1100. // Clear any existing character data for empty slots
  1101. PlayerPrefs.DeleteKey($"Character{i}_Exists");
  1102. }
  1103. }
  1104. // Save team composition info
  1105. PlayerPrefs.SetInt("TeamSize", configuredCharacters.Count);
  1106. // Update GameStateManager if available
  1107. if (GameStateManager.Instance != null)
  1108. {
  1109. // Copy our team to the GameStateManager
  1110. for (int i = 0; i < characterSlots.Length; i++)
  1111. {
  1112. if (characterSlots[i] != null)
  1113. {
  1114. GameStateManager.Instance.savedTeam[i] = characterSlots[i].CreateCopy();
  1115. }
  1116. else
  1117. {
  1118. GameStateManager.Instance.savedTeam[i] = null;
  1119. }
  1120. }
  1121. GameStateManager.Instance.teamSetupComplete = true;
  1122. GameStateManager.Instance.SaveGame();
  1123. }
  1124. else
  1125. {
  1126. Debug.LogWarning("GameStateManager.Instance is null!");
  1127. }
  1128. // Log configured team for MapScene
  1129. foreach (var character in configuredCharacters)
  1130. {
  1131. }
  1132. PlayerPrefs.Save(); // Ensure data is written to disk
  1133. }
  1134. public List<TeamCharacter> GetConfiguredCharacters()
  1135. {
  1136. // Public method to get all configured characters (useful for other scripts)
  1137. List<TeamCharacter> configuredCharacters = new List<TeamCharacter>();
  1138. for (int i = 0; i < characterSlots.Length; i++)
  1139. {
  1140. if (characterSlots[i] != null)
  1141. {
  1142. configuredCharacters.Add(characterSlots[i]);
  1143. }
  1144. }
  1145. return configuredCharacters;
  1146. }
  1147. private void UpdateNavigationButtons()
  1148. {
  1149. // Enable/disable proceed button based on team status
  1150. if (proceedToBattleButton != null)
  1151. {
  1152. bool canProceed = HasAtLeastOneCharacter();
  1153. proceedToBattleButton.SetEnabled(canProceed);
  1154. // Also remove/add visual disabled state
  1155. if (!canProceed)
  1156. {
  1157. proceedToBattleButton.AddToClassList("disabled-button");
  1158. proceedToBattleButton.tooltip = "Create at least one character to proceed";
  1159. }
  1160. else
  1161. {
  1162. proceedToBattleButton.RemoveFromClassList("disabled-button");
  1163. proceedToBattleButton.tooltip = "Start adventure with your team";
  1164. // Force remove any disabled classes that might be interfering
  1165. proceedToBattleButton.RemoveFromClassList("unity-disabled");
  1166. }
  1167. }
  1168. else
  1169. {
  1170. Debug.LogWarning("UpdateNavigationButtons: proceedToBattleButton is null! The button name in the UI might be different than expected.");
  1171. Debug.LogWarning("Please check that a button with name 'ProceedToBattleButton' exists in your UI Document.");
  1172. // Try to find the button again with common alternative names
  1173. var root = uiDocument?.rootVisualElement;
  1174. if (root != null)
  1175. {
  1176. proceedToBattleButton = root.Q<Button>("ProceedButton") ??
  1177. root.Q<Button>("StartButton") ??
  1178. root.Q<Button>("BattleButton") ??
  1179. root.Q<Button>("ProceedToBattleButton");
  1180. if (proceedToBattleButton != null)
  1181. {
  1182. // Recursively call this method now that we found the button
  1183. UpdateNavigationButtons();
  1184. }
  1185. }
  1186. }
  1187. }
  1188. private bool HasAtLeastOneCharacter()
  1189. {
  1190. int characterCount = 0;
  1191. for (int i = 0; i < characterSlots.Length; i++)
  1192. {
  1193. if (characterSlots[i] != null)
  1194. {
  1195. characterCount++;
  1196. }
  1197. else
  1198. {
  1199. }
  1200. }
  1201. bool hasCharacters = characterCount > 0;
  1202. return hasCharacters;
  1203. }
  1204. #endregion
  1205. #region Save/Load Team Data
  1206. private void LoadSavedTeamData()
  1207. {
  1208. // Try to load from GameStateManager first (if available and has data)
  1209. if (GameStateManager.Instance != null && GameStateManager.Instance.savedTeam != null)
  1210. {
  1211. for (int i = 0; i < characterSlots.Length && i < GameStateManager.Instance.savedTeam.Length; i++)
  1212. {
  1213. if (GameStateManager.Instance.savedTeam[i] != null)
  1214. {
  1215. characterSlots[i] = GameStateManager.Instance.savedTeam[i].CreateCopy();
  1216. // Update the slot button
  1217. if (i < characterSlotButtons.Count)
  1218. {
  1219. characterSlotButtons[i].text = characterSlots[i].name;
  1220. characterSlotButtons[i].SetEnabled(true);
  1221. characterSlotButtons[i].RemoveFromClassList("unity-disabled");
  1222. characterSlotButtons[i].RemoveFromClassList("DisabledCharacterCard");
  1223. // Hide the create button
  1224. if (i < createNewCharacterButtons.Count)
  1225. {
  1226. createNewCharacterButtons[i].style.display = DisplayStyle.None;
  1227. }
  1228. }
  1229. }
  1230. }
  1231. }
  1232. // Always also try to load from PlayerPrefs (either as backup or primary)
  1233. for (int i = 0; i < characterSlots.Length; i++)
  1234. {
  1235. // If we haven't loaded this slot from GameStateManager, try PlayerPrefs
  1236. if (characterSlots[i] == null && PlayerPrefs.HasKey($"Character{i}_Exists") && PlayerPrefs.GetInt($"Character{i}_Exists") == 1)
  1237. {
  1238. // Load character data from PlayerPrefs
  1239. characterSlots[i] = LoadCharacterFromPlayerPrefs(i);
  1240. // Update the slot button
  1241. if (i < characterSlotButtons.Count)
  1242. {
  1243. characterSlotButtons[i].text = characterSlots[i].name;
  1244. characterSlotButtons[i].SetEnabled(true);
  1245. characterSlotButtons[i].RemoveFromClassList("unity-disabled");
  1246. characterSlotButtons[i].RemoveFromClassList("DisabledCharacterCard");
  1247. // Hide the create button
  1248. if (i < createNewCharacterButtons.Count)
  1249. {
  1250. createNewCharacterButtons[i].style.display = DisplayStyle.None;
  1251. }
  1252. }
  1253. }
  1254. }
  1255. // Count loaded characters
  1256. int loadedCount = 0;
  1257. for (int i = 0; i < characterSlots.Length; i++)
  1258. {
  1259. if (characterSlots[i] != null) loadedCount++;
  1260. }
  1261. }
  1262. private void SaveCurrentTeamToGameState()
  1263. {
  1264. // Save the current team using PlayerPrefs for now
  1265. for (int i = 0; i < characterSlots.Length; i++)
  1266. {
  1267. if (characterSlots[i] != null)
  1268. {
  1269. SaveCharacterToPlayerPrefs(characterSlots[i], i);
  1270. PlayerPrefs.SetInt($"Character{i}_Exists", 1);
  1271. }
  1272. else
  1273. {
  1274. PlayerPrefs.SetInt($"Character{i}_Exists", 0);
  1275. }
  1276. }
  1277. PlayerPrefs.Save();
  1278. }
  1279. private TeamCharacter LoadCharacterFromPlayerPrefs(int index)
  1280. {
  1281. string prefix = $"Character{index}_";
  1282. var character = new TeamCharacter();
  1283. character.name = PlayerPrefs.GetString(prefix + "Name", "");
  1284. character.isMale = PlayerPrefs.GetInt(prefix + "IsMale", 1) == 1;
  1285. character.strength = PlayerPrefs.GetInt(prefix + "Strength", 10);
  1286. character.dexterity = PlayerPrefs.GetInt(prefix + "Dexterity", 10);
  1287. character.constitution = PlayerPrefs.GetInt(prefix + "Constitution", 10);
  1288. character.wisdom = PlayerPrefs.GetInt(prefix + "Wisdom", 10);
  1289. character.perception = PlayerPrefs.GetInt(prefix + "Perception", 10);
  1290. character.gold = PlayerPrefs.GetInt(prefix + "Gold", 25);
  1291. character.silver = PlayerPrefs.GetInt(prefix + "Silver", 0);
  1292. character.copper = PlayerPrefs.GetInt(prefix + "Copper", 0);
  1293. // Load equipped weapon
  1294. character.equippedWeapon = PlayerPrefs.GetString(prefix + "EquippedWeapon", "");
  1295. // Load weapon list
  1296. int weaponCount = PlayerPrefs.GetInt(prefix + "WeaponCount", 0);
  1297. character.weapons = new System.Collections.Generic.List<string>();
  1298. for (int i = 0; i < weaponCount; i++)
  1299. {
  1300. string weapon = PlayerPrefs.GetString(prefix + $"Weapon{i}", "");
  1301. if (!string.IsNullOrEmpty(weapon))
  1302. {
  1303. character.weapons.Add(weapon);
  1304. }
  1305. }
  1306. // Load armor list
  1307. int armorCount = PlayerPrefs.GetInt(prefix + "ArmorCount", 0);
  1308. character.armor = new System.Collections.Generic.List<string>();
  1309. for (int i = 0; i < armorCount; i++)
  1310. {
  1311. string armor = PlayerPrefs.GetString(prefix + $"Armor{i}", "");
  1312. if (!string.IsNullOrEmpty(armor))
  1313. {
  1314. character.armor.Add(armor);
  1315. }
  1316. }
  1317. // Load misc items
  1318. int miscCount = PlayerPrefs.GetInt(prefix + "MiscCount", 0);
  1319. character.miscItems = new System.Collections.Generic.List<string>();
  1320. for (int i = 0; i < miscCount; i++)
  1321. {
  1322. string misc = PlayerPrefs.GetString(prefix + $"Misc{i}", "");
  1323. if (!string.IsNullOrEmpty(misc))
  1324. {
  1325. character.miscItems.Add(misc);
  1326. }
  1327. }
  1328. // Load equipped armor
  1329. character.equippedArmor = PlayerPrefs.GetString(prefix + "EquippedArmor", "");
  1330. // If no equipped weapon but has weapons, equip the first one
  1331. if (string.IsNullOrEmpty(character.equippedWeapon) && character.weapons.Count > 0)
  1332. {
  1333. character.equippedWeapon = character.weapons[0];
  1334. Debug.Log($"🔧 LoadCharacter: Auto-equipped first weapon '{character.equippedWeapon}' for loaded character {character.name}");
  1335. }
  1336. // Recalculate equipment bonuses from inventory after loading
  1337. character.RecalculateEquipmentBonuses();
  1338. return character;
  1339. }
  1340. private void SaveCharacterToPlayerPrefs(TeamCharacter character, int index)
  1341. {
  1342. string prefix = $"Character{index}_";
  1343. PlayerPrefs.SetString(prefix + "Name", character.name);
  1344. PlayerPrefs.SetInt(prefix + "IsMale", character.isMale ? 1 : 0);
  1345. PlayerPrefs.SetInt(prefix + "Strength", character.strength);
  1346. PlayerPrefs.SetInt(prefix + "Dexterity", character.dexterity);
  1347. PlayerPrefs.SetInt(prefix + "Constitution", character.constitution);
  1348. PlayerPrefs.SetInt(prefix + "Wisdom", character.wisdom);
  1349. PlayerPrefs.SetInt(prefix + "Perception", character.perception);
  1350. PlayerPrefs.SetInt(prefix + "Gold", character.gold);
  1351. PlayerPrefs.SetInt(prefix + "Silver", character.silver);
  1352. PlayerPrefs.SetInt(prefix + "Copper", character.copper);
  1353. // Save equipped weapon
  1354. PlayerPrefs.SetString(prefix + "EquippedWeapon", character.equippedWeapon ?? "");
  1355. // Save weapon list
  1356. if (character.weapons != null)
  1357. {
  1358. PlayerPrefs.SetInt(prefix + "WeaponCount", character.weapons.Count);
  1359. for (int i = 0; i < character.weapons.Count; i++)
  1360. {
  1361. PlayerPrefs.SetString(prefix + $"Weapon{i}", character.weapons[i]);
  1362. }
  1363. }
  1364. else
  1365. {
  1366. PlayerPrefs.SetInt(prefix + "WeaponCount", 0);
  1367. }
  1368. // Save armor list
  1369. if (character.armor != null)
  1370. {
  1371. PlayerPrefs.SetInt(prefix + "ArmorCount", character.armor.Count);
  1372. for (int i = 0; i < character.armor.Count; i++)
  1373. {
  1374. PlayerPrefs.SetString(prefix + $"Armor{i}", character.armor[i]);
  1375. }
  1376. }
  1377. else
  1378. {
  1379. PlayerPrefs.SetInt(prefix + "ArmorCount", 0);
  1380. }
  1381. // Save misc items
  1382. if (character.miscItems != null)
  1383. {
  1384. PlayerPrefs.SetInt(prefix + "MiscCount", character.miscItems.Count);
  1385. for (int i = 0; i < character.miscItems.Count; i++)
  1386. {
  1387. PlayerPrefs.SetString(prefix + $"Misc{i}", character.miscItems[i]);
  1388. }
  1389. }
  1390. else
  1391. {
  1392. PlayerPrefs.SetInt(prefix + "MiscCount", 0);
  1393. }
  1394. // Save equipped armor
  1395. PlayerPrefs.SetString(prefix + "EquippedArmor", character.equippedArmor ?? "");
  1396. // Immediately verify what was saved
  1397. string savedName = PlayerPrefs.GetString(prefix + "Name", "FAILED_TO_SAVE");
  1398. int savedStr = PlayerPrefs.GetInt(prefix + "Strength", -1);
  1399. string savedWeapon = PlayerPrefs.GetString(prefix + "EquippedWeapon", "FAILED_TO_SAVE");
  1400. Debug.Log($"💾 SaveCharacter: Saved {character.name} with equipped weapon '{character.equippedWeapon}' -> verified as '{savedWeapon}'");
  1401. if (savedName != character.name)
  1402. {
  1403. Debug.LogError($" ERROR: Name save failed! Expected '{character.name}', got '{savedName}'");
  1404. }
  1405. }
  1406. #endregion
  1407. #region Team Finalization
  1408. private bool IsTeamFinalized()
  1409. {
  1410. // Check if the team has been finalized (player clicked "Proceed to Battle" and went to MapScene)
  1411. // This is indicated by TeamSetupComplete being true or HasGeneratedMap being true
  1412. bool hasGeneratedMap = PlayerPrefs.HasKey("HasGeneratedMap") && PlayerPrefs.GetInt("HasGeneratedMap") == 1;
  1413. bool teamSetupCompletePrefs = PlayerPrefs.HasKey("TeamSetupComplete") && PlayerPrefs.GetInt("TeamSetupComplete") == 1;
  1414. bool teamSetupCompleteGameState = false;
  1415. if (GameStateManager.Instance != null)
  1416. {
  1417. teamSetupCompleteGameState = GameStateManager.Instance.teamSetupComplete;
  1418. }
  1419. bool finalized = hasGeneratedMap || teamSetupCompletePrefs || teamSetupCompleteGameState;
  1420. return finalized;
  1421. }
  1422. private void SetTeamFinalizedMode()
  1423. {
  1424. // Disable all character creation and editing
  1425. foreach (var button in createNewCharacterButtons)
  1426. {
  1427. button.SetEnabled(false);
  1428. button.style.opacity = 0.5f;
  1429. button.tooltip = "Team has been finalized - cannot create new characters";
  1430. }
  1431. // Disable character editing fields
  1432. DisableCharacterEditingFields();
  1433. // Change the proceed button to "Return to Adventure"
  1434. if (proceedToBattleButton != null)
  1435. {
  1436. proceedToBattleButton.text = "Return to Adventure";
  1437. proceedToBattleButton.tooltip = "Return to your ongoing adventure";
  1438. }
  1439. // Change the back button to offer new game option
  1440. if (backToTitleButton != null)
  1441. {
  1442. backToTitleButton.text = "New Game";
  1443. backToTitleButton.tooltip = "Start a completely new game (will overwrite current save)";
  1444. }
  1445. // Show a message that team is finalized
  1446. }
  1447. private void DisableCharacterEditingFields()
  1448. {
  1449. // Disable name editing
  1450. if (characterNameField != null)
  1451. {
  1452. characterNameField.SetEnabled(false);
  1453. characterNameField.style.opacity = 0.7f;
  1454. }
  1455. if (randomizeNameButton != null)
  1456. {
  1457. randomizeNameButton.SetEnabled(false);
  1458. randomizeNameButton.style.opacity = 0.5f;
  1459. }
  1460. if (genderDropdown != null)
  1461. {
  1462. genderDropdown.SetEnabled(false);
  1463. genderDropdown.style.opacity = 0.7f;
  1464. }
  1465. // Disable stat editing
  1466. if (strengthField != null) strengthField.SetEnabled(false);
  1467. if (dexterityField != null) dexterityField.SetEnabled(false);
  1468. if (constitutionField != null) constitutionField.SetEnabled(false);
  1469. if (wisdomField != null) wisdomField.SetEnabled(false);
  1470. // Disable attribute buttons
  1471. if (randomizeAttributesButton != null)
  1472. {
  1473. randomizeAttributesButton.SetEnabled(false);
  1474. randomizeAttributesButton.style.opacity = 0.5f;
  1475. }
  1476. if (resetToPointBuyButton != null)
  1477. {
  1478. resetToPointBuyButton.SetEnabled(false);
  1479. resetToPointBuyButton.style.opacity = 0.5f;
  1480. }
  1481. // Disable inventory management
  1482. if (addWeaponButton != null)
  1483. {
  1484. addWeaponButton.SetEnabled(false);
  1485. addWeaponButton.style.opacity = 0.5f;
  1486. }
  1487. if (addArmorButton != null)
  1488. {
  1489. addArmorButton.SetEnabled(false);
  1490. addArmorButton.style.opacity = 0.5f;
  1491. }
  1492. if (addMiscButton != null)
  1493. {
  1494. addMiscButton.SetEnabled(false);
  1495. addMiscButton.style.opacity = 0.5f;
  1496. }
  1497. // Disable bank editing
  1498. if (goldField != null) goldField.SetEnabled(false);
  1499. if (silverField != null) silverField.SetEnabled(false);
  1500. if (copperField != null) copperField.SetEnabled(false);
  1501. }
  1502. #endregion
  1503. private System.Collections.IEnumerator RefreshShopManagerReference()
  1504. {
  1505. // Wait for a short delay to allow for potential late initialization
  1506. yield return new WaitForSeconds(0.1f);
  1507. // Try to find the shop manager again
  1508. var newShopManager = FindFirstObjectByType<ItemShopManager>();
  1509. if (newShopManager != null)
  1510. {
  1511. shopManager = newShopManager;
  1512. SetupShopManagerCallbacks();
  1513. }
  1514. else
  1515. {
  1516. Debug.LogWarning("Still no ItemShopManager found after delay. You may need to create one manually using the ShopSystemSetup component.");
  1517. }
  1518. }
  1519. private void SetupShopManagerCallbacks()
  1520. {
  1521. if (shopManager != null)
  1522. {
  1523. // Subscribe to character data changes from the shop
  1524. shopManager.OnCharacterDataChanged += OnShopCharacterDataChanged;
  1525. }
  1526. }
  1527. private void OnShopCharacterDataChanged(TeamCharacter updatedCharacter)
  1528. {
  1529. if (updatedCharacter == null || currentCharacter == null)
  1530. {
  1531. Debug.LogWarning("OnShopCharacterDataChanged: updatedCharacter or currentCharacter is null");
  1532. return;
  1533. }
  1534. // Copy the updated data back to the current character
  1535. // This ensures the character object reference remains the same but data is updated
  1536. currentCharacter.gold = updatedCharacter.gold;
  1537. currentCharacter.silver = updatedCharacter.silver;
  1538. currentCharacter.copper = updatedCharacter.copper;
  1539. // Update inventory lists (create new lists to avoid reference issues)
  1540. currentCharacter.weapons = new System.Collections.Generic.List<string>(updatedCharacter.weapons);
  1541. currentCharacter.armor = new System.Collections.Generic.List<string>(updatedCharacter.armor);
  1542. currentCharacter.miscItems = new System.Collections.Generic.List<string>(updatedCharacter.miscItems);
  1543. // Update the UI to reflect the changes
  1544. UpdateInventoryUI();
  1545. // Save the updated character to the slot
  1546. SaveCurrentCharacterToSlot();
  1547. }
  1548. // Clear all equipment from existing characters to ensure shop-only acquisition
  1549. private void ClearAllCharacterEquipment()
  1550. {
  1551. // Clear equipment from any existing characters in slots
  1552. for (int i = 0; i < characterSlots.Length; i++)
  1553. {
  1554. if (characterSlots[i] != null)
  1555. {
  1556. characterSlots[i].weapons.Clear();
  1557. characterSlots[i].armor.Clear();
  1558. characterSlots[i].miscItems.Clear();
  1559. characterSlots[i].equippedWeapon = "";
  1560. characterSlots[i].equippedArmor = "";
  1561. }
  1562. }
  1563. // Also clear equipment from current character if it exists
  1564. if (currentCharacter != null)
  1565. {
  1566. currentCharacter.weapons.Clear();
  1567. currentCharacter.armor.Clear();
  1568. currentCharacter.miscItems.Clear();
  1569. currentCharacter.equippedWeapon = "";
  1570. currentCharacter.equippedArmor = "";
  1571. }
  1572. }
  1573. }
  1574. [System.Serializable]
  1575. public class TeamCharacter
  1576. {
  1577. public string name = "";
  1578. public bool isMale = true;
  1579. // Base attributes (can be modified by equipment in the future)
  1580. public int strength = 10;
  1581. public int dexterity = 10;
  1582. public int constitution = 10;
  1583. public int wisdom = 10;
  1584. public int perception = 10;
  1585. // Character creation mode
  1586. public bool isRandomized = false; // Track if stats were randomized
  1587. public int availablePoints = 22; // Point-buy system (adjusted for 5 stats instead of 4)
  1588. // Equipment modifiers (for future use)
  1589. public int strengthModifier = 0;
  1590. public int dexterityModifier = 0;
  1591. public int constitutionModifier = 0;
  1592. public int wisdomModifier = 0;
  1593. public int perceptionModifier = 0;
  1594. public int acModifier = 0; // Direct AC bonuses from equipment
  1595. // Currency
  1596. public int gold = 25; // Reduced starting money to make shop purchases more strategic
  1597. public int silver = 0;
  1598. public int copper = 0;
  1599. // Equipment/Inventory (simple string-based for now)
  1600. public System.Collections.Generic.List<string> weapons = new System.Collections.Generic.List<string>();
  1601. public System.Collections.Generic.List<string> armor = new System.Collections.Generic.List<string>();
  1602. public System.Collections.Generic.List<string> miscItems = new System.Collections.Generic.List<string>();
  1603. public string equippedWeapon = "";
  1604. public string equippedArmor = "";
  1605. // Final attributes (base + equipment modifiers)
  1606. public int FinalStrength => strength + strengthModifier;
  1607. public int FinalDexterity => dexterity + dexterityModifier;
  1608. public int FinalConstitution => constitution + constitutionModifier;
  1609. public int FinalWisdom => wisdom + wisdomModifier;
  1610. public int FinalPerception => perception + perceptionModifier;
  1611. // Derived stats (calculated from final stats)
  1612. public int Initiative => FinalDexterity - 10;
  1613. public int DamageBonus => (FinalStrength - 10) / 2;
  1614. public int SpellAC => FinalWisdom - 10; // Renamed from SpellCastingBonus
  1615. public int MovementSpeed => 30 + (int)(Mathf.Ceil((FinalDexterity - 10) / 5.0f) * 5); // Rounded to closest 5 above
  1616. public int HitPoints => Mathf.Max(10, 10 + (FinalConstitution - 10) * 2 + (FinalStrength - 10) + (FinalDexterity - 10) / 2);
  1617. public int ArmorClass => 10 + (FinalDexterity - 10) / 2 + (FinalConstitution - 10) / 3 + acModifier; // Base 10 + DEX bonus + small CON bonus + equipment AC
  1618. public TeamCharacter()
  1619. {
  1620. // Don't generate random name in constructor to avoid serialization issues
  1621. // Name will be generated explicitly when needed
  1622. }
  1623. public TeamCharacter(string characterName, bool male = true)
  1624. {
  1625. name = characterName;
  1626. isMale = male;
  1627. }
  1628. public void GenerateRandomName()
  1629. {
  1630. // Only generate names when the application is playing to avoid serialization issues
  1631. if (Application.isPlaying)
  1632. {
  1633. name = FantasyNameGenerator.GenerateCharacterName(isMale);
  1634. }
  1635. else
  1636. {
  1637. // Fallback name for serialization/design time
  1638. name = isMale ? "New Male Character" : "New Female Character";
  1639. }
  1640. }
  1641. public void SetGender(bool male)
  1642. {
  1643. isMale = male;
  1644. }
  1645. // Randomize all attributes using point-buy system (22 points)
  1646. public void RandomizeAttributes()
  1647. {
  1648. if (Application.isPlaying)
  1649. {
  1650. // Start with random base values (4-12 range for variety)
  1651. int[] stats = new int[5];
  1652. for (int i = 0; i < 5; i++)
  1653. {
  1654. stats[i] = UnityEngine.Random.Range(4, 13); // Random start between 4-12
  1655. }
  1656. // Calculate how many points we've spent so far
  1657. int pointsSpent = 0;
  1658. for (int i = 0; i < 5; i++)
  1659. {
  1660. pointsSpent += GetStatCost(stats[i]);
  1661. }
  1662. int pointsRemaining = 22 - pointsSpent; // Changed from 18 to 22 for 5 stats
  1663. // If we're over budget, reduce some stats
  1664. while (pointsRemaining < 0)
  1665. {
  1666. int randomStat = UnityEngine.Random.Range(0, 5);
  1667. if (stats[randomStat] > 4) // Don't go below 4
  1668. {
  1669. int oldCost = GetStatCost(stats[randomStat]);
  1670. stats[randomStat]--;
  1671. int newCost = GetStatCost(stats[randomStat]);
  1672. pointsRemaining += (oldCost - newCost);
  1673. }
  1674. }
  1675. // Now spend remaining points randomly
  1676. while (pointsRemaining > 0)
  1677. {
  1678. // Pick a random stat to increase
  1679. int randomStat = UnityEngine.Random.Range(0, 5);
  1680. // Check if we can afford to increase this stat
  1681. int currentValue = stats[randomStat];
  1682. if (currentValue >= 18) continue; // Can't go higher than 18
  1683. int currentCost = GetStatCost(currentValue);
  1684. int newCost = GetStatCost(currentValue + 1);
  1685. int costDifference = newCost - currentCost;
  1686. if (pointsRemaining >= costDifference)
  1687. {
  1688. stats[randomStat]++;
  1689. pointsRemaining -= costDifference;
  1690. }
  1691. else
  1692. {
  1693. // If we can't afford any increases, try to find a stat we can afford
  1694. bool foundAffordable = false;
  1695. for (int i = 0; i < 5; i++)
  1696. {
  1697. if (stats[i] < 18)
  1698. {
  1699. int testCurrentCost = GetStatCost(stats[i]);
  1700. int testNewCost = GetStatCost(stats[i] + 1);
  1701. int testCostDiff = testNewCost - testCurrentCost;
  1702. if (pointsRemaining >= testCostDiff)
  1703. {
  1704. foundAffordable = true;
  1705. break;
  1706. }
  1707. }
  1708. }
  1709. // If no affordable increases, break out
  1710. if (!foundAffordable) break;
  1711. }
  1712. }
  1713. // Assign back to properties
  1714. strength = stats[0];
  1715. dexterity = stats[1];
  1716. constitution = stats[2];
  1717. wisdom = stats[3];
  1718. perception = stats[4];
  1719. // Set as point-buy mode (not locked like true random)
  1720. isRandomized = false;
  1721. UpdateAvailablePoints();
  1722. }
  1723. } // Alternative: Truly random stats (2-18, locked from editing)
  1724. public void RandomizeAttributesWild()
  1725. {
  1726. if (Application.isPlaying)
  1727. {
  1728. strength = UnityEngine.Random.Range(2, 19); // 2-18 inclusive
  1729. dexterity = UnityEngine.Random.Range(2, 19);
  1730. constitution = UnityEngine.Random.Range(2, 19);
  1731. wisdom = UnityEngine.Random.Range(2, 19);
  1732. perception = UnityEngine.Random.Range(2, 19);
  1733. isRandomized = true;
  1734. availablePoints = 0; // No points available when randomized
  1735. }
  1736. }
  1737. // Reset attributes to default for point-buy
  1738. public void ResetToPointBuy()
  1739. {
  1740. strength = 10;
  1741. dexterity = 10;
  1742. constitution = 10;
  1743. wisdom = 10;
  1744. perception = 10;
  1745. isRandomized = false;
  1746. availablePoints = 22; // Reset to full point pool (adjusted for 5 stats)
  1747. }
  1748. // Calculate point cost for a stat value (point-buy system)
  1749. public static int GetStatCost(int statValue)
  1750. {
  1751. // 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
  1752. switch (statValue)
  1753. {
  1754. case 4: return -4;
  1755. case 5: return -2;
  1756. case 6: return -1;
  1757. case 7: return -1;
  1758. case 8: return 0;
  1759. case 9: return 1;
  1760. case 10: return 2;
  1761. case 11: return 3;
  1762. case 12: return 4;
  1763. case 13: return 5;
  1764. case 14: return 7;
  1765. case 15: return 9;
  1766. case 16: return 12;
  1767. case 17: return 16;
  1768. case 18: return 21;
  1769. default: return statValue < 4 ? -4 : 25; // Invalid values
  1770. }
  1771. }
  1772. // Calculate total points spent
  1773. public int GetTotalPointsSpent()
  1774. {
  1775. return GetStatCost(strength) + GetStatCost(dexterity) + GetStatCost(constitution) + GetStatCost(wisdom) + GetStatCost(perception);
  1776. }
  1777. // Update available points based on current stats
  1778. public void UpdateAvailablePoints()
  1779. {
  1780. if (!isRandomized)
  1781. {
  1782. availablePoints = 22 - GetTotalPointsSpent(); // Changed from 18 to 22 for 5 stats
  1783. }
  1784. }
  1785. // Check if we can afford to increase a stat
  1786. public bool CanIncreaseStat(int currentValue)
  1787. {
  1788. if (isRandomized) return false; // Can't change randomized stats
  1789. if (currentValue >= 18) return false; // Max value
  1790. int currentCost = GetStatCost(currentValue);
  1791. int newCost = GetStatCost(currentValue + 1);
  1792. int costDifference = newCost - currentCost;
  1793. return availablePoints >= costDifference;
  1794. }
  1795. // Create a deep copy of this character
  1796. public TeamCharacter CreateCopy()
  1797. {
  1798. var copy = new TeamCharacter(name, isMale)
  1799. {
  1800. strength = this.strength,
  1801. dexterity = this.dexterity,
  1802. constitution = this.constitution,
  1803. wisdom = this.wisdom,
  1804. perception = this.perception,
  1805. isRandomized = this.isRandomized,
  1806. availablePoints = this.availablePoints,
  1807. gold = this.gold,
  1808. silver = this.silver,
  1809. copper = this.copper,
  1810. equippedWeapon = this.equippedWeapon,
  1811. equippedArmor = this.equippedArmor
  1812. };
  1813. // Deep copy the lists
  1814. copy.weapons = new System.Collections.Generic.List<string>(this.weapons);
  1815. copy.armor = new System.Collections.Generic.List<string>(this.armor);
  1816. copy.miscItems = new System.Collections.Generic.List<string>(this.miscItems);
  1817. return copy;
  1818. }
  1819. // Recalculate all equipment modifiers from items in inventory (temporary solution)
  1820. public void RecalculateEquipmentBonuses()
  1821. {
  1822. // Reset all modifiers to zero
  1823. strengthModifier = 0;
  1824. dexterityModifier = 0;
  1825. constitutionModifier = 0;
  1826. wisdomModifier = 0;
  1827. perceptionModifier = 0;
  1828. acModifier = 0;
  1829. // Get reference to the shop manager to access item definitions
  1830. var shopManager = UnityEngine.Object.FindFirstObjectByType<ItemShopManager>();
  1831. if (shopManager == null) return;
  1832. // Apply bonuses from all items in inventory
  1833. ApplyBonusesFromItemList(shopManager.GetWeapons(), weapons);
  1834. ApplyBonusesFromItemList(shopManager.GetArmor(), armor);
  1835. ApplyBonusesFromItemList(shopManager.GetMiscItems(), miscItems);
  1836. }
  1837. private void ApplyBonusesFromItemList(System.Collections.Generic.List<Item> shopItems, System.Collections.Generic.List<string> ownedItems)
  1838. {
  1839. foreach (string itemName in ownedItems)
  1840. {
  1841. var shopItem = shopItems.Find(item => item.itemName == itemName);
  1842. if (shopItem != null)
  1843. {
  1844. // Apply bonuses based on item type
  1845. if (shopItem is WeaponItem weapon)
  1846. {
  1847. // Weapons might provide damage bonuses, but character stats are typically different
  1848. // For now, we'll focus on armor and misc items for stat bonuses
  1849. }
  1850. else if (shopItem is ArmorItem armor)
  1851. {
  1852. strengthModifier += armor.strengthModifier;
  1853. dexterityModifier += armor.dexterityModifier;
  1854. constitutionModifier += armor.constitutionModifier;
  1855. wisdomModifier += armor.wisdomModifier;
  1856. acModifier += armor.armorClass;
  1857. }
  1858. else if (shopItem is MiscellaneousItem misc)
  1859. {
  1860. // Miscellaneous items might provide stat bonuses if they're permanent equipment
  1861. // For consumables, bonuses would typically be applied when used, not while owned
  1862. if (!misc.isConsumable)
  1863. {
  1864. // Add any permanent stat bonuses from misc items here
  1865. // This would need to be extended based on your specific misc item properties
  1866. }
  1867. }
  1868. }
  1869. }
  1870. }
  1871. // Copy data from another character into this one
  1872. public void CopyFrom(TeamCharacter other)
  1873. {
  1874. if (other == null) return;
  1875. name = other.name;
  1876. isMale = other.isMale;
  1877. strength = other.strength;
  1878. dexterity = other.dexterity;
  1879. constitution = other.constitution;
  1880. wisdom = other.wisdom;
  1881. }
  1882. }