TowerGame.cs 14 KB

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