TowerGame.cs 14 KB

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