Repository navigation
Expand file tree
/
Copy pathGame.lua
More file actions
1629 lines (1482 loc) · 59.7 KB
/
Copy pathGame.lua
File metadata and controls
1629 lines (1482 loc) · 59.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local ADDON_NAME, ns = ...
local Game = {}
ns.Game = Game
local Utils = ns.Utils
local sformat = Utils.sformat
local GetTime = Utils.GetTime
local tinsert = Utils.tinsert
local tremove = Utils.tremove
local tsort = Utils.tsort
local wipe = Utils.wipe
local mabs = Utils.mabs
local mfloor = Utils.mfloor
local mmin, mmax = Utils.mmin, Utils.mmax
local ipairs = Utils.ipairs
local pairs = Utils.pairs
local CreateFrame = Utils.CreateFrame
local HasAction = HasAction
local GetActionTexture = GetActionTexture
local GetBindingKey = GetBindingKey
local InCombatLockdown = InCombatLockdown
local IsShiftKeyDown = IsShiftKeyDown
local IsControlKeyDown = IsControlKeyDown
local IsAltKeyDown = IsAltKeyDown
local UIParent = UIParent
local isRunning = false
local isPaused = false
local currentMode = "timed" -- "timed", "practice", "competitive"
local activeNotes = {}
local availableSlots = {}
local destroyedLanes = {} -- [slotIndex] = expireTime
local barExtents = {} -- [barKey] = { l, r, b, t } screen px of each included bar
-- Reverse lookup: keybind string -> slotInfo
local keybindToSlot = {}
local score = 0
local combo = 0
local maxCombo = 0
local multiplier = 1
local hitCounts = { perfect = 0, great = 0, good = 0, miss = 0, redHerring = 0 }
local spawnAccumulator = 0
local gameStartTime = 0
local gameDuration = 0 -- 0 = unlimited (practice)
local gameElapsed = 0 -- tracks actual play time (excludes pauses)
local pauseStartTime = 0
local mirrorFlipped = false
local nextMirrorFlip = 0
local gameModifiers = {}
-- DDR-style "money score": a flawless run of ANY track lands at SCORE_CAP,
-- regardless of length. A note is worth SCORE_CAP / noteBudget, scaled by how
-- cleanly it was hit. The old per-note point values ran to hundreds of thousands
-- and scaled with track length, which maxed every rank on the first decent game.
local SCORE_CAP = 10000
local JUDGE_WEIGHT = { perfect = 1.0, great = 0.75, good = 0.45, miss = 0 }
local COMBO_THRESHOLDS = { 5, 10, 20, 35 }
-- Bomb fuse and fake-note laugh. Forever lacks the two sound kits but ships
-- their files, so it plays those directly.
local FUSE_FILES = { 2066602, 2066603 }
local LAUGH_FILES = { 541902, 541940, 541894, 541985 }
local function PlayFuseSound()
if Utils.IS_FOREVER then
return PlaySoundFile(FUSE_FILES[math.random(#FUSE_FILES)], "SFX")
end
return PlaySound(268433, "SFX", false)
end
local function PlayLaughSound()
if Utils.IS_FOREVER then
PlaySoundFile(LAUGH_FILES[math.random(#LAUGH_FILES)], "SFX")
else
PlaySound(23330)
end
end
-- Focus (health) system
local MAX_FOCUS = 100
local focus = MAX_FOCUS
local focusFailed = false
local FOCUS_DRAIN = { miss = 17, redHerring = 22 }
local FOCUS_RECOVER = { perfect = 6, great = 4, good = 2 }
local FOCUS_DIFF_SCALE = { Easy = 0.6, Medium = 1.0, Hard = 1.2, Extreme = 1.5 }
local lastBooTime = 0
local savedAmbienceVol, savedMusicVol
local isPlayingGameMusic = false
local DIFFICULTY_MUSIC = {
Easy = 53474, -- Silvermoon city walk (relaxed, warm)
Medium = 55957, -- Grizzly Hills (upbeat, pleasant)
Hard = 53199, -- Ulduar Algalon (intense, epic)
Extreme = 53569, -- L70ETC concert (intense)
}
local DIFFICULTY_PRESETS = {
Easy = { fallSpeed = 96, fallDistance = 350, maxActiveNotes = 1, spawnInterval = 2.1,
timingPerfect = 0.06, timingGreat = 0.20, timingGood = 0.40,
redHerringChance = 0, randomAngles = false, doublesChance = 0 },
Medium = { fallSpeed = 180, fallDistance = 300, maxActiveNotes = 3, spawnInterval = 1.25,
timingPerfect = 0.04, timingGreat = 0.12, timingGood = 0.22,
redHerringChance = 0, randomAngles = false, doublesChance = 0 },
Hard = { fallSpeed = 240, fallDistance = 280, maxActiveNotes = 4, spawnInterval = 1.0,
timingPerfect = 0.03, timingGreat = 0.09, timingGood = 0.18,
redHerringChance = 0, randomAngles = false, doublesChance = 0 },
Extreme = { fallSpeed = 240, fallDistance = 260, maxActiveNotes = 5, spawnInterval = 0.75,
timingPerfect = 0.025, timingGreat = 0.07, timingGood = 0.15,
redHerringChance = 0, randomAngles = false, doublesChance = 0 },
}
-- Note spacing is paced to each song's real tempo: spawn interval = one beat times
-- this many beats-per-note, so a faster track plays faster and lower difficulties
-- leave more beats between notes. The presets' fixed spawnInterval is only a
-- fallback for a song with no known BPM.
local BEATS_PER_NOTE = { Easy = 3, Medium = 2, Hard = 1.4, Extreme = 1 }
-- Real audio charts (ns.SongCharts, read through SongData.ChartNotes): each note is a
-- time, a register 1-5 and a level 1-4, one per 16th slot so the stream is monophonic (never two binds at once). Difficulty
-- keeps notes up to its level; the active bind pool grows with difficulty so lower
-- levels stay hittable. Rapid consecutive notes are kept to modifier-compatible
-- binds so a fast run never demands releasing one modifier to press another.
local ACTIVE_BINDS = { Easy = 5, Medium = 9, Hard = 14, Extreme = 99 }
-- How many times the active bind-set sweeps the whole layout over one song. The set
-- (size ACTIVE_BINDS) stays a coordinated group moment-to-moment but drifts across
-- every bind this many times, so no bind is ever left out of a track.
local BIND_COVERAGE = 2
-- Target notes per second per difficulty. The level-1 pulse is always kept; higher
-- tiers layer on up to this, so density ramps smoothly instead of jumping at Medium.
local TARGET_DENSITY = { Easy = 1.0, Medium = 1.6, Hard = 2.2, Extreme = 2.8 }
local RAPID_GAP = 0.22
-- Extra screen-pixel lift of the shared note start line above the topmost bar, so
-- notes (and the health bar sitting on the line) start higher for more reaction time.
local START_LINE_LIFT = 180
-- Room kept above the start line for the health bar that sits on it (UI units:
-- its 6 px lift, 34 px height and a margin), so the bar never leaves the screen.
local LINE_TOP_ROOM = 56
local function bindMods(keybind)
local m = ""
if keybind:find("SHIFT-", 1, true) then m = m .. "S" end
if keybind:find("CTRL-", 1, true) then m = m .. "C" end
if keybind:find("ALT-", 1, true) then m = m .. "A" end
return m
end
local function modCompatible(a, b) return a == "" or b == "" or a == b end
local function byEase(a, b)
if #a.mods ~= #b.mods then return #a.mods < #b.mods end
return a.slot < b.slot
end
local MODIFIER_KEYS = {
LSHIFT = true, RSHIFT = true,
LCTRL = true, RCTRL = true,
LALT = true, RALT = true,
}
-- All action bar binding prefixes to neutralize during gameplay
local ALL_BAR_PREFIXES = {
"ACTIONBUTTON",
"MULTIACTIONBAR1BUTTON",
"MULTIACTIONBAR2BUTTON",
"MULTIACTIONBAR3BUTTON",
"MULTIACTIONBAR4BUTTON",
"MULTIACTIONBAR5BUTTON",
"MULTIACTIONBAR6BUTTON",
"MULTIACTIONBAR7BUTTON",
}
local gameFrame
local inputFrame
function Game:Initialize()
gameFrame = CreateFrame("Frame", "BoundToLearnGameFrame", UIParent)
gameFrame:Hide()
gameFrame:SetScript("OnUpdate", function(_, elapsed)
self:OnUpdate(elapsed)
end)
inputFrame = CreateFrame("Frame", "BoundToLearnGameInput", UIParent)
inputFrame:SetFrameStrata("FULLSCREEN_DIALOG")
inputFrame:SetAllPoints()
inputFrame:EnableKeyboard(true)
inputFrame:Hide()
inputFrame:SetScript("OnKeyDown", function(_, key)
if MODIFIER_KEYS[key] then
inputFrame:SetPropagateKeyboardInput(true)
return
end
if key == "ESCAPE" then
inputFrame:SetPropagateKeyboardInput(false)
self:Stop()
return
end
local fullKey = ""
if IsAltKeyDown() then fullKey = fullKey .. "ALT-" end
if IsControlKeyDown() then fullKey = fullKey .. "CTRL-" end
if IsShiftKeyDown() then fullKey = fullKey .. "SHIFT-" end
fullKey = fullKey .. key
local slotInfo = keybindToSlot[fullKey]
if slotInfo then
inputFrame:SetPropagateKeyboardInput(false)
self:OnKeybindInput(slotInfo.slot)
else
-- Swallow every other key while the game is running so stray binds
-- (game menu, bags, character pane, spellbook, map, etc.) can't pop a
-- window mid-song. ESC still stops the game; modifiers still pass, and
-- the input frame is hidden on pause/stop so normal keys return then.
inputFrame:SetPropagateKeyboardInput(false)
end
end)
ns.eventFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
ns.eventFrame:HookScript("OnEvent", function(_, event)
if event == "PLAYER_REGEN_DISABLED" and isRunning then
if currentMode == "practice" then
self:Pause() -- Practice is lenient: combat just pauses.
else
-- Scored runs cannot be paused; entering combat ends the run.
BoundToLearn:Print("Entered combat. Run ended.")
self:Stop()
end
end
end)
end
-- A mouse-bound note is pressed through Utils.CatchMouseBinds, not OnKeyDown.
local function OnMouseBind(key)
if not isRunning or isPaused then return end
local slotInfo = keybindToSlot[key]
if slotInfo then Game:OnKeybindInput(slotInfo.slot) end
end
function Game:BlockActionBars()
-- Keyboard binds go to a nonexistent action so they do nothing; mouse
-- binds go to our catch, which scores them.
local mouseKeys = {}
for _, prefix in ipairs(ALL_BAR_PREFIXES) do
for i = 1, 12 do
local key1, key2 = GetBindingKey(prefix .. i)
for _, key in ipairs({ key1, key2 }) do
if Utils.IsMouseBind(key) then
mouseKeys[#mouseKeys + 1] = key
else
SetOverrideBinding(inputFrame, true, key, "BTLNOOP")
end
end
end
end
Utils.CatchMouseBinds(mouseKeys, OnMouseBind)
-- Block ping keybind
local pingKey1, pingKey2 = GetBindingKey("PING")
if pingKey1 then SetOverrideBinding(inputFrame, true, pingKey1, "BTLNOOP") end
if pingKey2 then SetOverrideBinding(inputFrame, true, pingKey2, "BTLNOOP") end
end
function Game:UnblockActionBars()
ClearOverrideBindings(inputFrame)
Utils.ReleaseMouseBinds()
end
function Game:GetSettings()
local db = BoundToLearn.db.game
local difficulty = db.difficulty
local settings
if difficulty ~= "Custom" and DIFFICULTY_PRESETS[difficulty] then
-- Copy so we don't mutate the preset
local preset = DIFFICULTY_PRESETS[difficulty]
settings = {
fallSpeed = preset.fallSpeed,
fallDistance = preset.fallDistance,
maxActiveNotes = preset.maxActiveNotes,
spawnInterval = preset.spawnInterval,
timingPerfect = preset.timingPerfect,
timingGreat = preset.timingGreat,
timingGood = preset.timingGood,
redHerringChance = preset.redHerringChance,
randomAngles = preset.randomAngles,
}
else
settings = {
fallSpeed = db.fallSpeed,
fallDistance = db.fallDistance,
maxActiveNotes = db.maxActiveNotes,
spawnInterval = db.spawnInterval,
timingPerfect = db.timingPerfect,
timingGreat = db.timingGreat,
timingGood = db.timingGood,
}
end
-- Pace note spacing to the song's real tempo so it feels tied to the music.
-- Lanes stay random across every bind (see SpawnNote). Custom keeps its slider.
if difficulty ~= "Custom" then
local bpm = ns.SongData.BPM(ns.SongData.Get(db.songKey))
if bpm and bpm > 0 then
settings.spawnInterval = mmax(0.34, mmin(2.6, (60 / bpm) * (BEATS_PER_NOTE[difficulty] or 1)))
end
end
-- Competitive has 15 lanes; scale note cap to keep similar density
if currentMode == "competitive" then
settings.maxActiveNotes = settings.maxActiveNotes * 3
end
return settings
end
function Game:GetMode()
return currentMode
end
function Game:GetTimeRemaining()
if gameDuration == 0 then return nil end
local remaining = gameDuration - mmax(0, gameElapsed)
return mmax(0, remaining)
end
function Game:DiscoverSlots()
wipe(availableSlots)
wipe(keybindToSlot)
local bars = BoundToLearn.db.game.bars
local barMappings = {
{ key = "main", bindPrefix = "ACTIONBUTTON", btnPrefix = "ActionButton", startSlot = 1 },
{ key = "bottomLeft", bindPrefix = "MULTIACTIONBAR1BUTTON", btnPrefix = "MultiBarBottomLeftButton", startSlot = 61 },
{ key = "bottomRight", bindPrefix = "MULTIACTIONBAR2BUTTON", btnPrefix = "MultiBarBottomRightButton", startSlot = 49 },
{ key = "right", bindPrefix = "MULTIACTIONBAR3BUTTON", btnPrefix = "MultiBarRightButton", startSlot = 25 },
{ key = "left", bindPrefix = "MULTIACTIONBAR4BUTTON", btnPrefix = "MultiBarLeftButton", startSlot = 37 },
{ key = "bar6", bindPrefix = "MULTIACTIONBAR5BUTTON", btnPrefix = "MultiBar5Button", startSlot = 145 },
{ key = "bar7", bindPrefix = "MULTIACTIONBAR6BUTTON", btnPrefix = "MultiBar6Button", startSlot = 157 },
{ key = "bar8", bindPrefix = "MULTIACTIONBAR7BUTTON", btnPrefix = "MultiBar7Button", startSlot = 169 },
}
local seenTextures = {}
wipe(barExtents)
for _, bar in ipairs(barMappings) do
if bars[bar.key] then
for i = 1, 12 do
local slot = bar.startSlot + (i - 1)
local btn = _G[bar.btnPrefix .. i]
if btn and btn:IsShown() then
-- The whole bar counts, bound or not: the HUD spans it.
local left = btn:GetLeft()
if left then
local scale = btn:GetEffectiveScale()
local e = barExtents[bar.key]
if not e then
e = { l = math.huge, r = -math.huge, b = math.huge, t = -math.huge }
barExtents[bar.key] = e
end
e.l, e.r = mmin(e.l, left * scale), mmax(e.r, btn:GetRight() * scale)
e.b, e.t = mmin(e.b, btn:GetBottom() * scale), mmax(e.t, btn:GetTop() * scale)
end
-- Read the button's CURRENT action, not the raw page slot.
-- Druid forms (and stance/bonus bars) remap the main bar,
-- so GetActionTexture(slot) returns a hidden other-form
-- icon. btn.action is what the player actually sees now.
local action = btn.action or slot
if HasAction(action) then
local keybind, keybind2 = GetBindingKey(bar.bindPrefix .. i)
if keybind then
local texture = GetActionTexture(action)
-- Skip duplicate textures (same ability on 2 bars)
if texture and not seenTextures[texture] then
seenTextures[texture] = true
local slotInfo = {
slot = slot,
keybind = keybind,
mods = bindMods(keybind),
texture = texture,
button = btn,
}
tinsert(availableSlots, slotInfo)
keybindToSlot[keybind] = slotInfo
-- Either bind of the button hits its notes.
if keybind2 then keybindToSlot[keybind2] = slotInfo end
end
end
end
end
end
end
end
end
function Game:DiscoverCompetitiveSlots()
wipe(availableSlots)
wipe(keybindToSlot)
wipe(destroyedLanes)
local CD = ns.CompetitiveData
if not CD then return end
local compBtns = ns.GameUI and ns.GameUI:GetCompBarButtons() or {}
for i, slotDef in ipairs(CD.slots) do
local btn = compBtns[i]
if btn then
local rowDef = CD.rows[slotDef.row]
local keybind = rowDef.modifier .. tostring(slotDef.col)
local slotInfo = {
slot = i,
keybind = keybind,
mods = bindMods(keybind),
texture = slotDef.texture,
button = btn,
competitive = true,
laneIndex = i,
}
tinsert(availableSlots, slotInfo)
keybindToSlot[keybind] = slotInfo
end
end
end
local gameMusicTarget
local function MuteGameAudio()
savedAmbienceVol = tonumber(GetCVar("Sound_AmbienceVolume")) or 0.5
SetCVar("Sound_AmbienceVolume", 0)
-- Silence the music channel too: the round's track starts on it unheard during
-- the countdown (StartGameMusicMuted). Persisted so a crash before GO still
-- restores it on next load.
savedMusicVol = tonumber(GetCVar("Sound_MusicVolume")) or 0.4
BoundToLearn.db.pendingMusicRestore = savedMusicVol
SetCVar("Sound_MusicVolume", 0)
end
-- Start the round's track on the muted channel, so its lead-in plays unheard during
-- the countdown (the client cannot seek into a track). The target volume is
-- persisted so a crash before GO still restores it on next load (Core clears
-- pendingMusicRestore once applied).
local function StartGameMusicMuted(track)
local target = savedMusicVol or tonumber(GetCVar("Sound_MusicVolume")) or 0.4
if target < 0.05 then target = 0.4 end
gameMusicTarget = target
BoundToLearn.db.pendingMusicRestore = target
SetCVar("Sound_MusicVolume", 0)
PlayMusic(track)
isPlayingGameMusic = true
end
-- GO: the track is past its lead-in and comes in at full volume at once.
local function UnmuteGameMusic()
if isPlayingGameMusic and gameMusicTarget then
SetCVar("Sound_MusicVolume", gameMusicTarget)
end
end
local function RestoreGameAudio()
if savedAmbienceVol then SetCVar("Sound_AmbienceVolume", savedAmbienceVol) end
savedAmbienceVol = nil
if isPlayingGameMusic then
isPlayingGameMusic = false
-- Do not stop the track: the round-over screen keeps it playing. Just
-- make sure the volume is back at the player's level and clear the guard.
SetCVar("Sound_MusicVolume", savedMusicVol or gameMusicTarget or 0.4)
elseif savedMusicVol then
-- Cancelled before the music started (e.g. during the countdown); un-mute.
SetCVar("Sound_MusicVolume", savedMusicVol)
end
BoundToLearn.db.pendingMusicRestore = nil
savedMusicVol = nil
end
local function ResetGameState()
isRunning = true
isPaused = false
score = 0
combo = 0
maxCombo = 0
multiplier = 1
wipe(hitCounts)
hitCounts.perfect = 0
hitCounts.great = 0
hitCounts.good = 0
hitCounts.miss = 0
hitCounts.redHerring = 0
wipe(activeNotes)
wipe(destroyedLanes)
spawnAccumulator = 999 -- trigger immediate first spawn
gameStartTime = GetTime()
gameElapsed = 0
pauseStartTime = 0
focus = MAX_FOCUS
focusFailed = false
lastBooTime = 0
mirrorFlipped = false
nextMirrorFlip = 0
gameModifiers = ns.Modifiers and ns.Modifiers:GetActive() or {}
end
function Game:Start()
if isRunning then return end
if InCombatLockdown() then
BoundToLearn:Print("Cannot start game during combat.")
return
end
-- Skyriding/dragonriding swaps the main action bar for the mount ability bar
-- (a bonus bar), which breaks keybind discovery. A grounded normal mount
-- leaves the bonus bar at 0, so only skyriding is blocked.
if IsMounted() and (GetBonusBarOffset and GetBonusBarOffset() or 0) > 0 then
BoundToLearn:Print("Dismount first. Skyriding swaps your action bars, which breaks keybind tracking.")
return
end
local db = BoundToLearn.db.game
currentMode = db.mode or "timed"
self:SeedChart(db.songKey, db.difficulty)
if currentMode == "competitive" then
return self:StartCompetitive()
end
self:DiscoverSlots()
if #availableSlots == 0 then
BoundToLearn:Print("No keybinds found on your action bars. Bind some keys first.")
return
end
gameDuration = (currentMode == "practice") and 0 or ns.SongData.PlayLength(ns.SongData.Get(db.songKey))
ResetGameState()
self:BuildChart(db.songKey, db.difficulty)
self:SetScoreBudget()
self:BlockActionBars()
if BoundToLearn.db.game.soundEnabled then
MuteGameAudio()
end
if ns.GameUI then
ns.GameUI:OnGameStart(availableSlots)
self:PlaceNoteLine() -- put the start line + health bar in place before the countdown
end
self:CountIn(db.songKey, db.difficulty)
-- Game started silently; UI shows everything needed
end
-- Many tracks open on a quiet lead-in (Fire Festival: 4 s, 15 dB under the rest).
-- The track starts muted during the countdown, timed so its lead-in (measured per
-- track, SongData.LeadIn) is over by GO, and comes in at full volume on GO. A lead-in
-- over 3 s runs the countdown longer, up to MAX_COUNTDOWN; past that, GO lands
-- MAX_COUNTDOWN into the track. The first falling note also starts on GO (PrepChart
-- picks and times it from goOffset, the track's position at GO), so nothing falls
-- during the countdown and nothing pops in partway down.
local MAX_COUNTDOWN = 5
local roundToken = 0
function Game:CountIn(songKey, difficulty)
roundToken = roundToken + 1
local token = roundToken
local function Live() return isRunning and token == roundToken end
self.goOffset = 0
if not ns.GameUI then
gameStartTime = GetTime()
gameFrame:Show()
inputFrame:Show()
return
end
local track
if BoundToLearn.db.game.soundEnabled then
local song = ns.SongData and ns.SongData.Get(songKey)
track = (song and song.id) or DIFFICULTY_MUSIC[difficulty]
end
local leadIn = track and mmin(ns.SongData.LeadIn(songKey), MAX_COUNTDOWN) or 0
local countdown = mmax(3, mmin(MAX_COUNTDOWN, math.ceil(leadIn)))
local musicAt
local function StartMusic()
if musicAt or not track then return end
StartGameMusicMuted(track)
musicAt = GetTime()
end
if leadIn > 0 then
C_Timer.After(countdown - leadIn, function()
if Live() then StartMusic() end
end)
end
ns.GameUI:ShowCountdown(countdown, function()
if not Live() then return end
StartMusic() -- a track with no lead-in starts here, on GO
local now = GetTime()
self.goOffset = musicAt and (now - musicAt) or 0
gameStartTime = now - self.goOffset
UnmuteGameMusic()
gameFrame:Show()
inputFrame:Show()
end)
end
function Game:StartCompetitive()
if isRunning then return end
if InCombatLockdown() then
BoundToLearn:Print("Cannot start game during combat.")
return
end
local db = BoundToLearn.db.game
currentMode = "competitive"
gameDuration = ns.SongData.PlayLength(ns.SongData.Get(db.songKey))
if ns.GameUI then
ns.GameUI:CreateCompBar()
end
self:DiscoverCompetitiveSlots()
if #availableSlots == 0 then
BoundToLearn:Print("No competitive slots available. Check your keybinds.")
if ns.GameUI then ns.GameUI:HideCompBar() end
return
end
ResetGameState()
self:SetScoreBudget()
self:BlockActionBars()
if BoundToLearn.db.game.soundEnabled then
MuteGameAudio()
end
if ns.GameUI then
ns.GameUI:OnGameStart(availableSlots)
self:PlaceNoteLine() -- put the start line + health bar in place before the countdown
end
self:CountIn(db.songKey, db.difficulty)
end
function Game:Stop()
if not isRunning then return end
isRunning = false
isPaused = false
gameFrame:Hide()
inputFrame:Hide()
self:UnblockActionBars()
RestoreGameAudio()
if ns.GameUI then
ns.GameUI:CancelCountdown()
if mirrorFlipped then
mirrorFlipped = false
ns.GameUI:SetMirrorFlipped(false)
end
end
for i = #activeNotes, 1, -1 do
local note = activeNotes[i]
if note.bombSoundHandle then
StopSound(note.bombSoundHandle, 0)
note.bombSoundHandle = nil
end
if ns.GameUI then ns.GameUI:ReleaseNote(note) end
end
wipe(activeNotes)
local duration = mmax(0, gameElapsed)
if duration == 0 then duration = mmax(0, GetTime() - gameStartTime) end
local totalNotes = hitCounts.perfect + hitCounts.great + hitCounts.good + hitCounts.miss
local difficulty = BoundToLearn.db.game.difficulty
if ns.Stats and totalNotes > 0 and currentMode ~= "practice" then
ns.Stats:RecordGameSession({
score = score,
maxCombo = maxCombo,
hitCounts = hitCounts,
duration = duration,
mode = currentMode,
difficulty = difficulty,
})
end
if ns.GameUI and totalNotes > 0 and currentMode ~= "practice" then
local songAcc = ns.Utils.HitAccuracy(hitCounts)
ns.GameUI:RecordSongScore(score, songAcc, maxCombo)
local key = BoundToLearn.db.game.songKey
local song = ns.SongData and ns.SongData.Get(key)
local songLen = song and ns.SongData.PlayLength(song) or 0
if songLen > 0 then
ns.GameUI:RecordSongProgress(key, mmin(1, duration / songLen))
end
end
if ns.GameUI then
ns.GameUI:OnGameEnd({
score = score,
maxCombo = maxCombo,
hitCounts = hitCounts,
duration = duration,
totalNotes = totalNotes,
mode = currentMode,
difficulty = difficulty,
focusFailed = focusFailed,
chartTotal = self.chartNotes and #self.chartNotes or 0,
notesShown = self.chartNotes and mmin(self.chartCursor - 1, #self.chartNotes) or 0,
})
if currentMode == "competitive" then
ns.GameUI:HideCompBar()
end
end
-- Broadcast to leaderboard
if ns.Leaderboard and totalNotes > 0 then
local results = {
score = score,
maxCombo = maxCombo,
hitCounts = hitCounts,
duration = duration,
totalNotes = totalNotes,
mode = currentMode,
difficulty = difficulty,
}
ns.Leaderboard:AddOwnScore(results)
ns.Leaderboard:OnGameEnd(results)
end
-- Check achievements (non-practice only)
if ns.Achievements and totalNotes > 0 and currentMode ~= "practice" then
local newUnlocks = ns.Achievements:CheckRoundAchievements({
score = score,
maxCombo = maxCombo,
hitCounts = hitCounts,
difficulty = difficulty,
modifiers = gameModifiers,
mode = currentMode,
})
if #newUnlocks > 0 and ns.GameUI then
ns.GameUI:ShowAchievementUnlocks(newUnlocks)
end
end
-- Game over silently; summary UI shows results
end
function Game:Pause()
if currentMode == "competitive" then
-- Competitive: pausing zeroes your score
score = 0
combo = 0
multiplier = 1
-- Score reset handled silently; UI updates
if ns.GameUI then
ns.GameUI:UpdateScoreDisplay(score, combo, multiplier)
end
end
isPaused = true
pauseStartTime = GetTime()
gameFrame:Hide()
inputFrame:Hide()
-- Combat pauses practice: the abilities must work in that fight.
self:UnblockActionBars()
if ns.GameUI then
ns.GameUI:CancelCountdown()
ns.GameUI:OnGamePause()
end
end
function Game:Resume()
if not isRunning then return end
if InCombatLockdown() then
BoundToLearn:Print("Cannot resume game during combat.")
return
end
isPaused = false
self:BlockActionBars()
local function DoResume()
local now = GetTime()
local pauseDuration = now - pauseStartTime
-- Shift all active note timings forward by the pause duration
for _, note in ipairs(activeNotes) do
if not note.evaluated then
note.spawnTime = note.spawnTime + pauseDuration
note.targetTime = note.targetTime + pauseDuration
end
end
gameStartTime = now - gameElapsed
UnmuteGameMusic() -- a pause during the countdown left the track muted
gameFrame:Show()
inputFrame:Show()
end
if ns.GameUI then
ns.GameUI:OnGameResume()
ns.GameUI:ShowCountdown(3, DoResume)
else
DoResume()
end
end
function Game:IsPaused()
return isPaused
end
function Game:IsRunning()
return isRunning
end
function Game:GetFocus()
return focus, MAX_FOCUS
end
function Game:DidFocusFail()
return focusFailed
end
function Game:OnFocusDepleted()
if not isRunning or focusFailed then return end
focusFailed = true
if BoundToLearn.db.game.soundEnabled then
PlaySound(847) -- igQuestLogAbandonQuest (focus depleted)
end
self:Stop()
end
function Game:OnUpdate(elapsed)
if not isRunning or isPaused then return end
local now = GetTime()
gameElapsed = now - gameStartTime
-- Check timer (timed and competitive modes)
if gameDuration > 0 and gameElapsed >= gameDuration then
self:Stop()
return
end
local settings = self:GetSettings()
-- Update timer display
if gameDuration > 0 and ns.GameUI then
ns.GameUI:UpdateTimer(gameDuration - mmax(0, gameElapsed))
end
-- Restore destroyed lanes
if currentMode == "competitive" then
for laneIdx, expireTime in pairs(destroyedLanes) do
if now >= expireTime then
destroyedLanes[laneIdx] = nil
if ns.GameUI then ns.GameUI:RestoreLane(laneIdx) end
end
end
end
-- Mirror modifier: flip lane positions periodically
local activeMods = ns.Modifiers and ns.Modifiers:GetActive() or {}
if activeMods.mirror and now >= nextMirrorFlip then
mirrorFlipped = not mirrorFlipped
nextMirrorFlip = now + 8 + math.random() * 6 -- flip every 8-14 seconds
if ns.GameUI then ns.GameUI:SetMirrorFlipped(mirrorFlipped) end
end
if self.chartNotes then
-- Chart-driven: every note falls from one shared start line at a constant
-- speed, so notes bound for lower bars have farther to fall and take longer.
-- Per-note fall times (and the sort into spawn order) are set up once the
-- buttons have laid out, in PrepChart. Each note still reaches its button at
-- gameStartTime + cn.t (on the beat).
if not self.chartPrepped then self.chartPrepped = self:PrepChart(settings) end
if self.chartPrepped then
local notes = self.chartNotes
while self.chartCursor <= #notes do
local cn = notes[self.chartCursor]
if gameElapsed < cn.spawnT then break end
self:SpawnNote(now, settings, cn.slotInfo, gameStartTime + cn.t, cn.fallTime)
self.chartCursor = self.chartCursor + 1
end
end
else
spawnAccumulator = spawnAccumulator + elapsed
if spawnAccumulator >= settings.spawnInterval then
spawnAccumulator = spawnAccumulator % settings.spawnInterval
self:SpawnNote(now, settings)
-- Doubles: modifier only, not available in competitive (modifier keys conflict)
if currentMode ~= "competitive" and activeMods.doubles and math.random() < 0.20 then
self:SpawnNote(now, settings)
end
end
end
-- Bombs detonate at ~20% overlap (80% of full distance between centers)
local bombDetonateThreshold = 48 * 0.8 / settings.fallSpeed
for i = #activeNotes, 1, -1 do
local note = activeNotes[i]
if not note then break end
if not note.evaluated then
local timeToTarget = note.targetTime - now
local missThreshold = (note.isBomb and bombDetonateThreshold) or -settings.timingGood
if timeToTarget < missThreshold then
if note.isRedHerring then
note.evaluated = true
note.evaluatedAt = now
note.result = "avoided"
else
self:EvaluateNote(note, "miss")
if not isRunning then return end
end
end
end
-- Only keep updating position for unevaluated notes and misses (fall through)
if note.noteFrame and (not note.evaluated or note.result == "miss" or note.result == "avoided") then
local fallTime = note.fallTime or (settings.fallDistance / settings.fallSpeed)
local timeToTarget = note.targetTime - now
local progress = 1.0 - (timeToTarget / fallTime)
progress = mmax(progress, 0)
if ns.GameUI then
ns.GameUI:UpdateNotePosition(note, progress)
end
end
if note.evaluated and (now - note.evaluatedAt) > 0.6 then
if ns.GameUI then ns.GameUI:ReleaseNote(note) end
tremove(activeNotes, i)
end
end
end
-- Load the baked onset chart for this track+difficulty into self.chartNotes. The
-- level-1 pulse is always kept (steady backbone, no dead spots); higher tiers (weak
-- beats, eighths, sixteenths) layer on in priority order up to the difficulty's
-- notes-per-second target, evenly subsampling the tier that crosses it so density
-- ramps smoothly. Returns true, or leaves chartNotes nil (false) when no chart
-- exists so OnUpdate falls back to the procedural spawner.
local buildBuckets = { {}, {}, {}, {} }
function Game:BuildChart(key, diff)
self.chartNotes = nil
self.chartCursor = 1
self.chartPrepped = nil
local chart = ns.SongCharts and key and ns.SongCharts[key]
if not (chart and chart.notes and #chart.notes > 0) then return false end
if #availableSlots == 0 then return false end
local cutoff = gameDuration > 0 and gameDuration or 1e9
for lvl = 1, 4 do wipe(buildBuckets[lvl]) end
local lastT = 0
for ms, _, lvl in ns.SongData.ChartNotes(chart) do
local t = tonumber(ms) / 1000
if t <= cutoff then
local bucket = buildBuckets[tonumber(lvl)]
bucket[#bucket + 1] = t
if t > lastT then lastT = t end
end
end
local roundLen = (gameDuration > 0 and gameDuration) or lastT
if roundLen <= 0 then return false end
local target = (TARGET_DENSITY[diff] or 2.0) * roundLen
-- The pulse always plays; layer higher tiers on up to the target.
local chosen = {}
local pulse = buildBuckets[1]
for j = 1, #pulse do chosen[#chosen + 1] = pulse[j] end
for lvl = 2, 4 do
local bucket = buildBuckets[lvl]
local n = #bucket
local room = target - #chosen
if n > 0 and room > 0 then
if n <= room then
for j = 1, n do chosen[#chosen + 1] = bucket[j] end
else
local keep = mfloor(room)
if keep > 0 then
local stride = n / keep
for j = 1, keep do
chosen[#chosen + 1] = bucket[mmin(n, mfloor((j - 0.5) * stride) + 1)]
end
end
break
end
end
end
if #chosen == 0 then return false end
tsort(chosen)
local notes = {}
for i = 1, #chosen do notes[i] = { t = chosen[i] } end
self:AssignChartBinds(notes, diff)
self.chartNotes = notes
self.chartCursor = 1
return true
end
-- Set up the shared-start-line fall. Every note falls from one screen line (the
-- topmost bar's button + the configured drop) at a constant speed, so a note bound for
-- a lower bar has farther to go and takes proportionally longer. Computes each note's
-- fall time and the moment it must appear at the line, sorts them into that appear
-- order (a later beat on a far bar can appear before an earlier beat on a near one),
-- and hands the line to the UI. Runs once live button positions exist; false = retry.
local function bySpawnT(a, b) return a.spawnT < b.spawnT end
-- Screen-pixel Y of the shared start line: topmost bar's button + the drop + the lift.
-- nil if the buttons have not laid out yet.
function Game:ComputeNoteLine(settings)
local topY
for i = 1, #availableSlots do
local btn = availableSlots[i].button
if btn then