GameApp.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using TMPro;
  7. using UnityEngine;
  8. using UnityEngine.EventSystems;
  9. using UnityEngine.UI;
  10. namespace BuffaloSiege
  11. {
  12. public partial class GameApp : MonoBehaviour
  13. {
  14. public ArtCatalog art; public Canvas canvas; public RectTransform safeRoot, pageRoot, overlayRoot; public SaveStore Store { get; private set; }
  15. public BattleSimulation Battle { get; private set; }
  16. public string Page { get; private set; }
  17. public string Modal => modals.Count > 0 ? modals[modals.Count - 1].Id : "";
  18. public BattleView battleView; UIFactory ui; GameAudio audioSystem; readonly List<ModalFrame> modals = new List<ModalFrame>(); TMP_Text toastLabel; float toastUntil; float stepAccumulator, hudTimer; int speed = 1; bool appPaused; BattleResult result;
  19. class ModalFrame { public string Id; public GameObject Root; public bool Locked; }
  20. public bool IsBattlePaused => appPaused || modals.Count > 0;
  21. public void BuildShell()
  22. {
  23. var go = new GameObject("Canvas_750x1334", typeof(RectTransform), typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster)); go.transform.SetParent(transform, false); canvas = go.GetComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.sortingOrder = 0;
  24. var scaler = go.GetComponent<CanvasScaler>(); scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; scaler.referenceResolution = art.referenceResolution; scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight; scaler.matchWidthOrHeight = 0;
  25. ui = new UIFactory(art); var bg = ui.Image(go.transform, "illustration.menu-desert", 0, 0, 750, 1334, false); UIFactory.Fill(bg.rectTransform); var fit = bg.gameObject.AddComponent<AspectRatioFitter>(); fit.aspectMode = AspectRatioFitter.AspectMode.EnvelopeParent; fit.aspectRatio = 941f / 1672;
  26. var tint = ui.Solid(go.transform, "Backdrop tint", new Color(.13f, .06f, .09f, .24f), 0, 0, 750, 1334); UIFactory.Fill(tint.rectTransform);
  27. safeRoot = UIFactory.Root("Safe Area", go.transform); UIFactory.Fill(safeRoot); safeRoot.gameObject.AddComponent<SafeAreaLayout>(); pageRoot = UIFactory.Root("Pages", safeRoot); UIFactory.Fill(pageRoot); overlayRoot = UIFactory.Root("Modal Layer", safeRoot); UIFactory.Fill(overlayRoot);
  28. if (!FindFirstObjectByType<EventSystem>()) new GameObject("Event System", typeof(EventSystem), typeof(StandaloneInputModule));
  29. }
  30. void Awake() { Application.targetFrameRate = 60; Screen.sleepTimeout = SleepTimeout.NeverSleep; }
  31. IEnumerator Start()
  32. {
  33. AppRuntimes.Initialization();
  34. Store = new SaveStore(Path.Combine(Application.persistentDataPath, "buffalo-siege-v1.json")); if (!canvas) BuildShell(); SetupFactory(); audioSystem = gameObject.AddComponent<GameAudio>(); audioSystem.Initialize(Store);
  35. Loading(); yield return null; yield return new WaitForSecondsRealtime(.65f); ShowStart(); if (Store.Recovered) Toast("Local save recovered from backup.");
  36. }
  37. void SetupFactory() { ui = new UIFactory(art) { ClickSound = () => audioSystem?.Play("click") }; }
  38. public void PreviewLobby() { Store = new SaveStore(null); SetupFactory(); ShowLobby(); }
  39. #if UNITY_EDITOR
  40. public void UseTestSave() { StopAllCoroutines(); if (Battle != null) Battle = null; Store = new SaveStore(null); if (audioSystem) audioSystem.Initialize(Store); SetupFactory(); ShowLobby(); }
  41. #endif
  42. void ResetPage(string name)
  43. { Page = name; UIFactory.Clear(pageRoot); UIFactory.Clear(overlayRoot); modals.Clear(); toastLabel = null; hudGold = null; hudHp = null; hudWave = null; hudScore = null; if (name != "battle" && battleView) { Destroy(battleView.gameObject); battleView = null; } if (name != "battle") Battle = null; }
  44. void Loading() { ResetPage("loading"); ui.Image(pageRoot, "brand.buffalo", 230, 250, 290, 290); var t = ui.Text(pageRoot, "BUFFALO SIEGE", 40, 540, 670, 90, 50, TextAlignmentOptions.Midline); t.font = art.brand; ui.Text(pageRoot, "Preparing the frontier...", 100, 650, 550, 50, 28, TextAlignmentOptions.Midline); ui.Panel(pageRoot, "Loading track", 140, 740, 470, 24, "ui.progress-track"); ui.Panel(pageRoot, "Loading progress", 146, 746, 452, 12, "ui.progress-fill"); }
  45. public async void ShowStart()
  46. {
  47. ResetPage("start"); var center = UIFactory.Root("Title composition", pageRoot); center.anchorMin = center.anchorMax = new Vector2(.5f, .5f); center.pivot = new Vector2(.5f, .5f); center.sizeDelta = new Vector2(750, 900);
  48. ui.Image(center, "brand.buffalo", 210, 30, 330, 330); var title = ui.Text(center, "BUFFALO\nSIEGE", 50, 350, 650, 210, 78, TextAlignmentOptions.Midline); title.font = art.brand; ui.Text(center, "D E S E R T D E F E N S E", 70, 575, 610, 45, 28, TextAlignmentOptions.Midline, art.gold, true);
  49. var playBtn = ui.Button(center, "PLAY", 145, 690, 460, 100, ShowLobby, true, 44); Footer(pageRoot, false);
  50. playBtn.interactable = false;
  51. if (!await AppRuntimes.CheckVersion())
  52. {
  53. playBtn.interactable = true;
  54. }
  55. }
  56. void Header(string heading, bool back = false)
  57. {
  58. ui.Panel(pageRoot, "Header", 0, 0, 750, 104, "ui.button.wood"); if (back) { ui.IconButton(pageRoot, "back", 18, 17, 68, ShowLobby); ui.Text(pageRoot, heading, 104, 17, 390, 70, 38); }
  59. else { ui.Image(pageRoot, "brand.buffalo", 12, 3, 90, 90); var brand = ui.Text(pageRoot, "BUFFALO SIEGE", 102, 6, 385, 53, 33); brand.font = art.brand; ui.Text(pageRoot, "D E S E R T D E F E N S E", 107, 59, 350, 28, 18, TextAlignmentOptions.MidlineLeft, art.gold, true); }
  60. ui.IconButton(pageRoot, "calendar", 500, 17, 66, OpenCheckin); var coin = ui.Button(pageRoot, "", 578, 16, 156, 70, OpenShop); ui.Image(coin.transform, "ui.coin", 11, 16, 37, 37); ui.Text(coin.transform, Fmt(Store.Data.coins), 48, 7, 99, 53, 30, TextAlignmentOptions.Midline); if (Store.CanClaim(DateTime.Now)) ui.Image(pageRoot, "ui.badge", 547, 11, 20, 20);
  61. }
  62. void Footer(Transform parent, bool showLocalSave = true) { var r = UIFactory.Root("Footer", parent); r.anchorMin = new Vector2(0, 0); r.anchorMax = new Vector2(1, 0); r.pivot = new Vector2(0, 0); r.sizeDelta = new Vector2(0, 42); if (showLocalSave) ui.Text(r, "LOCAL SAVE", 24, 0, 300, 40, 19, TextAlignmentOptions.MidlineLeft, art.gold, true); ui.Text(r, "BUFFALO SIEGE 1.0", 380, 0, 346, 40, 19, TextAlignmentOptions.MidlineRight, art.gold, true); }
  63. public void ShowLobby()
  64. {
  65. ResetPage("lobby"); Header(""); var c = ui.Scroll(pageRoot, "Lobby scroll", 1081, 114, 129, 22, 22); var d = Store.Data;
  66. var profile = ui.Panel(c, "Player card", 0, 0, 706, 108); var hit = profile.gameObject.AddComponent<Button>(); profile.raycastTarget = true; hit.targetGraphic = profile; hit.onClick.AddListener(OpenProfile);
  67. ui.Image(c, "avatar." + d.avatar, 10, 4, 96, 96); ui.Text(c, d.playerName, 115, 10, 390, 46, 34); ui.Text(c, "LOCAL PLAYER · ID " + d.playerId, 117, 57, 385, 32, 21, TextAlignmentOptions.MidlineLeft, art.gold, true); ui.Text(c, "ENDLESS BEST", 526, 12, 155, 30, 19, TextAlignmentOptions.Midline, art.cream, true); ui.Text(c, "W" + d.bestWave, 533, 43, 144, 50, 40, TextAlignmentOptions.Midline, art.gold);
  68. Section(c, "CHOOSE A MODE", 111); ModeCard(c, 156, false); ModeCard(c, 337, true);
  69. Section(c, "YOUR ARSENAL", 516, () => OpenArmory(), "UPGRADE");
  70. for (int i = 0; i < 5; i++)
  71. { int type = i; float x = i * 142; var card = ui.Panel(c, "Arsenal " + GameData.Towers[i].Name, x, 562, 137, 172, "ui.card.frame"); var b = card.gameObject.AddComponent<Button>(); card.raycastTarget = true; b.onClick.AddListener(() => OpenArmory(type)); ui.Image(card.transform, "tower." + GameData.Towers[i].Id, 9, 5, 119, 99); ui.Text(card.transform, GameData.Towers[i].Name, 3, 104, 131, 29, 23, TextAlignmentOptions.Midline); ui.Text(card.transform, "Lv." + d.armory[i], 3, 129, 131, 31, 20, TextAlignmentOptions.Midline, art.gold); for (int j = 0; j < 5; j++) ui.Image(card.transform, "ui.star", 21 + j * 19, 155, 15, 12).color = j < d.armory[i] ? Color.white : new Color(.3f, .3f, .3f); }
  72. Section(c, "LEADERBOARD", 739, OpenBoard, "VIEW ALL"); var board = Store.Board(); var top = board.Take(5).ToList(); if (!top.Any(x => x.player)) top[4] = board.First(x => x.player); ui.Panel(c, "Leaderboard", 0, 785, 706, 204, "ui.button.wood");
  73. for (int i = 0; i < top.Count; i++) BoardRow(c, top[i], Array.IndexOf(board, top[i]) + 1, 793 + i * 37, 706);
  74. var stats = ui.Panel(c, "Campaign progress", 0, 999, 706, 80); Stat(stats.transform, "CLEARED", d.cleared + "/20", 0, 235); Stat(stats.transform, "STARS", d.stars.Sum() + "/60", 235, 235); Stat(stats.transform, "BEST", "W" + d.bestWave, 470, 235);
  75. var bottom = UIFactory.Root("Bottom navigation", pageRoot); bottom.anchorMin = new Vector2(0, 0); bottom.anchorMax = new Vector2(1, 0); bottom.pivot = Vector2.zero; bottom.sizeDelta = new Vector2(0, 129); ui.Panel(bottom, "Navigation backing", 0, 0, 750, 129, "ui.button.wood");
  76. var shop = ui.Button(bottom, "SHOP", 22, 9, 224, 78, OpenShop, false, 29); var help = ui.Button(bottom, "HOW TO PLAY", 263, 9, 224, 78, OpenHelp, false, 25); var settings = ui.Button(bottom, "SETTINGS", 504, 9, 224, 78, OpenSettings, false, 27);
  77. NavIcon(shop, "shop"); NavIcon(help, "book"); NavIcon(settings, "settings"); Footer(bottom);
  78. audioSystem?.EnterLobby();
  79. }
  80. void NavIcon(Button button, string icon)
  81. { ui.Image(button.transform, "ui." + icon, 13, 21, 36, 36); var text = button.GetComponentInChildren<TMP_Text>(); UIFactory.Place(text.rectTransform, 50, 4, 164, 70); }
  82. void ModeCard(Transform parent, float y, bool endless)
  83. {
  84. var card = ui.Panel(parent, endless ? "Endless mode" : "Campaign mode", 0, y, 706, 170, "ui.card.frame"); var pic = ui.Image(card.transform, "illustration.mode-" + (endless ? "endless" : "campaign"), 9, 9, 688, 152, true); pic.transform.SetAsFirstSibling();
  85. ui.Solid(card.transform, "Text backing", new Color(.13f, .065f, .13f, .84f), 294, 11, 400, 148); ui.Text(card.transform, endless ? "ENDLESS" : "CAMPAIGN", 305, 10, 390, 57, 43);
  86. ui.Text(card.transform, endless ? "SURVIVE · HIGH SCORE" : "20 LEVELS · 4 MAPS", 311, 67, 367, 29, 21, TextAlignmentOptions.MidlineLeft, art.gold);
  87. ui.Button(card.transform, endless ? "PLAY >" : "LEVEL " + Math.Min(20, Store.Data.cleared + 1) + " >", 484, 103, 197, 53, () => { if (endless) StartBattle(true, 1); else ShowLevels(); }, true, 28);
  88. }
  89. void Section(Transform parent, string label, float y, Action action = null, string button = "")
  90. { ui.Solid(parent, "Section backing", new Color(.14f, .075f, .10f, .74f), 0, y + 2, 706, 37); ui.Text(parent, label, 10, y, 485, 42, 29); ui.Solid(parent, "Brass divider", art.gold, 330, y + 22, action != null ? 165 : 365, 1); if (action != null) ui.Button(parent, button + " >", 525, y + 1, 180, 37, action, false, 20); }
  91. void Stat(Transform parent, string label, string value, float x, float width)
  92. { ui.Text(parent, value, x, 3, width, 48, 35, TextAlignmentOptions.Midline, art.cream); ui.Text(parent, label, x, 45, width, 30, 19, TextAlignmentOptions.Midline, art.gold, true); }
  93. void BoardRow(Transform parent, LeaderEntry e, int rank, float y, float width)
  94. { if (e.player) ui.Solid(parent, "Your rank", new Color(.16f, .35f, .35f, .65f), 12, y, width - 24, 41); ui.Text(parent, rank.ToString(), 18, y, 52, 38, 26, TextAlignmentOptions.Midline, e.player ? art.gold : art.cream); ui.Text(parent, e.name, 80, y, width - 365, 38, 25, TextAlignmentOptions.MidlineLeft, e.player ? art.gold : art.cream); ui.Text(parent, Fmt(e.score), width - 277, y, 164, 38, 26, TextAlignmentOptions.MidlineRight, art.gold); ui.Text(parent, "W" + e.wave, width - 95, y, 75, 38, 24, TextAlignmentOptions.MidlineRight); }
  95. public void ShowLevels()
  96. {
  97. ResetPage("levels"); Header("CAMPAIGN", true); var c = ui.Scroll(pageRoot, "Level selection", 1090, 120, 50, 24, 24); ui.Text(c, "Defend the frontier", 0, 0, 702, 66, 44); ui.Text(c, "20 outposts · 4 battlefields · 60 stars", 0, 69, 702, 42, 25, TextAlignmentOptions.MidlineLeft, art.gold, true);
  98. for (int i = 0; i < 20; i++) { int level = i + 1; bool unlocked = i <= Store.Data.cleared; float x = (i % 4) * 177, y = 135 + (i / 4) * 167; var b = ui.Button(c, "", x, y, 170, 157, () => OpenLevel(level), false); b.interactable = unlocked; ui.Text(b.transform, level.ToString(), 10, 7, 150, 58, 43, TextAlignmentOptions.Midline, unlocked ? art.cream : Color.gray); ui.Text(b.transform, level % 5 == 0 ? "BOSS" : "WAVES " + GameData.WaveCount(level), 8, 66, 154, 27, 20, TextAlignmentOptions.Midline, art.gold, true); if (unlocked) { for (int s = 0; s < 3; s++) ui.Image(b.transform, "ui.star", 40 + s * 31, 108, 26, 26).color = s < Store.Data.stars[i] ? Color.white : new Color(.25f, .22f, .24f); } else ui.Image(b.transform, "ui.lock", 67, 102, 36, 36); }
  99. ui.Text(c, "Win to unlock the next outpost.\nUpgrade your arsenal in the lobby for lasting bonuses.", 0, 995, 702, 85, 25, TextAlignmentOptions.Midline, art.cream, true); Footer(pageRoot);
  100. }
  101. void OpenLevel(int level)
  102. {
  103. var map = GameData.Maps[(level - 1) % 4]; var c = OpenModal("level", "OUTPOST " + level, 950, 700); ui.Image(c, "map." + map.Id, 20, 5, 610, 340, false); ui.Text(c, map.Name, 20, 355, 610, 54, 40, TextAlignmentOptions.Midline); ui.Text(c, GameData.WaveCount(level) + " WAVES · " + GameData.Reward(level) + " COINS\nStarting gold: " + Fmt(GameData.StartingGold(level)) + "\nRecommended arsenal: Lv." + Math.Min(5, 1 + (level - 1) / 4) + (level % 5 == 0 ? "\nBuffalo King on the final wave." : ""), 20, 416, 610, 150, 26, TextAlignmentOptions.Midline, art.gold); ui.Button(c, "DEFEND OUTPOST", 60, 590, 530, 78, () => StartBattle(false, level), true, 34);
  104. }
  105. RectTransform OpenModal(string id, string title, float preferred, float contentHeight, bool locked = false)
  106. {
  107. if (modals.Count > 0) { var group = modals[modals.Count - 1].Root.GetComponent<CanvasGroup>(); group.interactable = false; group.blocksRaycasts = false; }
  108. var root = UIFactory.Root("Modal_" + id, overlayRoot); UIFactory.Fill(root); root.gameObject.AddComponent<CanvasGroup>(); var shade = root.gameObject.AddComponent<Image>(); shade.color = new Color(.035f, .02f, .035f, .82f); shade.raycastTarget = true;
  109. var p = ui.Panel(root, "Dialog", 0, 0, 700, preferred); p.rectTransform.anchorMin = p.rectTransform.anchorMax = new Vector2(.5f, .5f); p.rectTransform.pivot = new Vector2(.5f, .5f); p.rectTransform.anchoredPosition = Vector2.zero; p.raycastTarget = true; var sizing = p.gameObject.AddComponent<ModalFit>(); sizing.preferredHeight = preferred;
  110. ui.Text(p.transform, title, 25, 17, 570, 64, 39); if (!locked) ui.IconButton(p.transform, "close", 610, 20, 62, () => CloseModal()); ui.Solid(p.transform, "Title rule", art.gold, 25, 87, 650, 2); var c = ui.Scroll(p.transform, "Dialog scroll", contentHeight, 105, 22, 25, 25);
  111. modals.Add(new ModalFrame { Id = id, Root = root.gameObject, Locked = locked }); if (toastLabel) toastLabel.transform.parent.SetAsLastSibling(); return c;
  112. }
  113. public void CloseModal(bool force = false)
  114. {
  115. if (modals.Count == 0 || modals[modals.Count - 1].Locked && !force) return; var f = modals[modals.Count - 1]; f.Root.SetActive(false); Destroy(f.Root); modals.RemoveAt(modals.Count - 1); if (modals.Count > 0) { var g = modals[modals.Count - 1].Root.GetComponent<CanvasGroup>(); g.interactable = true; g.blocksRaycasts = true; }
  116. if (modals.Count == 0) { if (Page == "lobby") ShowLobby(); else if (Page == "levels") ShowLevels(); else if (Page == "battle") RefreshBattleHud(); }
  117. }
  118. void ReplaceModal(Action next) { CloseModal(true); next(); }
  119. public void Toast(string message)
  120. {
  121. if (!toastLabel) { var p = ui.Panel(overlayRoot, "Toast", 0, 0, 680, 80); p.rectTransform.anchorMin = p.rectTransform.anchorMax = new Vector2(.5f, 0); p.rectTransform.pivot = new Vector2(.5f, 0); p.rectTransform.anchoredPosition = new Vector2(0, 160); toastLabel = ui.Text(p.transform, "", 18, 3, 644, 74, 27, TextAlignmentOptions.Midline); }
  122. toastLabel.text = message; toastLabel.transform.parent.gameObject.SetActive(true); toastLabel.transform.parent.SetAsLastSibling(); toastUntil = Time.unscaledTime + 2.5f;
  123. }
  124. void Update()
  125. {
  126. if (Store == null) return; if (toastLabel && Time.unscaledTime > toastUntil) toastLabel.transform.parent.gameObject.SetActive(false);
  127. if (Input.GetKeyDown(KeyCode.Escape)) { if (modals.Count > 0) CloseModal(); else if (Page == "battle") OpenPause(); else if (Page == "levels") ShowLobby(); }
  128. if (Battle != null && Page == "battle")
  129. {
  130. if (!IsBattlePaused && Battle.Phase != BattlePhase.Done) { stepAccumulator += Math.Min(Time.unscaledDeltaTime, .1f) * speed; while (stepAccumulator >= 1f / 60) { Battle.Step(1f / 60); stepAccumulator -= 1f / 60; if (Battle.Phase == BattlePhase.Done) break; } }
  131. if (battleView) battleView.Render(); hudTimer += Time.unscaledDeltaTime; if (hudTimer >= .1f) { hudTimer = 0; RefreshBattleHud(); }
  132. if (Battle.Phase == BattlePhase.Done && result == null) { result = Battle.Settle(); if (result != null) { audioSystem?.Play(result.Win ? "win" : "lose"); OpenResult(); } }
  133. }
  134. }
  135. void OnApplicationPause(bool pause) { appPaused = pause; if (Store != null) Store.Save(); if (!pause && Page == "battle" && Battle != null && Battle.Phase != BattlePhase.Done && modals.Count == 0) OpenPause(); }
  136. void OnApplicationQuit() { Store?.Save(); }
  137. public static string Fmt(int n) => n.ToString("N0", System.Globalization.CultureInfo.InvariantCulture);
  138. }
  139. }