HexGameApp.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. using UnityEngine.EventSystems;
  8. using TMPro;
  9. using HexaCrazy.Ads;
  10. using Random=System.Random;
  11. namespace HexaCrazy
  12. {
  13. public partial class HexGameApp : MonoBehaviour
  14. {
  15. public LevelDatabase levels;
  16. public TMP_FontAsset displayFont, bodyFont;
  17. public bool automatedReview;
  18. public LocalProfile Profile { get; private set; }
  19. internal RewardedAds Ads { get; set; }
  20. public HexRules Game { get; private set; }
  21. public string ScreenName { get; private set; }
  22. public bool Busy { get; private set; }
  23. public bool Paused => modal!=null;
  24. public int SelectedSlot { get; private set; }=-1;
  25. public RectTransform Root { get; private set; }
  26. public RectTransform Modal => modal;
  27. Canvas canvas; RectTransform page,boardLayer,handLayer,dockLayer,fxLayer,modal,toastLayer;
  28. HexProgress progress; TextMeshProUGUI scoreText,timeText,hintText; Vector2[] cellPositions;
  29. float cellWidth, cellHeight, toastUntil; int modeIndex,activePointerSlot=-1; bool hammer,finished,drawBusy;
  30. RectTransform dragGhost; Coroutine actionRoutine; HexAudio audioPlayer;
  31. readonly Random rng=new Random(); readonly Stack<string> panelHistory=new Stack<string>(); string currentPanel;
  32. int screenW,screenH, resumedFrame = -1; Rect lastSafe;
  33. HexLobbyCarousel carousel;TextMeshProUGUI playHint,playLabel;readonly Image[] modeDots=new Image[3];
  34. public int SelectedMode => modeIndex;
  35. void Awake()
  36. {
  37. Application.targetFrameRate=60; Screen.orientation=ScreenOrientation.Portrait;
  38. if(levels==null) levels=LevelDatabase.LoadDefault();
  39. if(displayFont==null) displayFont=Resources.Load<TMP_FontAsset>("HexaArt/Fonts/Display SDF");
  40. if(bodyFont==null) bodyFont=Resources.Load<TMP_FontAsset>("HexaArt/Fonts/Body SDF");
  41. HexUI.Display=displayFont; HexUI.Body=bodyFont;
  42. Profile=new LocalProfile(System.IO.Path.Combine(Application.persistentDataPath,"hexa-crazy-v1.json"));
  43. audioPlayer=gameObject.AddComponent<HexAudio>(); HexUI.Tap=()=>audioPlayer.Play("tap"); SyncAudio();
  44. var go=new GameObject("HexaCanvas",typeof(RectTransform),typeof(Canvas),typeof(CanvasScaler),typeof(GraphicRaycaster)); go.transform.SetParent(transform,false);
  45. canvas=go.GetComponent<Canvas>(); canvas.renderMode=RenderMode.ScreenSpaceOverlay; canvas.sortingOrder=10;
  46. var scaler=go.GetComponent<CanvasScaler>(); scaler.uiScaleMode=CanvasScaler.ScaleMode.ScaleWithScreenSize; scaler.referenceResolution=new Vector2(750,1334); scaler.matchWidthOrHeight=.5f;
  47. var bg=HexUI.Image(go.transform,"VelvetBackground","background",0,0,750,1334); bg.rectTransform.anchorMin=Vector2.zero;bg.rectTransform.anchorMax=Vector2.one;bg.rectTransform.offsetMin=bg.rectTransform.offsetMax=Vector2.zero;
  48. var backgroundFit=bg.gameObject.AddComponent<AspectRatioFitter>();backgroundFit.aspectRatio=bg.sprite.rect.width/bg.sprite.rect.height;backgroundFit.aspectMode=AspectRatioFitter.AspectMode.EnvelopeParent;
  49. Root=HexUI.Node(go.transform,"SafeDesignCanvas",0,0,750,1334);Root.anchorMin=Root.anchorMax=new Vector2(.5f,.5f);Root.anchoredPosition=Vector2.zero;
  50. page=Layer("Page");fxLayer=Layer("Effects");toastLayer=Layer("Toasts");
  51. if(FindAnyObjectByType<EventSystem>()==null){var es=new GameObject("EventSystem",typeof(EventSystem),typeof(StandaloneInputModule));es.transform.SetParent(transform);}
  52. FitSafeArea();
  53. AppRuntimesEvents.OnPlatformOpen += HandlePlatformOpen;
  54. }
  55. void OnDestroy() => AppRuntimesEvents.OnPlatformOpen -= HandlePlatformOpen;
  56. void HandlePlatformOpen()
  57. {
  58. audioPlayer.StopMusic();
  59. if (!Profile.Data.music && Profile.Available) return;
  60. Profile.Data.music = false;
  61. Profile.Save();
  62. if (currentPanel == "settings") Reopen("settings");
  63. }
  64. void Start() { Ads = Ads != null ? Ads : AdMobRewardedAds.Shared(); ShowStart(); }
  65. RectTransform Layer(string name) => HexUI.Node(Root,name,375,667,750,1334);
  66. void SyncAudio(){audioPlayer.Music=gameStarted&&Profile.Data.music;audioPlayer.Sound=Profile.Data.sound;}
  67. void Update()
  68. {
  69. RefreshAdButton();
  70. if(screenW!=Screen.width||screenH!=Screen.height||lastSafe!=Screen.safeArea) FitSafeArea();
  71. if(toastLayer!=null&&toastLayer.childCount>0&&Time.unscaledTime>toastUntil) HexUI.Clear(toastLayer);
  72. if(Input.GetKeyDown(KeyCode.Escape)) { if(currentPanel=="result"){}else if(modal!=null)ClosePanel();else if(ScreenName=="Game")OpenPanel("pause"); }
  73. if(ScreenName=="Game"&&Game!=null&&!Game.Over&&!Paused&&Game.Spec.mode==1 && Time.frameCount != resumedFrame)
  74. { Game.Time=Mathf.Max(0,Game.Time-Time.unscaledDeltaTime);UpdateHud();if(Game.Time<=0 && !Busy)CheckEnd(); }
  75. }
  76. void FitSafeArea()
  77. {
  78. screenW=Screen.width;screenH=Screen.height;lastSafe=Screen.safeArea;
  79. if(screenW<=0||screenH<=0)return;
  80. Canvas.ForceUpdateCanvases(); var cr=(RectTransform)canvas.transform;var sz=cr.rect.size;
  81. var safe=lastSafe;float sw=sz.x*safe.width/screenW,sh=sz.y*safe.height/screenH;
  82. float scale=Mathf.Min(sw/750f,sh/1334f);Root.localScale=Vector3.one*scale;
  83. Root.anchoredPosition=new Vector2((safe.center.x/screenW-.5f)*sz.x,(safe.center.y/screenH-.5f)*sz.y);
  84. }
  85. void CleanPage(string screen)
  86. {
  87. if(actionRoutine!=null){StopCoroutine(actionRoutine);actionRoutine=null;} Busy=false;finished=false;SelectedSlot=-1;hammer=false;
  88. if(dragGhost!=null)Destroy(dragGhost.gameObject);dragGhost=null;activePointerSlot=-1;
  89. RemoveModal();panelHistory.Clear();currentPanel=null;HexUI.Clear(page);HexUI.Clear(fxLayer);ScreenName=screen;
  90. ResetPresentation();
  91. gameStartButton=null;
  92. carousel=null;playHint=null;playLabel=null;
  93. }
  94. void Logo(Transform p,float y,float w=500)
  95. {
  96. if(HexUI.Sprite("logo")!=null)HexUI.Image(p,"GameLogo","logo",375,y,w,w*.32f);
  97. else {HexUI.Image(p,"LogoPlate","marquee",375,y,w,w*.32f);HexUI.Text(p,"GameLogo","HEXA CRAZY 7+",375,y,w-70,w*.22f,56,true);}
  98. }
  99. public void ShowStart()
  100. {
  101. CleanPage("Start");Game=null;
  102. HexUI.Text(page,"SinglePlayer","FREE PLAY · NO CASH VALUE",375,280,600,30,19);
  103. Logo(page,405,550);HexUI.Image(page,"Divider","ornament",375,510,280,24);
  104. for(int i=0;i<6;i++){float a=i*Mathf.PI/3;HexUI.Tile(page,new[]{0,1,3,4,5,6}[i],2,375+Mathf.Cos(a)*113,685+Mathf.Sin(a)*105,111,false);}
  105. HexUI.Tile(page,2,3,375,685,128,false);
  106. HexUI.Text(page,"Pitch","DRAG · STACK 8 · CHAIN CLEAR",375,860,620,44,24);
  107. HexUI.Text(page,"Modes","3 MODES · 60 LEVELS · OFFLINE",375,908,600,30,19,false,HexUI.Muted);
  108. gameStartButton=HexUI.Button(page,"GameStart","GAME START",375,1018,540,120,EnterGameFromStart,"primary",50,true);
  109. gameStartButton.interactable=!gameStarted;
  110. HexUI.Text(page,"Version","HEXA CRAZY 7+ · v1.0",375,1176,600,30,16,false,HexUI.Muted);
  111. }
  112. public void ShowLobby()
  113. {
  114. CleanPage("Lobby");Game=null;
  115. var d=Profile.Data;
  116. var bar = HexUI.Image(page, "PlayerBar", "player_header_rail", 375, 74, 730, 100);
  117. var profile = HexUI.Button(bar.transform, "ProfileAvatar", "", 219, 50, 322, 84, () => OpenPanel("profile"), null);
  118. var medal = HexUI.Image(profile.transform, "PortraitMedal", "medallion", 45, 42, 75, 75);
  119. profile.targetGraphic = medal;
  120. HexUI.Image(medal.transform, "Avatar", HexUI.Symbols[Mathf.Clamp(d.avatar, 0, HexUI.Symbols.Length - 1)], 37.5f, 33, 47, 47);
  121. var nickname = LeftText(profile.transform, "Nickname", d.nickname, 98, 28, 221, 37, 30, true);
  122. nickname.textWrappingMode = TextWrappingModes.NoWrap;
  123. nickname.fontSizeMin = 14;
  124. LeftText(profile.transform, "PlayerLevel", "LOCAL PLAYER · LV. " + (1 + d.totalWins / 3), 99, 62, 219, 26, 17, false, HexUI.Muted);
  125. var wallet = HexUI.Button(bar.transform, "CoinBalance", "", 504, 50, 215, 61, () => OpenPanel("shop"), "wallet_frame");
  126. HexUI.Image(wallet.transform, "Coins", "reward_coins", 32, 30, 37, 37);
  127. var balance = HexUI.Text(wallet.transform, "Balance", d.coins.ToString("N0"), 113, 30, 118, 37, 26);
  128. balance.textWrappingMode = TextWrappingModes.NoWrap;
  129. balance.fontSizeMin = 13;
  130. var arrow = HexUI.Image(wallet.transform, "ShopArrow", "icon_back", 185, 30, 15, 19);
  131. arrow.rectTransform.localScale = new Vector3(-1, 1, 1);
  132. var settings = HexUI.Button(bar.transform, "Settings", "", 646, 50, 66, 80, () => OpenPanel("settings"), null);
  133. settings.targetGraphic = HexUI.Image(settings.transform, "Icon", "pref_gear", 33, 40, 48, 48);
  134. Logo(page,205,500);HexUI.Text(page,"SelectTitle","SELECT YOUR TABLE",375,312,600,50,29);
  135. HexUI.Image(page,"SelectLineLeft","ornament",110,312,135,14);HexUI.Image(page,"SelectLineRight","ornament",640,312,135,14);
  136. var deck=HexUI.Image(page,"ModeDeck",null,375,654,750,612,Color.clear);deck.raycastTarget=true;deck.gameObject.AddComponent<RectMask2D>();
  137. var cards=Enumerable.Range(0,3).Select(m=>ModeCard(deck.transform,m)).ToArray();
  138. carousel=deck.gameObject.AddComponent<HexLobbyCarousel>();carousel.Initialize(this,cards,modeIndex);
  139. HexUI.IconButton(page,"PreviousMode","back",70,650,70,()=>SetMode((modeIndex+2)%3));
  140. var next=HexUI.IconButton(page,"NextMode","back",680,650,70,()=>SetMode((modeIndex+1)%3));next.transform.Find("Icon").localScale=new Vector3(-1,1,1);
  141. for(int i=0;i<3;i++){int index=i;var dot=HexUI.Button(page,"ModeDot"+i,"",335+i*40,987,18,18,()=>SetMode(index),"coin");modeDots[i]=dot.image;}
  142. var play = HexUI.Button(page, "Play", "PLAY", 375, 1069, 494, 104, StartCurrentMode, "primary", 61, true);
  143. playLabel = play.GetComponentInChildren<TextMeshProUGUI>();
  144. playHint = HexUI.Text(page, "NextLevel", "", 375, 1147, 580, 34, 22, false, HexUI.Cream);
  145. CarouselSelectionChanged(modeIndex);
  146. string[] panels = { "checkin", "shop", "draw", "help", "profile" };
  147. string[] labels = { "CHECK-IN", "SHOP", "DRAW", "HELP", "PROFILE" };
  148. var dock = HexUI.Image(page, "LobbyDock", "lobby_nav_rail", 375, 1248, 730, 140);
  149. for (int i = 0; i < panels.Length; i++)
  150. {
  151. string panel = panels[i];
  152. const float slotWidth = 116;
  153. float center = 365 + (i - 2) * slotWidth;
  154. var entry = HexUI.Button(dock.transform, "Dock_" + panel, "", center, 70, slotWidth, 112, () => OpenPanel(panel), null);
  155. entry.targetGraphic = HexUI.Image(entry.transform, "Icon", "dock_" + panel, slotWidth / 2, 39, 54, 54);
  156. var label = HexUI.Text(entry.transform, "Label", labels[i], slotWidth / 2, 88, slotWidth, 29, 19);
  157. label.characterSpacing = 2;
  158. if ((i == 0 && Profile.CanCheckin) || (i == 2 && (Profile.FreeDraw || d.tickets > 0)))
  159. HexUI.Image(entry.transform, "Notification", "chip_red", slotWidth / 2 + 32, 20, 17, 15);
  160. }
  161. }
  162. Button ModeCard(Transform parent,int mode)
  163. {
  164. int lv=Mathf.Min(20,Profile.Data.cleared[mode]+1);var spec=levels.Get(mode,lv);
  165. var card=HexUI.Button(parent,"ModeCard"+mode,"",375,306,522,612,()=>{if(mode==modeIndex&&!carousel.IsAnimating)StartCurrentMode();else SetMode(mode);},"card");
  166. var c=card.transform;
  167. HexUI.Image(c,"ModeBadge","primary",105,52,160,48);HexUI.Text(c,"ModeTag",new[]{"NO TIMER","TIMED","LOCKED"}[mode],105,52,145,35,21);
  168. HexUI.Text(c,"Level","LV "+lv+" / 20",412,52,168,40,22);
  169. HexUI.Tile(c,2,2,261,135,145,false);HexUI.Tile(c,0,3,165,205,145,false);HexUI.Tile(c,1,3,357,205,145,false);HexUI.Tile(c,3,2,261,271,145,false);
  170. HexUI.Image(c,"ModeMedal","medallion",261,226,128,128);HexUI.Image(c,"ModeIcon","icon_"+(mode==2?"lock":mode==1?"clock":"swap"),261,217,70,70);
  171. HexUI.Text(c,"ModeTitle",LevelDatabase.ModeNames[mode],261,356,490,80,55,true);
  172. HexUI.Text(c,"ModeSubtitle",new[]{"STEADY · NO RUSH","BEAT THE CLOCK","UNLOCK THE HIVE"}[mode],261,405,465,36,24);
  173. HexUI.Text(c,"ModeDescription",new[]{"Merge matching stacks. Take your time.","Every clear buys four more seconds.","Score points to open locked cells."}[mode],261,446,470,38,21);
  174. HexUI.Image(c,"TargetPlaque","primary",261,498,290,50);HexUI.Text(c,"Target","TARGET "+spec.target,261,498,280,42,31,true);
  175. HexUI.Text(c,"Attributes",spec.cells+" CELLS · "+spec.colors+" COLORS",261,542,460,28,20);
  176. HexUI.Image(c,"ProgressPanel","panel",261,582,472,45,null,true);HexUI.Text(c,"Cleared","CLEARED "+Profile.Data.cleared[mode]+"/20",133,581,225,28,21);
  177. HexUI.Image(c,"ProgressTrack","bar",351,581,224,20);
  178. HexUI.Fill(c,"ProgressFill",351,581,210,10).Value=Profile.Data.cleared[mode]/20f;
  179. return card;
  180. }
  181. public void SetMode(int mode)
  182. {
  183. mode=(mode%3+3)%3;
  184. if(ScreenName=="Lobby"&&carousel!=null){carousel.Select(mode);return;}
  185. modeIndex=mode;ShowLobby();
  186. }
  187. public void CarouselSelectionChanged(int mode)
  188. {
  189. modeIndex=mode;int done=Profile.Data.cleared[mode],level=Mathf.Min(20,done+1);
  190. if(playHint!=null)playHint.text=LevelDatabase.ModeNames[mode]+" · LEVEL "+level;
  191. if(playLabel!=null)playLabel.text=done>=20?"REPLAY":"PLAY";
  192. for(int i=0;i<3;i++)if(modeDots[i]!=null){modeDots[i].color=i==mode?HexUI.Cream:new Color(.6f,.45f,.3f);modeDots[i].transform.localScale=Vector3.one*(i==mode?1.16f:1);}
  193. }
  194. void StartCurrentMode(){StartLevel(modeIndex,Mathf.Min(20,Profile.Data.cleared[modeIndex]+1));}
  195. public void StartLevel(int mode,int level,bool skipTutorial=false)
  196. {
  197. CleanPage("Game");modeIndex=mode;Game=new HexRules(levels.Get(mode,level),rng.Next(),!skipTutorial&&Profile.Data.tutorial==0);
  198. HexUI.IconButton(page,"BackToLobby","back",88,116,78,LeaveGame);
  199. HexUI.Image(page,"LevelMarquee","marquee",375,113,420,123);
  200. HexUI.Text(page,"LevelLabel","LEVEL "+level,375,102,390,64,57,true);
  201. HexUI.Text(page,"ModeLabel",LevelDatabase.ModeNames[mode],375,137,340,32,24);
  202. HexUI.IconButton(page,"Pause","pause",664,116,78,()=>OpenPanel("pause"));
  203. HexUI.Image(page,"ScorePanel","panel",375,220,700,58,null,true);
  204. HexUI.Text(page,"ScoreTitle","SCORE",90,220,122,42,28,true);
  205. HexUI.Image(page,"ScoreDivider",null,170,220,1.5f,25,HexUI.Gold);
  206. scoreText=HexUI.Text(page,"ScoreValue","0 / "+Game.Spec.target,252,220,160,42,31);
  207. var scoreRoot=HexUI.Node(page,"ScoreBar",515,220,346,28);
  208. HexUI.Image(scoreRoot,"ScoreTrough","bar",173,14,346,28);
  209. progress=HexUI.Fill(scoreRoot,"ScoreFill",173,14,330,17);
  210. scoreBar=scoreRoot.gameObject.AddComponent<HexScoreBar>();scoreBar.Initialize(this,progress,scoreText,Game.Spec.target);
  211. timeText=HexUI.Text(page,"Timer","",640,278,150,40,29,true);
  212. boardLayer=HexUI.Node(page,"Board",375,667,750,1334);handLayer=HexUI.Node(page,"Hand",375,667,750,1334);dockLayer=HexUI.Node(page,"PowerUps",375,667,750,1334);
  213. hintText=HexUI.Text(page,"Hint","DRAG TO AN EMPTY CELL",375,951,450,42,24);
  214. HexUI.Image(page,"HandDividerLeft","ornament",110,951,80,12);HexUI.Image(page,"HandDividerRight","ornament",640,951,80,12);
  215. LayoutBoard();DrawBoard();DrawHand();DrawDock();UpdateHud();
  216. if(!skipTutorial&&Profile.Data.tutorial==0) ShowTutorial();
  217. }
  218. void LayoutBoard()
  219. {
  220. float minQ=Game.Cells.Min(c=>c.q),maxQ=Game.Cells.Max(c=>c.q),minY=Game.Cells.Min(c=>c.r+c.q*.5f),maxY=Game.Cells.Max(c=>c.r+c.q*.5f);
  221. float ratio=HexUI.HexHeightRatio;
  222. float radius=Mathf.Min(68,660/(1.5f*(maxQ-minQ)+1.9f),610/(1.732f*(maxY-minY)+1.9f*ratio));cellWidth=radius*1.9f;cellHeight=cellWidth*ratio;
  223. cellPositions=Game.Cells.Select(c=>new Vector2(375+1.5f*radius*(c.q-(minQ+maxQ)*.5f),610+1.732f*radius*(c.r+c.q*.5f-(minY+maxY)*.5f))).ToArray();
  224. }
  225. void DrawBoard()
  226. {
  227. RenderBoardViews();
  228. }
  229. void DrawHand()
  230. {
  231. HexUI.Clear(handLayer);
  232. for(int i=0;i<3;i++)
  233. {
  234. float x=210+i*165;var im=HexUI.Image(handLayer,"HandSlot_"+i,"holder",x,1058,148,130,SelectedSlot==i?HexUI.Gold:Color.white); im.raycastTarget=true;
  235. var drag=im.gameObject.AddComponent<HandDrag>();drag.app=this;drag.slot=i;
  236. if(Game.Hand[i]!=null){var h=Game.Hand[i];HexUI.Tile(handLayer,h.color,h.count,x,1058,125);}
  237. }
  238. }
  239. void DrawDock()
  240. {
  241. if (dockLayer == null) return;
  242. HexUI.Clear(dockLayer);
  243. var tray = HexUI.Image(dockLayer, "DockPanel", "game_tool_tray", 375, 1244, 730, 146);
  244. const float slotWidth = 142;
  245. for (int i = 0; i < HexUI.ItemIcons.Length; i++)
  246. {
  247. int item = i;
  248. float center = 365 + (i - 1.5f) * slotWidth;
  249. var button = HexUI.Button(tray.transform, "UseItem_" + i, "", center, 73, slotWidth, 116, () => UseItem(item), null);
  250. var face = button.transform;
  251. int stock = Profile.Data.items[i];
  252. string count = stock.ToString();
  253. Color ink = stock == 0 ? HexUI.Muted : HexUI.Cream;
  254. Color tint = stock == 0 ? new Color(.65f, .61f, .66f) : Color.white;
  255. float badgeWidth = Mathf.Max(34, 14 + count.Length * 11);
  256. float iconSize = Mathf.Min(60, slotWidth - badgeWidth - 6);
  257. button.targetGraphic = HexUI.Image(face, "Icon", "power_" + HexUI.ItemIcons[i],
  258. (slotWidth - badgeWidth) / 2, 42, iconSize, iconSize, tint);
  259. float badgeX = (slotWidth + iconSize) / 2;
  260. HexUI.Image(face, "CountBadge", "badge", badgeX, 30, badgeWidth, 29, tint);
  261. HexUI.Text(face, "Count", count, badgeX, 30, badgeWidth - 10, 26, 20, false, ink);
  262. if (hammer && i == 0)
  263. HexUI.Image(face, "Armed", "primary", slotWidth / 2, 93, 126, 32);
  264. var label = HexUI.Text(face, "Label", LevelDatabase.ItemNames[i], slotWidth / 2, 93, 120, 28, 19, false, ink);
  265. label.characterSpacing = 2;
  266. }
  267. }
  268. void SetHammerSelected(bool selected)
  269. {
  270. if (hammer == selected) return;
  271. hammer = selected;
  272. hintText.text = selected ? "TAP ANY STACK TO SMASH IT" : "DRAG TO AN EMPTY CELL";
  273. DrawDock();
  274. }
  275. void UpdateHud()
  276. {
  277. if(Game==null||scoreText==null)return;scoreBar.SetScore(VisibleScore,Profile.Data.reduceMotion);
  278. if(Game.Spec.mode==1){int sec=Mathf.CeilToInt(Game.Time);timeText.text=(sec/60)+":"+(sec%60).ToString("00");timeText.color=sec<=15?HexUI.ColorOf("FF6075"):HexUI.Cream;}else timeText.text="";
  279. }
  280. void ShowTutorial()
  281. {
  282. if(hintText!=null)hintText.text=SelectedSlot<0?"DRAG THIS GROUP TO THE BOARD":"DROP IT NEXT TO THE SAME COLOR";
  283. var old=fxLayer.Find("Tutorial");if(old!=null)Destroy(old.gameObject);
  284. var rt=HexUI.Node(fxLayer,"Tutorial",375,667,750,1334);
  285. int center=Game.Cells.FindIndex(c=>c.q==0&&c.r==0);
  286. int target=Game.Neighbors(center).Where(Game.CanPlace).DefaultIfEmpty(-1).First();
  287. if(target<0) target=Enumerable.Range(0,Game.Cells.Count).Where(Game.CanPlace).DefaultIfEmpty(-1).First();
  288. if(target<0)return;
  289. var p=SelectedSlot<0?new Vector2(210,1150):cellPositions[target]+new Vector2(0,65);
  290. var finger=HexUI.Image(rt,"Finger","finger",p.x,p.y,49,65);if(SelectedSlot>=0)finger.rectTransform.localRotation=Quaternion.Euler(0,0,180);
  291. if(!Profile.Data.reduceMotion)finger.gameObject.AddComponent<UIPulse>();
  292. }
  293. public void SelectHand(int slot)
  294. {
  295. if(ScreenName!="Game"||Game.Over||Busy||Paused||activePointerSlot>=0||Game.Hand[slot]==null)return;
  296. SetHammerSelected(false);SelectedSlot=SelectedSlot==slot?-1:slot;audioPlayer.Play("pick");DrawBoard();DrawHand();
  297. if(Profile.Data.tutorial==0)ShowTutorial();
  298. }
  299. public bool BeginHandDrag(int slot,Vector2 screen)
  300. {
  301. if(ScreenName!="Game"||Game.Over||Busy||Paused||Game.Hand[slot]==null||activePointerSlot>=0)return false;
  302. SelectedSlot=slot;activePointerSlot=slot;SetHammerSelected(false);var h=Game.Hand[slot];dragGhost=HexUI.Tile(fxLayer,h.color,h.count,0,0,132);MoveHandDrag(screen);DrawBoard();audioPlayer.Play("pick");if(Profile.Data.tutorial==0)ShowTutorial();return true;
  303. }
  304. public Vector2 ScreenToDesign(Vector2 screen){RectTransformUtility.ScreenPointToLocalPointInRectangle(Root,screen,null,out var p);return new Vector2(p.x+375,667-p.y);}
  305. public void MoveHandDrag(Vector2 screen){if(dragGhost!=null){var p=ScreenToDesign(screen);dragGhost.anchoredPosition=new Vector2(p.x,-p.y-44);}}
  306. public int HitCell(Vector2 p)
  307. {
  308. if(cellPositions==null)return -1;
  309. for(int i=0;i<cellPositions.Length;i++){var d=p-cellPositions[i];float x=Mathf.Abs(d.x)/(cellWidth*.5f),y=Mathf.Abs(d.y)/(cellHeight*.5f);if(x<=1&&y<=1&&x+y*.5f<=1)return i;}return -1;
  310. }
  311. public void EndHandDrag(Vector2 screen)
  312. { if(dragGhost!=null)Destroy(dragGhost.gameObject);dragGhost=null;int target=HitCell(ScreenToDesign(screen));activePointerSlot=-1;if(target>=0)TapCell(target);else{SelectedSlot=-1;DrawBoard();DrawHand();} }
  313. public void TapCell(int i)
  314. {
  315. if(Game==null||Game.Over||Busy||Paused)return;
  316. if(hammer){if(Game.Hammer(i)){Profile.Data.items[0]--;Profile.Save();SetHammerSelected(false);audioPlayer.Play("hammer");DrawBoard();CheckEnd();}else Toast("Tap a stack to smash it");return;}
  317. if(SelectedSlot<0)return;
  318. if(!Game.CanPlace(i)){audioPlayer.Play("error");Toast(Game.Locked(i)?"Locked · "+(Game.Cells[i].need-Game.Score)+" pts to go":"Cell is taken · use an empty cell");return;}
  319. int slot=SelectedSlot;SelectedSlot=-1;Busy=true;actionRoutine=StartCoroutine(PlayMove(slot,i));
  320. }
  321. public bool PlaceAt(int slot,int cell){if(Game==null||Busy||Paused||Game.Hand[slot]==null||!Game.CanPlace(cell))return false;SelectHand(slot);TapCell(cell);return true;}
  322. IEnumerator PlayMove(int slot,int cell)
  323. {
  324. BeginPresentation();
  325. foreach(var step in Game.Place(slot,cell))
  326. {
  327. if(Game.Over)yield break;
  328. if(!Profile.Data.reduceMotion)yield return AnimatePresentationStep(step);
  329. if(Game.Over)yield break;
  330. CommitPresentationStep(step);
  331. audioPlayer.Play(step.kind==StepKind.Clear?"clear":step.kind==StepKind.Merge?"merge":step.kind==StepKind.Place?"place":"grow",step.chain);
  332. }
  333. presenting=false;AnimationStep=null;DrawBoard();DrawHand();DrawDock();UpdateHud();
  334. if(!Profile.Data.reduceMotion&&Game.Score>=Game.Spec.target)
  335. while(scoreBar.IsAnimating&&!Game.Over)yield return null;
  336. if(Game.Over)yield break;
  337. Busy=false;actionRoutine=null;CheckEnd();
  338. }
  339. public void UseItem(int item)
  340. {
  341. if(Game==null||Game.Over||Busy||Paused)return;
  342. if(Profile.Data.items[item]<=0){OpenPanel("shop");Toast("Out of items · visit the shop");return;}
  343. if(item==0){SelectedSlot=-1;SetHammerSelected(!hammer);DrawBoard();DrawHand();return;}
  344. if(item==1)Game.Refill(true);else if(item==2)Game.Bonus();else if(!Game.Unlock()){Toast("No locked cells left");return;}
  345. Profile.Data.items[item]--;Profile.Save();audioPlayer.Play(item==1?"swap":item==2?"bonus":"unlock");DrawHand();DrawBoard();DrawDock();if(item==1)CheckEnd();
  346. }
  347. void CheckEnd()
  348. {
  349. if (Game.Score >= Game.Spec.target) Finish(true,"CLEARED");
  350. else if (Game.Spec.mode == 1 && Game.Time <= 0) Finish(false,"TIME UP");
  351. else if (!Game.HasSpace) Finish(false,"NO MOVES");
  352. }
  353. string resultTitle;bool resultWin;int resultCoins,resultTicket;
  354. void Finish(bool win,string title)
  355. {
  356. if(finished||Game==null||Game.Over)return;finished=true;Game.Over=true;Busy=true;
  357. if(actionRoutine!=null){StopCoroutine(actionRoutine);actionRoutine=null;}HexUI.Clear(fxLayer);
  358. activeFlights.Clear();flightPool.Clear();presenting=false;AnimationStep=null;DrawBoard();UpdateHud();
  359. resultTitle=title;resultWin=win;resultCoins=win?Game.Spec.Reward+Game.Clears:0;resultTicket=win?Profile.Win(Game.Spec,Game.Clears,Game.Score,rng):0;
  360. audioPlayer.Play(win?"win":"lose");
  361. if(win&&!Profile.Data.reduceMotion)StartCoroutine(WinCelebration());else OpenPanel("result");
  362. }
  363. IEnumerator WinCelebration()
  364. {
  365. var bits=new List<RectTransform>();for(int i=0;i<96;i++){var im=HexUI.Image(fxLayer,"Confetti",null,rng.Next(750),rng.Next(-700,0),rng.Next(5,12),rng.Next(12,23),UnityEngine.Random.ColorHSV(0,1,.65f,1,.85f,1));bits.Add(im.rectTransform);}
  366. var clear=HexUI.Text(fxLayer,"ClearBurst","CLEAR!",375,570,720,170,112,true);
  367. for(float t=0;t<1.15f;t+=Time.unscaledDeltaTime){foreach(var b in bits){b.anchoredPosition+=new Vector2(Mathf.Sin(t*3+b.GetSiblingIndex())*30,-1000)*Time.unscaledDeltaTime;b.Rotate(0,0,100*Time.unscaledDeltaTime);}clear.transform.localScale=Vector3.one*(1+Mathf.Sin(t*8)*.04f);yield return null;}
  368. HexUI.Clear(fxLayer);OpenPanel("result");
  369. }
  370. public void LeaveGame(){if(Game!=null)Game.Over=true;ShowLobby();}
  371. public void Toast(string message)
  372. {
  373. HexUI.Clear(toastLayer);toastLayer.SetAsLastSibling();HexUI.Image(toastLayer,"ToastPanel","panel",375,332,670,62,null,true);HexUI.Text(toastLayer,"ToastText",message,375,332,640,52,21);toastUntil=Time.unscaledTime+2.1f;
  374. }
  375. void OnApplicationPause(bool paused){if(paused){Profile?.Save();if(ScreenName=="Game"&&Game!=null&&!Game.Over&&!Paused)OpenPanel("pause");}}
  376. void OnApplicationFocus(bool focus){if(!focus&&!automatedReview&&ScreenName=="Game"&&Game!=null&&!Game.Over&&!Paused)OpenPanel("pause");}
  377. void OnApplicationQuit(){Profile?.Save();}
  378. public void UseReviewProfile(string path){automatedReview=true;Profile=new LocalProfile(path);SyncAudio();}
  379. public void PreviewApprovedGameplay()
  380. {
  381. StartLevel(2,1,true);foreach(var c in Game.Cells){c.tiles.Clear();c.need=0;}
  382. Action<int,int,int,int> put=(q,r,color,n)=>Game.Cells.First(c=>c.q==q&&c.r==r).tiles.AddRange(Enumerable.Repeat(color,n));
  383. put(-2,0,0,3);put(-1,0,1,4);put(0,0,2,2);put(1,1,3,3);put(2,-1,0,4);put(0,2,1,2);
  384. Game.Score=36;Game.Cells.First(c=>c.q==0&&c.r==-2).need=84;Game.Cells.First(c=>c.q==-2&&c.r==2).need=92;Game.Cells.First(c=>c.q==2&&c.r==0).need=100;
  385. Game.Hand=new[]{new HandGroup(0,3),new HandGroup(1,2),new HandGroup(2,4)};DrawBoard();DrawHand();UpdateHud();
  386. }
  387. }
  388. public sealed class UIPulse:MonoBehaviour {void Update(){transform.localScale=Vector3.one*(1+Mathf.Sin(Time.unscaledTime*4)*.08f);}}
  389. }