using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace TowerDevil { public sealed partial class TowerGame { RectTransform tiles, monsters, fx, shieldPips, sealDetails, guide, shopTarget; RectTransform hud, boardStage, battleFooter, fieldClip; float runwayDepth; CourtyardBackdrop courtyard; PieceShadows pieceShadows; readonly Dictionary courtSprites = new Dictionary(); GateFractures gateFractures; Vector2 fractureOrigin; BattleEffects battleEffects; Button attackButton, repairButton; RawImage attackIcon; readonly Dictionary pieces = new Dictionary(); readonly Dictionary chestHints = new Dictionary(); readonly Dictionary foes = new Dictionary(); readonly List gone = new List(); readonly Queue frames = new Queue(); Text movesLabel, coinLabel, shardLabel, forecastLabel, waveLabel, enemiesLabel; RectTransform waveFill; bool animating; 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[] GuideIcons = { "gauntlet", "shard", "hammer", "woodChest", "swords" }; 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.WaveCleared -= OnWaveCleared; run.BoardChanged -= frames.Enqueue; } run = next; run.Fired += OnFire; run.Hit += OnHit; run.StruckGate += OnGateHit; run.WaveCleared += OnWaveCleared; 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(); chestHints.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, -76, 290, 32); sealDetails = (RectTransform)Hotspot(boardStage, "Seal details", 0, -91, 0, 60, SealSheet).transform; 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, 0, 750, 850); fieldClip.gameObject.AddComponent(); monsters = Box(fieldClip, "Horde", 0, 0, 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; repairButton = Hotspot(boardStage, "Watch ad to mend seal", 0, -105, 88, 88, () => WatchRepairAd(false)); repairButton.targetGraphic = Image(repairButton.transform, "Seal repair icon", "seal_repair_ad", 10, 16, 56, 56); repairButton.transition = Selectable.Transition.ColorTint; BuildBattleHud(); battleFooter = Box(page, "Battle footer", 0, 1113, 750, 221); attackButton = Hotspot(battleFooter, "Primary", 298, 0, 154, 154, BeginAttack); attackIcon = Image(attackButton.transform, "Crossed swords", "battle_swords", 0, 0, 154, 154); shopTarget = (RectTransform)Hotspot(battleFooter, "SHOP", 642, 121, 94, 90, Merchant).transform; Image(shopTarget, "Shop icon", "battle_shop", 9, 7, 76, 76); Fit(); lastDay = run.Day; lastPhase = run.Phase; forecastTime = 6; DrawBoard(run.Board); RefreshHud(); DrawGuide(); } void FitBattle(float safeWidth, float safeHeight) { float extra = Mathf.Max(0, safeHeight - 1334); float boardY = 490 - extra * .19f; hud.anchoredPosition = new Vector2(0, extra * .5f - 49); boardStage.anchoredPosition = new Vector2(0, -boardY); battleFooter.anchoredPosition = new Vector2(0, -1113 - extra * .5f); shopTarget.anchoredPosition = new Vector2(642 + (safeWidth - 750) * .5f, -121); float laneEnd = -battleFooter.anchoredPosition.y - boardY + 82; runwayDepth = laneEnd - BoardLayout.Height; 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))); // Clip arriving feet at the runway entrance. Let heads and health bars overlap the castle. Vector2 viewportOrigin = topLeft - boardStage.anchoredPosition; fieldClip.anchoredPosition = viewportOrigin; fieldClip.sizeDelta = new Vector2(bottomRight.x - topLeft.x, viewportOrigin.y + laneEnd); monsters.anchoredPosition = -viewportOrigin; 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 + 178 - 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, 135); Round(hud, "Portrait setting", 15, 1, 44, 42, "39251C", "F4B943", 14, "170F0D"); headerPortrait = KeepPortrait(hud, "Warden portrait", profile.avatar, 17, 2, 39); headerName = Label(hud, profile.name, 71, 0, 325, 43, 22, Ink); headerName.resizeTextForBestFit = true; headerName.resizeTextMinSize = 15; headerName.resizeTextMaxSize = 22; RefreshPlayerIdentity(); 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); Image(hud, "Wave rail", "battle_wave", 13, 55, 724, 52); waveLabel = Label(hud, "", 42, 60, 94, 42, 20, Ink, TextAnchor.MiddleCenter); waveFill = Round(hud, "Wave progress", 153, 76, 0, 11, "FFD473", "AD6F33", 5, "D4872D").rectTransform; movesLabel = Label(hud, "", 36, 102, 155, 33, 22, Ink); enemiesLabel = Label(hud, "", 551, 102, 166, 33, 22, Ink, TextAnchor.MiddleRight); forecastLabel = Label(hud, "", 184, 102, 366, 33, 14, Gold, TextAnchor.MiddleCenter); } 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; } 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 BeginAttack() { if (modal != null || animating || tutorial >= 0 || !run.BeginAttack()) return; nextAttack = -1; RefreshHud(); StartCoroutine(AnnounceBattle(victory: false)); } 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; if (p.Kind == Kind.Chest && !chestHints.ContainsKey(p)) { float size = BoardLayout.FrontCell * .86f; var halo = Box(rt, "Open chest cue", rt.rect.width * .5f, rt.rect.height * .5f, size, size) .gameObject.AddComponent(); halo.rectTransform.pivot = new Vector2(.5f, .5f); halo.color = Hex("FFD060"); halo.raycastTarget = false; var badge = Round(halo.transform, "Extra moves", size - 34, 3, 34, 22, "FEDA82", "75451D", 10, "E8A438"); Label(badge.transform, "+" + Rules.ChestMoves[p.Tier - 1], 0, 0, 34, 22, 15, Hex("382012"), TextAnchor.MiddleCenter); chestHints.Add(p, halo); } 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); chestHints.Remove(key); } pieceShadows.SetVerticesDirty(); } void LateUpdate() { if (route != "Run") return; bool canOpen = CanUseBoard && tutorial < 0; foreach (var halo in chestHints.Values) { if (halo.gameObject.activeSelf != canOpen) halo.gameObject.SetActive(canOpen); if (!canOpen) continue; float pulse = .5f + .5f * Mathf.Cos(motionTime * (2 * Mathf.PI / 1.4f)); halo.rectTransform.localScale = Vector3.one * Mathf.Lerp(1.02f, .93f, pulse); halo.canvasRenderer.SetAlpha(Mathf.Lerp(.42f, 1f, pulse)); var badge = halo.transform.GetChild(0).gameObject; bool showReward = run.Phase != Phase.Rest; if (badge.activeSelf != showReward) badge.SetActive(showReward); } if (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) { if (!battleAnnouncement || !battleAnnouncement.gameObject.activeInHierarchy) RestSheet(); return; } if (lastDay != run.Day || lastPhase != run.Phase) { if (lastDay != run.Day) { forecastTime = 6; DrawBoard(run.Board); } lastDay = run.Day; lastPhase = run.Phase; RefreshHud(); } } Vector2 Feet(Foe f) { var at = BoardLayout.Center(f.Row, f.Col); if (f.Row >= Foe.RunwayStart) { at.y = -BoardLayout.Height - runwayDepth * (f.Row - Foe.RunwayStart) / (Foe.RunwayEnd - Foe.RunwayStart); } return at; } void RefreshHud() { if (route != "Run") return; bool arranging = run.CanArrange; movesLabel.text = arranging ? "Move " + (run.Phase == Phase.Rest ? "∞" : run.Moves.ToString()) : ""; coinLabel.text = run.Available.ToString(); shardLabel.text = profile.shards.ToString(); forecastLabel.text = forecastTime > 0 && run.Phase == Phase.Plan ? run.Forecast : ""; waveLabel.text = "WAVE " + run.Day; enemiesLabel.text = "Enemies " + run.Remaining; float progress = 1 - Mathf.Clamp01((float)run.Remaining / Mathf.Max(1, run.WaveTotal)); waveFill.gameObject.SetActive(progress > 0); waveFill.sizeDelta = new Vector2(554 * progress, 11); attackButton.interactable = arranging && tutorial < 0 && !animating; attackIcon.texture = Art(attackButton.interactable ? "battle_swords" : "battle_swords_disabled"); if (repairButton.gameObject.activeSelf != run.CanWatchRepairAd) repairButton.gameObject.SetActive(run.CanWatchRepairAd); 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(35, 282f / run.MaxPlates); float center = shieldPips.anchoredPosition.x + shieldPips.rect.width * .5f; float touchWidth = pitch * run.MaxPlates + 12; sealDetails.anchoredPosition = new Vector2(center - touchWidth * .5f, 91); sealDetails.sizeDelta = new Vector2(touchWidth, 60); ((RectTransform)repairButton.transform).anchoredPosition = new Vector2(center + touchWidth * .5f, 105); 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, 30, intact ? "FFE798" : "605359", intact ? "EF992D" : "392B33"); } lastPlates = run.Plates; lastMaxPlates = run.MaxPlates; } } void DrawGuide() { Remove(guide); guide = null; if (tutorial < 0) return; guide = Box(boardStage, "Guide", 35, -267, 680, 207); KeepLayer(guide, "walletPlate", 0, 0, 680, 207); DrawPart(guide, GuideIcons[tutorial], 34, 59, 69, 69, true); KeepText(guide, (tutorial + 1) + " / 5", 28, 132, 83, 32, 18); KeepText(guide, GuideTitle[tutorial], 120, 34, 422, 39, 24, TextAnchor.MiddleLeft).color = Gold; KeepText(guide, GuideBody[tutorial], 120, 73, 507, 69, 20, TextAnchor.MiddleLeft).fontStyle = FontStyle.Normal; var skip = Hotspot(guide, "SKIP", 550, 31, 89, 47, FinishGuide); KeepText(skip.transform, "SKIP", 0, 0, 89, 47, 19); if (tutorial > 0) InscribedButton(guide, tutorial == 4 ? "DEFEND" : "NEXT", 485, 135, 143, 42, () => { if (++tutorial == GuideTitle.Length) FinishGuide(); else DrawGuide(); }, primary: true, font: 18); } void FinishGuide() { tutorial = -1; RefreshHud(); profile.tutorialDone = true; profile.Save(); DrawGuide(); } } }