TowerGame.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. using UnityEngine.UI;
  7. namespace TowerDevil
  8. {
  9. public sealed partial class TowerGame : MonoBehaviour
  10. {
  11. const string SaveKey = "TowerDevil.iOS.profile.v1";
  12. static readonly Color Ink = Hex("F8E9CC"), Gold = Hex("E6B36F"), Muted = Hex("BEAEA0");
  13. readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();
  14. RectTransform screen, frame, page, modal, toastRoot, battleVeil;
  15. RawImage environment;
  16. Font sans, serif;
  17. Profile profile;
  18. Run run;
  19. string route;
  20. int tutorial = -1;
  21. Rect lastSafe;
  22. Vector2Int lastSize;
  23. Vector2 lastCanvasSize;
  24. AudioSource effects, music;
  25. AudioClip tapSound, forgeSound, shotSound, gateSound, tune;
  26. public Run CurrentRun => run;
  27. public string Page => route;
  28. public bool CanUseBoard =>
  29. route == "Run" && run != null && run.CanArrange && modal == null && !animating && tutorial <= 0;
  30. void Awake()
  31. {
  32. sans = Font.CreateDynamicFontFromOSFont(new[] { "Arial", "Helvetica Neue", "Helvetica" }, 24);
  33. if (!sans)
  34. sans = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
  35. serif = Font.CreateDynamicFontFromOSFont(new[] { "Georgia", "Times New Roman", "Times" }, 32);
  36. if (!serif)
  37. serif = sans;
  38. profile = Profile.Decode(PlayerPrefs.GetString(SaveKey, ""));
  39. profile.OnSave = () =>
  40. {
  41. PlayerPrefs.SetString(SaveKey, JsonUtility.ToJson(profile));
  42. PlayerPrefs.Save();
  43. };
  44. effects = gameObject.AddComponent<AudioSource>();
  45. effects.playOnAwake = false;
  46. music = gameObject.AddComponent<AudioSource>();
  47. music.playOnAwake = false;
  48. music.loop = true;
  49. tapSound = Tone("Tap", 330, .07f);
  50. forgeSound = Tone("Forge", 630, .2f);
  51. shotSound = Tone("Shot", 116, .09f);
  52. gateSound = Tone("Gate", 53, .32f);
  53. tune = Ambience();
  54. music.clip = tune;
  55. music.volume = .14f;
  56. SyncMusic();
  57. var canvasObject =
  58. new GameObject("Game Canvas", typeof(RectTransform), typeof(Canvas), typeof(GraphicRaycaster));
  59. canvasObject.transform.SetParent(transform, false);
  60. var canvas = canvasObject.GetComponent<Canvas>();
  61. canvas.renderMode = RenderMode.ScreenSpaceOverlay;
  62. screen = (RectTransform)canvasObject.transform;
  63. if (!EventSystem.current)
  64. new GameObject("Event System", typeof(EventSystem), typeof(StandaloneInputModule))
  65. .transform.SetParent(transform, false);
  66. environment = Image(screen, "Environment", "bg_board", 0, 0, 750, 1334, false);
  67. Stretch(environment.rectTransform);
  68. var wash = Solid(screen, "Environment shadow", 0, 0, 750, 1334, new Color(.04f, .025f, .035f, .57f));
  69. Stretch(wash.rectTransform);
  70. battleVeil = Box(screen, "Battle lighting", 0, 0, 750, 1334);
  71. Stretch(battleVeil);
  72. BattleShade(0, .16f, .93f, .88f);
  73. BattleShade(.16f, .7f, .88f, .40f);
  74. BattleShade(.7f, 1, .40f, .71f);
  75. frame = Box(screen, "Safe play area", 0, 0, 750, 1334);
  76. frame.pivot = new Vector2(.5f, .5f);
  77. frame.anchorMin = frame.anchorMax = new Vector2(.5f, .5f);
  78. Fit();
  79. Application.targetFrameRate = 60;
  80. ShowLoading();
  81. }
  82. void Start()
  83. {
  84. StartCoroutine(Boot());
  85. }
  86. IEnumerator Boot()
  87. {
  88. yield return new WaitForSecondsRealtime(.8f);
  89. if (route != "Loading")
  90. yield break;
  91. if (string.IsNullOrEmpty(profile.auth))
  92. ShowStart();
  93. else if (!profile.played)
  94. StartGame();
  95. else
  96. ShowLobby();
  97. }
  98. void OnEnable() => Canvas.preWillRenderCanvases += CheckLayout;
  99. void OnDisable() => Canvas.preWillRenderCanvases -= CheckLayout;
  100. void CheckLayout()
  101. {
  102. if (frame && (lastSize.x != Screen.width || lastSize.y != Screen.height ||
  103. lastSafe != Screen.safeArea || lastCanvasSize != screen.rect.size))
  104. Fit();
  105. }
  106. void Fit()
  107. {
  108. lastSize = new Vector2Int(Mathf.Max(1, Screen.width), Mathf.Max(1, Screen.height));
  109. lastSafe = Screen.safeArea;
  110. lastCanvasSize = screen.rect.size;
  111. if (lastCanvasSize.x < 1 || lastCanvasSize.y < 1)
  112. return;
  113. var safe = lastSafe;
  114. if (safe.width < 1 || safe.height < 1)
  115. safe = new Rect(Vector2.zero, lastSize);
  116. // The simulator and Game View can render the same canvas at different pixel sizes.
  117. var ratio = lastCanvasSize / (Vector2)lastSize;
  118. safe = new Rect(safe.position * ratio, safe.size * ratio);
  119. float factor = Mathf.Min(safe.width / 750f, safe.height / 1334f);
  120. frame.localScale = new Vector3(factor, factor, 1);
  121. frame.anchoredPosition = safe.center - lastCanvasSize * .5f;
  122. if (route == "Run" && battleFooter)
  123. FitBattle(safe.height / factor);
  124. if (modal)
  125. FitModalVeil();
  126. if (environment && environment.texture)
  127. Cover(environment, lastCanvasSize.x, lastCanvasSize.y);
  128. }
  129. void Update()
  130. {
  131. CheckLayout();
  132. if (route == "Run")
  133. UpdateRun();
  134. if (Input.GetKeyDown(KeyCode.Escape))
  135. {
  136. if (modal != null && !watchingAd)
  137. {
  138. if (run?.Phase != Phase.RestChoice)
  139. CloseSheet();
  140. }
  141. else if (route == "Run" && !animating)
  142. PauseSheet();
  143. }
  144. }
  145. static Color Hex(string s)
  146. {
  147. ColorUtility.TryParseHtmlString("#" + s, out var color);
  148. return color;
  149. }
  150. static RectTransform Box(Transform parent, string name, float x, float y, float w, float h)
  151. {
  152. var rt = new GameObject(name, typeof(RectTransform)).GetComponent<RectTransform>();
  153. rt.SetParent(parent, false);
  154. rt.anchorMin = rt.anchorMax = rt.pivot = new Vector2(0, 1);
  155. rt.anchoredPosition = new Vector2(x, -y);
  156. rt.sizeDelta = new Vector2(w, h);
  157. return rt;
  158. }
  159. static void Stretch(RectTransform rt)
  160. {
  161. rt.anchorMin = Vector2.zero;
  162. rt.anchorMax = Vector2.one;
  163. rt.offsetMin = rt.offsetMax = Vector2.zero;
  164. }
  165. static Image Solid(Transform parent, string name, float x, float y, float w, float h, Color color,
  166. bool hit = false)
  167. {
  168. var im = Box(parent, name, x, y, w, h).gameObject.AddComponent<Image>();
  169. im.color = color;
  170. im.raycastTarget = hit;
  171. return im;
  172. }
  173. static IronPanel Panel(Transform p, string name, float x, float y, float w, float h, string face, string rim,
  174. float bevel = 5, string lower = null)
  175. {
  176. var g = Box(p, name, x, y, w, h).gameObject.AddComponent<IronPanel>();
  177. g.top = Hex(face);
  178. g.bottom = Hex(lower ?? face);
  179. g.border = Hex(rim);
  180. g.bevel = bevel;
  181. g.raycastTarget = false;
  182. return g;
  183. }
  184. Texture2D Art(string key)
  185. {
  186. if (!textures.TryGetValue(key, out var t))
  187. {
  188. t = Resources.Load<Texture2D>("DevilArt/" + key);
  189. textures[key] = t;
  190. }
  191. return t;
  192. }
  193. RawImage Image(Transform parent, string name, string art, float x, float y, float w, float h,
  194. bool contain = true)
  195. {
  196. var im = Box(parent, name, x, y, w, h).gameObject.AddComponent<RawImage>();
  197. im.texture = Art(art);
  198. im.raycastTarget = false;
  199. if (im.texture)
  200. {
  201. if (contain)
  202. {
  203. float scale = Mathf.Min(w / im.texture.width, h / im.texture.height);
  204. var size = new Vector2(im.texture.width, im.texture.height) * scale;
  205. im.rectTransform.sizeDelta = size;
  206. im.rectTransform.anchoredPosition = new Vector2(x + (w - size.x) * .5f, -y - (h - size.y) * .5f);
  207. }
  208. else
  209. Cover(im, w, h);
  210. }
  211. return im;
  212. }
  213. static void Cover(RawImage im, float w, float h)
  214. {
  215. if (!im.texture || h <= 0 || w <= 0)
  216. return;
  217. float ratio = (w / h) / ((float)im.texture.width / im.texture.height);
  218. float u = Mathf.Min(1, ratio), v = Mathf.Min(1, 1 / ratio);
  219. im.uvRect = new Rect((1 - u) * .5f, (1 - v) * .5f, u, v);
  220. }
  221. Text Label(Transform p, string value, float x, float y, float w, float h, int size, Color color,
  222. TextAnchor anchor = TextAnchor.MiddleLeft, bool title = false, bool bold = true)
  223. {
  224. var label = Box(p, value, x, y, w, h).gameObject.AddComponent<Text>();
  225. label.font = title ? serif : sans;
  226. label.fontSize = size;
  227. label.fontStyle = bold ? FontStyle.Bold : FontStyle.Normal;
  228. label.text = value;
  229. label.color = color;
  230. label.alignment = anchor;
  231. label.supportRichText = false;
  232. label.raycastTarget = false;
  233. label.horizontalOverflow = HorizontalWrapMode.Wrap;
  234. label.verticalOverflow = VerticalWrapMode.Truncate;
  235. return label;
  236. }
  237. Button ButtonAt(Transform p, string caption, float x, float y, float w, float h, Action action,
  238. bool main = false, int size = 24, bool enabled = true)
  239. {
  240. var plate = Panel(p, caption, x, y, w, h, main ? "F4A34A" : "353033", main ? "F8CE88" : "896B4E",
  241. main ? 9 : 6, main ? "B95620" : "201C20");
  242. plate.raycastTarget = true;
  243. var button = plate.gameObject.AddComponent<Button>();
  244. button.targetGraphic = plate;
  245. button.interactable = enabled;
  246. var colors = button.colors;
  247. colors.pressedColor = Hex("CA9E7E");
  248. colors.disabledColor = new Color(.56f, .52f, .48f);
  249. button.colors = colors;
  250. Label(plate.transform, caption, 5, 2, w - 10, h - 4, size, enabled ? (main ? Hex("28170D") : Ink) : Muted,
  251. TextAnchor.MiddleCenter, main);
  252. button.onClick.AddListener(() =>
  253. {
  254. Sound(tapSound);
  255. action();
  256. });
  257. return button;
  258. }
  259. Button Hotspot(Transform p, string name, float x, float y, float w, float h, Action action)
  260. {
  261. var b = Solid(p, name, x, y, w, h, Color.clear, true).gameObject.AddComponent<Button>();
  262. b.transition = Selectable.Transition.None;
  263. b.onClick.AddListener(() =>
  264. {
  265. Sound(tapSound);
  266. action();
  267. });
  268. return b;
  269. }
  270. static void Remove(RectTransform obj)
  271. {
  272. if (obj)
  273. {
  274. obj.gameObject.SetActive(false);
  275. Destroy(obj.gameObject);
  276. }
  277. }
  278. void NewPage(string next)
  279. {
  280. CloseSheet();
  281. Remove(page);
  282. Remove(toastRoot);
  283. toastRoot = null;
  284. route = next;
  285. battleVeil.gameObject.SetActive(next == "Run");
  286. page = Box(frame, next, 0, 0, 750, 1334);
  287. nextAttack = -1;
  288. if (next != "Run")
  289. {
  290. tutorial = -1;
  291. frames.Clear();
  292. animating = false;
  293. }
  294. environment.texture = Art(next == "Lobby" ? "bg_lobby" : next == "Start" ? "bg_start" : "bg_board");
  295. Fit();
  296. }
  297. void Backdrop(string art)
  298. {
  299. Image(page, "Backdrop", art, 0, 0, 750, 1334, false);
  300. Solid(page, "Shade", 0, 0, 750, 1334, new Color(.045f, .026f, .04f, art == "bg_boss" ? .54f : .21f));
  301. }
  302. void Toast(string value)
  303. {
  304. Remove(toastRoot);
  305. toastRoot = Panel(frame, "Notice", 75, 1116, 600, 55, "292025", "906E4C").rectTransform;
  306. Label(toastRoot, value, 8, 2, 584, 50, 20, Ink, TextAnchor.MiddleCenter);
  307. Destroy(toastRoot.gameObject, 1.8f);
  308. }
  309. static AudioClip Tone(string name, float hz, float duration)
  310. {
  311. int rate = 22050, n = (int)(rate * duration);
  312. var data = new float[n];
  313. for (int i = 0; i < n; i++)
  314. {
  315. float t = (float)i / rate;
  316. data[i] = Mathf.Sin(t * hz * 6.283f) * Mathf.Exp(-6 * t / duration) * .20f;
  317. }
  318. var clip = AudioClip.Create(name, n, 1, rate, false);
  319. clip.SetData(data, 0);
  320. return clip;
  321. }
  322. static AudioClip Ambience()
  323. {
  324. const int rate = 11025, n = rate * 8;
  325. var data = new float[n];
  326. for (int i = 0; i < n; i++)
  327. {
  328. float t = (float)i / rate;
  329. float env = Mathf.Sin(Mathf.PI * t / 8);
  330. data[i] =
  331. env * env * (Mathf.Sin(t * 55 * 2 * Mathf.PI) * .11f + Mathf.Sin(t * 82.5f * 2 * Mathf.PI) * .09f);
  332. }
  333. var clip = AudioClip.Create("Keep ambience", n, 1, rate, false);
  334. clip.SetData(data, 0);
  335. return clip;
  336. }
  337. void Sound(AudioClip clip)
  338. {
  339. if (profile.sound && clip)
  340. effects.PlayOneShot(clip);
  341. }
  342. void SyncMusic()
  343. {
  344. if (profile.music)
  345. {
  346. if (!music.isPlaying)
  347. music.Play();
  348. }
  349. else
  350. music.Stop();
  351. }
  352. }
  353. }