using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace TowerDevil { public sealed partial class TowerGame { RectTransform tiles, monsters, fx, shieldPips, guide, actionArea; RectTransform hud, boardStage, battleFooter, fieldClip; CourtyardBackdrop courtyard; PieceShadows pieceShadows; readonly Dictionary courtSprites = new Dictionary(); GateFractures gateFractures; Vector2 fractureOrigin; BattleEffects battleEffects; IronPanel turnDot, turnStrip; readonly Dictionary pieces = new Dictionary(); readonly Dictionary foes = new Dictionary(); readonly List gone = new List(); readonly Queue frames = new Queue(); Text movesLabel, sealLabel, nightLabel, coinLabel, shardLabel, turnLabel, waveLabel, waitLabel, leftLabel; RectTransform waveFill; bool animating, assaultTint; float nextAttack = -1, tickRemainder, forecastTime; int lastPlates = -1, lastMaxPlates = -1, lastDay = -1; Phase lastPhase; Coroutine playback; static readonly string[] GuideTitle = { "DRAG TO SWAP", "THREE IN A LINE", "FORGE A STRONGER TOWER", "GOLD MAKES CHESTS", "LET THEM COME" }; static readonly string[] GuideBody = { "Drag a piece onto a neighbouring square to spend one move.", "Match stone, wood, crystal or ice to forge its tower. Watch where the pieces fall.", "Line up three towers of the same kind and tier to upgrade one.", "Match three gold piles for a chest. Tap it for moves, or line up three chests to upgrade.", "Finish arranging the board, then call the horde. Your towers fire automatically." }; void StartGame() { profile.played = true; profile.Save(); AttachRun(new Run(profile, System.Environment.TickCount)); tutorial = profile.tutorialDone ? -1 : 0; ShowBattle(); } void AttachRun(Run next) { if (playback != null) { StopCoroutine(playback); playback = null; } frames.Clear(); animating = false; tickRemainder = 0; if (run != null) { run.Fired -= OnFire; run.Hit -= OnHit; run.StruckGate -= OnGateHit; run.BoardChanged -= frames.Enqueue; } run = next; run.Fired += OnFire; run.Hit += OnHit; run.StruckGate += OnGateHit; run.BoardChanged += frames.Enqueue; } #if UNITY_EDITOR public void EditorReview() { // This fixture never writes to the player's local profile. profile = new Profile { played = true, tutorialDone = true, auth = "guest" }; var review = new Run(profile, 404); review.SetReviewBoard(); profile.shards = 0; AttachRun(review); tutorial = -1; ShowBattle(); } #endif void ShowBattle() { battleFooter = null; NewPage("Run"); pieces.Clear(); foes.Clear(); motionTime = 0; gateHitTime = -1; nextMotionSeed = 0; lastPlates = -1; guide = null; if (courtSprites.Count == 0) foreach (var sprite in Resources.LoadAll("DevilArt/Courtyard")) courtSprites.Add(sprite.name, sprite); courtyard = Box(page, "Basalt courtyard", 0, 0, 1000, 1334).gameObject.AddComponent(); courtyard.SetPainting(Art("Courtyard/backdrop")); gateFractures = Box(courtyard.transform, "Gate fractures", 0, 0, 0, 0).gameObject.AddComponent(); gateFractures.raycastTarget = false; boardStage = Box(page, "Battlefield", 0, 0, BoardLayout.Width, BoardLayout.Height); shieldPips = Box(boardStage, "Seal stones", 230, -92, 290, 35); turnStrip = Round(boardStage, "Turn strip", 33, -47, 684, 33, "261D20", "75605A", 16, "171114"); assaultTint = false; turnDot = Round(turnStrip.transform, "Phase light", 20, 11, 12, 12, "A4F09D", "366439", 6, "5FC56F"); turnLabel = Label(turnStrip.transform, "YOUR TURN", 46, 0, 223, 33, 17, Ink); waitLabel = Label(turnStrip.transform, "", 247, 0, 418, 33, 16, Hex("FFDA89"), TextAnchor.MiddleRight); var pieceWindow = Box(boardStage, "Piece viewport", 0, -10, BoardLayout.Width, BoardLayout.Height + 27); pieceWindow.gameObject.AddComponent(); pieceShadows = Box(pieceWindow, "Contact shadows", 0, 10, BoardLayout.Width, BoardLayout.Height) .gameObject.AddComponent(); pieceShadows.raycastTarget = false; pieceShadows.Bind(pieces); tiles = Box(pieceWindow, "Pieces", 0, 10, BoardLayout.Width, BoardLayout.Height); fieldClip = Box(boardStage, "Visible battlefield", 0, -15, 750, 850); fieldClip.gameObject.AddComponent(); monsters = Box(fieldClip, "Horde", 0, 15, 750, 1334); fx = Box(boardStage, "Effects", 0, 0, 750, 1334); battleEffects = fx.gameObject.AddComponent(); battleEffects.raycastTarget = false; var input = Solid(boardStage, "Board input", 0, 0, BoardLayout.Width, BoardLayout.Height, Color.clear, true) .gameObject.AddComponent(); input.Game = this; BuildBattleHud(); battleFooter = Box(page, "Battle footer", 0, 1221, 750, 113); waveLabel = Label(battleFooter, "", 26, 0, 125, 35, 17, Ink); Round(battleFooter, "Wave track", 145, 13, 454, 10, "3A292C", "49353A", 5, "2A1C20"); waveFill = Round(battleFooter, "Wave progress", 145, 13, 1, 10, "FFD473", "CD8D34", 5, "E59B38").rectTransform; leftLabel = Label(battleFooter, "", 606, 0, 116, 35, 17, Muted, TextAnchor.MiddleRight); actionArea = Box(battleFooter, "Actions", 0, 41, 750, 64); SideAction("SHOP", "shop", 20, Merchant); SideAction("MENU", "menu", 544, PauseSheet); Fit(); lastDay = run.Day; lastPhase = run.Phase; forecastTime = 6; DrawBoard(run.Board); RebuildAction(); RefreshHud(); DrawGuide(); } void FitBattle(float safeHeight) { float extra = Mathf.Max(0, safeHeight - 1334); float boardY = 460 - extra * .19f; hud.anchoredPosition = new Vector2(0, extra * .5f); boardStage.anchoredPosition = new Vector2(0, -boardY); battleFooter.anchoredPosition = new Vector2(0, -1221 - extra * .5f); float laneEnd = -battleFooter.anchoredPosition.y - boardY; fieldClip.sizeDelta = new Vector2(750, laneEnd + 15); Vector2 topLeft = page.InverseTransformPoint(screen.TransformPoint(new Vector2(screen.rect.xMin, screen.rect.yMax))); Vector2 bottomRight = page.InverseTransformPoint(screen.TransformPoint(new Vector2(screen.rect.xMax, screen.rect.yMin))); float visibleWidth = 2 * Mathf.Max(375 - topLeft.x, bottomRight.x - 375) + 2; float width = Mathf.Max(1000, visibleWidth); var painting = courtyard.rectTransform; painting.anchoredPosition = new Vector2(375 - width * .5f, topLeft.y); painting.sizeDelta = new Vector2(width, topLeft.y - bottomRight.y); courtyard.Fit(topLeft.y + 138 - extra * .5f, topLeft.y + boardY - 66, visibleWidth); courtyard.RegisterFractures(gateFractures.rectTransform); fractureOrigin = gateFractures.rectTransform.anchoredPosition; } static IronPanel Round(Transform parent, string name, float x, float y, float w, float h, string face, string rim, float radius, string lower = null) { var plate = Panel(parent, name, x, y, w, h, face, rim, radius, lower); plate.rounded = true; plate.stroke = 2; return plate; } void BuildBattleHud() { hud = Box(page, "Warden HUD", 0, 0, 750, 118); Round(hud, "Portrait setting", 15, 1, 44, 42, "39251C", "F4B943", 14, "170F0D"); Image(hud, "Warden portrait", "av_" + profile.avatar, 17, 2, 39, 39); var name = Label(hud, profile.name, 71, 0, 325, 43, 22, Ink); name.resizeTextForBestFit = true; name.resizeTextMinSize = 15; name.resizeTextMaxSize = 22; coinLabel = WalletPill("Gold", "ui_coin", 450, 94, "70404B", "FFCE65"); shardLabel = WalletPill("Shards", "ui_gem", 554, 83, "34627C", "79D6FF"); var pause = Round(hud, "Pause bezel", 693, 1, 46, 41, "22171C", "804452", 14, "120D10"); for (int i = 0; i < 2; i++) Solid(pause.transform, "Pause bar", 17 + i * 9, 12, 5, 15, Ink); Hotspot(hud, "Pause battle", 674, 0, 74, 49, PauseSheet); movesLabel = StatCard("MOVES", 15, "FF7964", "B82E23", "F8AA91", "A33D2C", Color.white); sealLabel = StatCard("SEAL", 255, "FFDA5E", "C48812", "FFE49B", "BE8D29", Hex("442C0C")); nightLabel = StatCard("NIGHT", 497, "67C8FC", "1B67AC", "96D5FE", "357CAA", Color.white); Hotspot(hud, "Seal details", 255, 49, 230, 69, SealSheet); } Text WalletPill(string name, string icon, float x, float w, string border, string accent) { var pill = Round(hud, name, x, 1, w, 41, "21171A", border, 22, "0F0B10"); var symbol = Image(pill.transform, icon, icon, 14, 10, 21, 21); symbol.uvRect = name == "Gold" ? new Rect(.17f, .17f, .66f, .66f) : new Rect(.20f, .18f, .6f, .64f); symbol.color = Hex(accent); var label = Label(pill.transform, "", 37, 0, w - 45, 41, 22, Hex(accent), TextAnchor.MiddleCenter); label.resizeTextForBestFit = true; label.resizeTextMinSize = 12; label.resizeTextMaxSize = 22; return label; } Text StatCard(string caption, float x, string hi, string lo, string rim, string inset, Color ink) { Round(hud, caption + " shadow", x, 53, 232, 68, "28171B", "241418", 21, "100B0E"); var card = Round(hud, caption + " card", x, 49, 232, 68, hi, rim, 21, lo); card.stroke = 3; var badge = Round(card.transform, "Icon well", 15, 15, 40, 38, inset, inset, 12); if (caption == "SEAL") { Shield(badge.transform, 11, 9, 18, 19, "77501D", "513714"); } else if (caption == "MOVES") Label(badge.transform, "⇄", 0, -1, 40, 38, 26, ink, TextAnchor.MiddleCenter); else { for (int i = 0; i < 8; i++) { var ray = Solid(badge.transform, "Sun ray", 20, 19, 3, 11, ink).rectTransform; ray.pivot = new Vector2(.5f, 0); ray.localRotation = Quaternion.Euler(0, 0, i * 45); } Round(badge.transform, "Sun", 13, 12, 14, 14, "FFF0D6", "FFF0D6", 7); } var value = Label(card.transform, "", 70, 4, 150, 34, 30, ink); Label(card.transform, caption, 71, 38, 145, 23, 14, ink); return value; } static void Shield(Transform parent, float x, float y, float width, float height, string top, string bottom) { var icon = Box(parent, "Seal stone", x, y, width, height).gameObject.AddComponent(); icon.raycastTarget = false; icon.top = Hex(top); icon.bottom = Hex(bottom); } void SideAction(string label, string glyph, float x, System.Action callback) { var button = ButtonAt(actionArea, label, x, 0, 186, 62, callback, false, 18); StyleBattleButton(button, false); var caption = button.GetComponentInChildren().rectTransform; caption.anchoredPosition = new Vector2(58, -2); caption.sizeDelta = new Vector2(96, 58); Image(button.transform, label + " icon", "ui_" + glyph, 40, 18, 27, 27).color = Ink; } void StyleBattleButton(Button button, bool primary) { var plate = (IronPanel)button.targetGraphic; plate.rounded = true; plate.bevel = 19; plate.stroke = 3; plate.top = Hex(primary ? "FFDC77" : "482932"); plate.bottom = Hex(primary ? "E89B22" : "2E1821"); plate.border = Hex(primary ? "FFECBD" : "845060"); } void RebuildAction() { var previous = actionArea.Find("Primary"); if (previous) Remove((RectTransform)previous); string caption = run.Phase == Phase.Assault ? "HORDE ATTACKING" : run.Phase == Phase.Rest ? "DONE" : "LET THEM COME"; var b = ButtonAt(actionArea, caption, 219, 0, 312, 62, BeginAttack, true, 23, run.CanArrange); StyleBattleButton(b, true); b.name = "Primary"; var captionText = b.GetComponentInChildren(); captionText.font = sans; var label = captionText.rectTransform; label.anchoredPosition = new Vector2(52, -2); label.sizeDelta = new Vector2(247, 58); Image(b.transform, "Sword", "ui_sword", 27, 15, 32, 32).color = Hex("342315"); } void BeginAttack() { if (modal != null || animating || tutorial >= 0 || !run.BeginAttack()) return; nextAttack = -1; RefreshHud(); RebuildAction(); } public void TrySwap(int r, int c, int nr, int nc) { if (!CanUseBoard || !run.Swap(r, c, nr, nc)) return; Sound(tapSound); if (tutorial == 0) { tutorial = 1; DrawGuide(); } PlayBoard(); } public void TapCell(int r, int c) { if (!CanUseBoard || tutorial >= 0 || !Run.Inside(r, c)) return; if (run.OpenChest(r, c)) { Sound(forgeSound); PlayBoard(); } else if (run.Board[r, c]?.Tower == true) GearSheet(r, c); } void PlayBoard() { nextAttack = -1; if (!animating && frames.Count > 0) playback = StartCoroutine(AnimateBoard()); else RefreshHud(); } static Vector2 SetRegion(RawImage image, Sprite sprite, bool flip) { Texture2D texture = sprite.texture; Rect crop = sprite.rect; var uv = new Rect(crop.x / texture.width, crop.y / texture.height, crop.width / texture.width, crop.height / texture.height); if (flip) uv = new Rect(uv.xMax, uv.y, -uv.width, uv.height); image.texture = texture; image.uvRect = uv; return crop.size; } void SetPieceArt(RawImage image, Piece piece, bool firing = false) { // The painted cannon points right at rest. A shot sets its actual facing; // board re-layouts retain that facing until the next shot. bool flip = piece.Kind == Kind.Cannon && (firing ? !piece.Reversed : image.uvRect.width < 0); Vector2 size = SetRegion(image, courtSprites[piece.Art], flip); image.name = piece.Art; float footprint = piece.Kind switch { Kind.Stone => .70f, Kind.Ice => .74f, Kind.Gold => .80f, Kind.Ballista => .91f, Kind.Frost => .90f, Kind.Cannon => .86f, Kind.Arrow => .86f, _ => .77f }; float span = BoardLayout.FrontCell * (footprint + .035f * (piece.Tier - 1)); image.rectTransform.sizeDelta = size * (span / Mathf.Max(size.x, size.y)); } void DrawBoard(Piece[,] cells, Dictionary previous = null) { var used = new HashSet(); for (int r = 0; r < 6; r++) for (int c = 0; c < 6; c++) { Piece p = cells[r, c]; if (p == null) continue; used.Add(p); if (!pieces.TryGetValue(p, out var image)) { image = Box(tiles, p.Art, 0, 0, 0, 0).gameObject.AddComponent(); image.raycastTarget = false; image.rectTransform.pivot = new Vector2(.5f, 0); pieces.Add(p, image); } SetPieceArt(image, p); var rt = image.rectTransform; var center = BoardLayout.Center(r, c); var end = center + Vector2.down * (BoardLayout.Depth(r) * .42f); rt.localScale = Vector3.one * (BoardLayout.Size(r) / BoardLayout.FrontCell); rt.SetAsLastSibling(); if (previous != null && !previous.ContainsKey(rt)) previous[rt] = end + Vector2.up * BoardLayout.Size(r) * .72f; rt.anchoredPosition = end; image.color = Color.white; } var removed = new List(); foreach (var pair in pieces) if (!used.Contains(pair.Key)) { Remove(pair.Value.rectTransform); removed.Add(pair.Key); } foreach (var key in removed) pieces.Remove(key); pieceShadows.SetVerticesDirty(); } void LateUpdate() { if (route == "Run" && pieceShadows && (animating || held || run.Phase == Phase.Assault)) pieceShadows.SetVerticesDirty(); } void UpdateRun() { if (modal != null) return; motionTime += Time.deltaTime; battleEffects.Advance(Time.deltaTime); ShakeGate(); if (animating) return; if (run.Phase == Phase.Plan && tutorial < 0 && run.Moves == 0) { if (nextAttack < 0) nextAttack = .9f; nextAttack -= Time.deltaTime; if (nextAttack <= 0) BeginAttack(); } if (forecastTime > 0) { forecastTime -= Time.deltaTime; if (forecastTime <= 0) RefreshHud(); } if (run.Phase == Phase.Assault) { tickRemainder += Mathf.Min(Time.deltaTime, .1f); while (tickRemainder >= 1f / 30) { run.Tick(1f / 30); tickRemainder -= 1f / 30; } DrawFoes(); RefreshHud(); } else if (foes.Count != 0) DrawFoes(); if (run.Phase != Phase.Assault && gateHitTime > 0 && motionTime < gateHitTime + .28f) return; if (run.Phase == Phase.Over) { ShowOver(); return; } if (run.Phase == Phase.RestChoice) { RestSheet(); return; } if (lastDay != run.Day || lastPhase != run.Phase) { if (lastDay != run.Day) { forecastTime = 6; Toast(run.Day % 10 == 0 ? "BOSS NIGHT" : "NIGHT " + run.Day); DrawBoard(run.Board); } lastDay = run.Day; lastPhase = run.Phase; RebuildAction(); RefreshHud(); } } Vector2 Feet(Foe f) { var at = BoardLayout.Center(f.Row, f.Col); if (f.Row >= Foe.RunwayStart) { float laneDepth = fieldClip.sizeDelta.y - 15 - BoardLayout.Height; at.y = -BoardLayout.Height - laneDepth * (f.Row - Foe.RunwayStart) / (Foe.RunwayEnd - Foe.RunwayStart); } return at; } void RefreshHud() { if (route != "Run") return; movesLabel.text = run.Phase == Phase.Rest ? "∞" : run.Moves.ToString(); sealLabel.text = run.Plates.ToString(); nightLabel.text = run.Day.ToString(); coinLabel.text = run.Available.ToString(); shardLabel.text = profile.shards.ToString(); turnLabel.text = run.Phase == Phase.Assault ? "THE HORDE" : run.Phase == Phase.Rest ? "REST NIGHT" : run.Moves == 0 ? "MOVES SPENT" : "YOUR TURN"; string fc = forecastTime > 0 ? run.Forecast : ""; waitLabel.text = fc != "" && run.Phase == Phase.Plan ? fc : run.Phase == Phase.Assault ? run.Remaining + " LEFT" : run.Phase == Phase.Rest ? "FREE MOVES · NO REFILL" : run.Moves + " MOVES · " + run.Remaining + " DEMONS WAIT"; bool attacking = run.Phase == Phase.Assault; if (assaultTint != attacking) { assaultTint = attacking; turnDot.top = Hex(attacking ? "FF7A64" : "A4F09D"); turnDot.bottom = Hex(attacking ? "E1483E" : "5FC56F"); turnStrip.top = Hex(attacking ? "541D26" : "24171B"); turnDot.SetVerticesDirty(); turnStrip.SetVerticesDirty(); } waveLabel.text = "WAVE " + run.Day; leftLabel.text = run.Remaining + " left"; waveFill.sizeDelta = new Vector2(454 * (1 - (float)run.Remaining / Mathf.Max(1, run.WaveTotal)), 10); if (lastPlates != run.Plates || lastMaxPlates != run.MaxPlates) { foreach (Transform child in shieldPips) { child.gameObject.SetActive(false); Destroy(child.gameObject); } gateFractures.SetDamage(run.Plates, run.MaxPlates); float pitch = Mathf.Min(39, 282f / run.MaxPlates); for (int i = 0; i < run.MaxPlates; i++) { bool intact = i < run.Plates; Shield(shieldPips, 145 + (i - run.MaxPlates * .5f) * pitch + 3, 0, pitch - 6, 34, intact ? "FFE798" : "605359", intact ? "EF992D" : "392B33"); } lastPlates = run.Plates; lastMaxPlates = run.MaxPlates; } } void DrawGuide() { Remove(guide); guide = null; if (tutorial < 0) return; guide = Panel(boardStage, "Guide", 35, -267, 680, 207, "211B1C", "C29157", 10).rectTransform; Label(guide, (tutorial + 1) + " / 5 " + GuideTitle[tutorial], 20, 10, 530, 43, 23, Gold); Label(guide, GuideBody[tutorial], 20, 53, 640, 69, 23, Ink, TextAnchor.MiddleLeft, false, false); ButtonAt(guide, "SKIP", 544, 10, 115, 44, FinishGuide, false, 17); if (tutorial == 0) Label(guide, "Make a swap on the board.", 20, 135, 630, 45, 19, Muted); else ButtonAt(guide, tutorial == 4 ? "DEFEND" : "NEXT", 400, 138, 260, 52, () => { if (++tutorial == 5) FinishGuide(); else DrawGuide(); }, true, 20); } void FinishGuide() { tutorial = -1; profile.tutorialDone = true; profile.Save(); DrawGuide(); } } }