MainTeamSelectScript.cs 77 KB

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