| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.EventSystems;
- using UnityEngine.UI;
- namespace TowerDevil
- {
- public sealed partial class TowerGame : MonoBehaviour
- {
- const string SaveKey = "TowerDevil.iOS.profile.v1";
- static readonly Color Ink = Hex("F8E9CC"), Gold = Hex("E6B36F"), Muted = Hex("BEAEA0");
- readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();
- RectTransform screen, frame, page, modal, toastRoot, battleVeil;
- RawImage environment;
- Font sans, serif;
- Profile profile;
- Run run;
- string route;
- int tutorial = -1;
- Rect lastSafe;
- Vector2Int lastSize;
- Vector2 lastCanvasSize;
- AudioSource effects, music;
- AudioClip tapSound, forgeSound, shotSound, gateSound, tune;
- public Run CurrentRun => run;
- public string Page => route;
- public bool CanUseBoard =>
- route == "Run" && run != null && run.CanArrange && modal == null && !animating && tutorial <= 0;
- void Awake()
- {
- sans = Font.CreateDynamicFontFromOSFont(new[] { "Arial", "Helvetica Neue", "Helvetica" }, 24);
- if (!sans)
- sans = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
- serif = Font.CreateDynamicFontFromOSFont(new[] { "Georgia", "Times New Roman", "Times" }, 32);
- if (!serif)
- serif = sans;
- profile = Profile.Decode(PlayerPrefs.GetString(SaveKey, ""));
- profile.OnSave = () =>
- {
- PlayerPrefs.SetString(SaveKey, JsonUtility.ToJson(profile));
- PlayerPrefs.Save();
- };
- effects = gameObject.AddComponent<AudioSource>();
- effects.playOnAwake = false;
- music = gameObject.AddComponent<AudioSource>();
- music.playOnAwake = false;
- music.loop = true;
- tapSound = Tone("Tap", 330, .07f);
- forgeSound = Tone("Forge", 630, .2f);
- shotSound = Tone("Shot", 116, .09f);
- gateSound = Tone("Gate", 53, .32f);
- tune = Ambience();
- music.clip = tune;
- music.volume = .14f;
- SyncMusic();
- var canvasObject =
- new GameObject("Game Canvas", typeof(RectTransform), typeof(Canvas), typeof(GraphicRaycaster));
- canvasObject.transform.SetParent(transform, false);
- var canvas = canvasObject.GetComponent<Canvas>();
- canvas.renderMode = RenderMode.ScreenSpaceOverlay;
- screen = (RectTransform)canvasObject.transform;
- if (!EventSystem.current)
- new GameObject("Event System", typeof(EventSystem), typeof(StandaloneInputModule))
- .transform.SetParent(transform, false);
- environment = Image(screen, "Environment", "bg_board", 0, 0, 750, 1334, false);
- Stretch(environment.rectTransform);
- var wash = Solid(screen, "Environment shadow", 0, 0, 750, 1334, new Color(.04f, .025f, .035f, .57f));
- Stretch(wash.rectTransform);
- battleVeil = Box(screen, "Battle lighting", 0, 0, 750, 1334);
- Stretch(battleVeil);
- BattleShade(0, .16f, .93f, .88f);
- BattleShade(.16f, .7f, .88f, .40f);
- BattleShade(.7f, 1, .40f, .71f);
- frame = Box(screen, "Safe play area", 0, 0, 750, 1334);
- frame.pivot = new Vector2(.5f, .5f);
- frame.anchorMin = frame.anchorMax = new Vector2(.5f, .5f);
- Fit();
- Application.targetFrameRate = 60;
- ShowLoading();
- }
- void Start()
- {
- StartCoroutine(Boot());
- }
- IEnumerator Boot()
- {
- yield return new WaitForSecondsRealtime(.8f);
- if (route != "Loading")
- yield break;
- if (string.IsNullOrEmpty(profile.auth))
- ShowStart();
- else if (!profile.played)
- StartGame();
- else
- ShowLobby();
- }
- void OnEnable() => Canvas.preWillRenderCanvases += CheckLayout;
- void OnDisable() => Canvas.preWillRenderCanvases -= CheckLayout;
- void CheckLayout()
- {
- if (frame && (lastSize.x != Screen.width || lastSize.y != Screen.height ||
- lastSafe != Screen.safeArea || lastCanvasSize != screen.rect.size))
- Fit();
- }
- void Fit()
- {
- lastSize = new Vector2Int(Mathf.Max(1, Screen.width), Mathf.Max(1, Screen.height));
- lastSafe = Screen.safeArea;
- lastCanvasSize = screen.rect.size;
- if (lastCanvasSize.x < 1 || lastCanvasSize.y < 1)
- return;
- var safe = lastSafe;
- if (safe.width < 1 || safe.height < 1)
- safe = new Rect(Vector2.zero, lastSize);
- // The simulator and Game View can render the same canvas at different pixel sizes.
- var ratio = lastCanvasSize / (Vector2)lastSize;
- safe = new Rect(safe.position * ratio, safe.size * ratio);
- float factor = Mathf.Min(safe.width / 750f, safe.height / 1334f);
- frame.localScale = new Vector3(factor, factor, 1);
- frame.anchoredPosition = safe.center - lastCanvasSize * .5f;
- if (route == "Run" && battleFooter)
- FitBattle(safe.height / factor);
- if (modal)
- FitModalVeil();
- if (environment && environment.texture)
- Cover(environment, lastCanvasSize.x, lastCanvasSize.y);
- }
- void Update()
- {
- CheckLayout();
- if (route == "Run")
- UpdateRun();
- if (Input.GetKeyDown(KeyCode.Escape))
- {
- if (modal != null && !watchingAd)
- {
- if (run?.Phase != Phase.RestChoice)
- CloseSheet();
- }
- else if (route == "Run" && !animating)
- PauseSheet();
- }
- }
- static Color Hex(string s)
- {
- ColorUtility.TryParseHtmlString("#" + s, out var color);
- return color;
- }
- static RectTransform Box(Transform parent, string name, float x, float y, float w, float h)
- {
- var rt = new GameObject(name, typeof(RectTransform)).GetComponent<RectTransform>();
- rt.SetParent(parent, false);
- rt.anchorMin = rt.anchorMax = rt.pivot = new Vector2(0, 1);
- rt.anchoredPosition = new Vector2(x, -y);
- rt.sizeDelta = new Vector2(w, h);
- return rt;
- }
- static void Stretch(RectTransform rt)
- {
- rt.anchorMin = Vector2.zero;
- rt.anchorMax = Vector2.one;
- rt.offsetMin = rt.offsetMax = Vector2.zero;
- }
- static Image Solid(Transform parent, string name, float x, float y, float w, float h, Color color,
- bool hit = false)
- {
- var im = Box(parent, name, x, y, w, h).gameObject.AddComponent<Image>();
- im.color = color;
- im.raycastTarget = hit;
- return im;
- }
- static IronPanel Panel(Transform p, string name, float x, float y, float w, float h, string face, string rim,
- float bevel = 5, string lower = null)
- {
- var g = Box(p, name, x, y, w, h).gameObject.AddComponent<IronPanel>();
- g.top = Hex(face);
- g.bottom = Hex(lower ?? face);
- g.border = Hex(rim);
- g.bevel = bevel;
- g.raycastTarget = false;
- return g;
- }
- Texture2D Art(string key)
- {
- if (!textures.TryGetValue(key, out var t))
- {
- t = Resources.Load<Texture2D>("DevilArt/" + key);
- textures[key] = t;
- }
- return t;
- }
- RawImage Image(Transform parent, string name, string art, float x, float y, float w, float h,
- bool contain = true)
- {
- var im = Box(parent, name, x, y, w, h).gameObject.AddComponent<RawImage>();
- im.texture = Art(art);
- im.raycastTarget = false;
- if (im.texture)
- {
- if (contain)
- {
- float scale = Mathf.Min(w / im.texture.width, h / im.texture.height);
- var size = new Vector2(im.texture.width, im.texture.height) * scale;
- im.rectTransform.sizeDelta = size;
- im.rectTransform.anchoredPosition = new Vector2(x + (w - size.x) * .5f, -y - (h - size.y) * .5f);
- }
- else
- Cover(im, w, h);
- }
- return im;
- }
- static void Cover(RawImage im, float w, float h)
- {
- if (!im.texture || h <= 0 || w <= 0)
- return;
- float ratio = (w / h) / ((float)im.texture.width / im.texture.height);
- float u = Mathf.Min(1, ratio), v = Mathf.Min(1, 1 / ratio);
- im.uvRect = new Rect((1 - u) * .5f, (1 - v) * .5f, u, v);
- }
- Text Label(Transform p, string value, float x, float y, float w, float h, int size, Color color,
- TextAnchor anchor = TextAnchor.MiddleLeft, bool title = false, bool bold = true)
- {
- var label = Box(p, value, x, y, w, h).gameObject.AddComponent<Text>();
- label.font = title ? serif : sans;
- label.fontSize = size;
- label.fontStyle = bold ? FontStyle.Bold : FontStyle.Normal;
- label.text = value;
- label.color = color;
- label.alignment = anchor;
- label.supportRichText = false;
- label.raycastTarget = false;
- label.horizontalOverflow = HorizontalWrapMode.Wrap;
- label.verticalOverflow = VerticalWrapMode.Truncate;
- return label;
- }
- Button ButtonAt(Transform p, string caption, float x, float y, float w, float h, Action action,
- bool main = false, int size = 24, bool enabled = true)
- {
- var plate = Panel(p, caption, x, y, w, h, main ? "F4A34A" : "353033", main ? "F8CE88" : "896B4E",
- main ? 9 : 6, main ? "B95620" : "201C20");
- plate.raycastTarget = true;
- var button = plate.gameObject.AddComponent<Button>();
- button.targetGraphic = plate;
- button.interactable = enabled;
- var colors = button.colors;
- colors.pressedColor = Hex("CA9E7E");
- colors.disabledColor = new Color(.56f, .52f, .48f);
- button.colors = colors;
- Label(plate.transform, caption, 5, 2, w - 10, h - 4, size, enabled ? (main ? Hex("28170D") : Ink) : Muted,
- TextAnchor.MiddleCenter, main);
- button.onClick.AddListener(() =>
- {
- Sound(tapSound);
- action();
- });
- return button;
- }
- Button Hotspot(Transform p, string name, float x, float y, float w, float h, Action action)
- {
- var b = Solid(p, name, x, y, w, h, Color.clear, true).gameObject.AddComponent<Button>();
- b.transition = Selectable.Transition.None;
- b.onClick.AddListener(() =>
- {
- Sound(tapSound);
- action();
- });
- return b;
- }
- static void Remove(RectTransform obj)
- {
- if (obj)
- {
- obj.gameObject.SetActive(false);
- Destroy(obj.gameObject);
- }
- }
- void NewPage(string next)
- {
- CloseSheet();
- Remove(page);
- Remove(toastRoot);
- toastRoot = null;
- route = next;
- battleVeil.gameObject.SetActive(next == "Run");
- page = Box(frame, next, 0, 0, 750, 1334);
- nextAttack = -1;
- if (next != "Run")
- {
- tutorial = -1;
- frames.Clear();
- animating = false;
- }
- environment.texture = Art(next == "Lobby" ? "bg_lobby" : next == "Start" ? "bg_start" : "bg_board");
- Fit();
- }
- void Backdrop(string art)
- {
- Image(page, "Backdrop", art, 0, 0, 750, 1334, false);
- Solid(page, "Shade", 0, 0, 750, 1334, new Color(.045f, .026f, .04f, art == "bg_boss" ? .54f : .21f));
- }
- void Toast(string value)
- {
- Remove(toastRoot);
- toastRoot = Panel(frame, "Notice", 75, 1116, 600, 55, "292025", "906E4C").rectTransform;
- Label(toastRoot, value, 8, 2, 584, 50, 20, Ink, TextAnchor.MiddleCenter);
- Destroy(toastRoot.gameObject, 1.8f);
- }
- static AudioClip Tone(string name, float hz, float duration)
- {
- int rate = 22050, n = (int)(rate * duration);
- var data = new float[n];
- for (int i = 0; i < n; i++)
- {
- float t = (float)i / rate;
- data[i] = Mathf.Sin(t * hz * 6.283f) * Mathf.Exp(-6 * t / duration) * .20f;
- }
- var clip = AudioClip.Create(name, n, 1, rate, false);
- clip.SetData(data, 0);
- return clip;
- }
- static AudioClip Ambience()
- {
- const int rate = 11025, n = rate * 8;
- var data = new float[n];
- for (int i = 0; i < n; i++)
- {
- float t = (float)i / rate;
- float env = Mathf.Sin(Mathf.PI * t / 8);
- data[i] =
- env * env * (Mathf.Sin(t * 55 * 2 * Mathf.PI) * .11f + Mathf.Sin(t * 82.5f * 2 * Mathf.PI) * .09f);
- }
- var clip = AudioClip.Create("Keep ambience", n, 1, rate, false);
- clip.SetData(data, 0);
- return clip;
- }
- void Sound(AudioClip clip)
- {
- if (profile.sound && clip)
- effects.PlayOneShot(clip);
- }
- void SyncMusic()
- {
- if (profile.music)
- {
- if (!music.isPlaying)
- music.Play();
- }
- else
- music.Stop();
- }
- }
- }
|