Repository navigation
Expand file tree
/
Copy pathCore.lua
More file actions
executable file
·775 lines (651 loc) · 26.7 KB
/
Copy pathCore.lua
File metadata and controls
executable file
·775 lines (651 loc) · 26.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
--[[
CeeLo Dice Addon
A duel-like Cee-lo dice game for World of Warcraft
Core module: Addon initialization, event handling, and state management
]]
local addonName, ns = ...
-- ============================================================================
-- Addon Namespace Setup
-- ============================================================================
CeeLo = ns
ns.version = "1.1.0"
ns.prefix = "CEELO"
-- Bump whenever the message format or dice derivation changes. Clients with a
-- different protocol would compute different dice, so they refuse to play.
ns.PROTOCOL_VERSION = 2
-- Both sides use the same invite timeout so neither can accept a challenge the
-- other has already given up on
ns.INVITE_TIMEOUT = 30
-- Game states
ns.STATE = {
IDLE = "idle",
PENDING_INVITE = "pending_invite", -- Waiting for response to our invite
INVITED = "invited", -- We received an invite
COUNTDOWN = "countdown", -- Both accepted, countdown in progress
COMMITTING = "committing", -- Exchanging commits
REVEALING = "revealing", -- Exchanging reveals
RESOLVED = "resolved", -- Game complete, showing results
}
-- Current game session. ResetSession replaces this table, so delayed callbacks
-- capture it and compare against ns.session to detect that their game ended.
local function NewSession()
return {
state = ns.STATE.IDLE,
opponent = nil,
opponentGUID = nil,
gameId = nil, -- Random id chosen by the challenger, sent with every message
isChallenger = false,
countdown = 3,
myCommit = nil,
mySeed = nil,
theirCommit = nil,
theirSeed = nil,
myDice = nil,
theirDice = nil,
result = nil, -- "win", "lose"
timeout = nil,
tiebreakerRound = 0, -- Track tiebreaker rounds (0 = first game)
pendingTiebreaker = false, -- Tied; waiting to start the next round
}
end
ns.session = NewSession()
-- Defaults for SavedVariables
local defaultGlobalDB = {
ruleVariant = "classic",
soundEnabled = true,
debugMode = false,
matchHistory = {},
maxHistorySize = 100,
}
local defaultCharDB = {
autoDecline = false,
wins = 0,
losses = 0,
groupWins = 0, -- Group tables are tracked separately from 1v1
groupGames = 0,
}
-- ============================================================================
-- Initialization
-- ============================================================================
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_LOGOUT")
eventFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
eventFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
eventFrame:RegisterEvent("CHAT_MSG_SYSTEM")
function ns:Initialize()
-- Initialize saved variables with defaults
if not CeeLoGlobalDB then
CeeLoGlobalDB = CopyTable(defaultGlobalDB)
else
-- Merge missing defaults
for k, v in pairs(defaultGlobalDB) do
if CeeLoGlobalDB[k] == nil then
CeeLoGlobalDB[k] = v
end
end
end
if not CeeLoCharDB then
CeeLoCharDB = CopyTable(defaultCharDB)
else
for k, v in pairs(defaultCharDB) do
if CeeLoCharDB[k] == nil then
CeeLoCharDB[k] = v
end
end
end
ns.db = CeeLoGlobalDB
ns.charDB = CeeLoCharDB
-- Register addon message prefix
C_ChatInfo.RegisterAddonMessagePrefix(ns.prefix)
-- Restore debug mode from saved settings
ns.Utils.debugMode = ns.db.debugMode or false
-- Initialize modules
if ns.Net then ns.Net:Initialize() end
if ns.UI then ns.UI:Initialize() end
if ns.Options then ns.Options:Initialize() end
-- Register slash commands
ns:RegisterSlashCommands()
print("|cff00ff00CeeLo Dice|r v" .. ns.version .. " loaded. Type |cff00ffff/ceelo|r for help.")
end
-- ============================================================================
-- Slash Commands
-- ============================================================================
function ns:RegisterSlashCommands()
SLASH_CEELO1 = "/ceelo"
SLASH_CEELO2 = "/cl"
SlashCmdList["CEELO"] = function(msg)
local cmd, arg = strsplit(" ", msg, 2)
cmd = strlower(cmd or "")
if cmd == "" then
-- No command given - challenge target if one exists
local target, hidden = ns.Utils.GetTargetPlayerName()
if target then
ns:Challenge(target)
elseif hidden then
print("|cffff6600CeeLo:|r Can't read your target's name right now. Use /ceelo challenge <name>")
else
ns:PrintHelp()
end
elseif cmd == "help" then
ns:PrintHelp()
elseif cmd == "challenge" or cmd == "c" then
if arg and arg ~= "" then
ns:Challenge(arg)
else
-- Challenge current target
local target, hidden = ns.Utils.GetTargetPlayerName()
if target then
ns:Challenge(target)
elseif hidden then
print("|cffff6600CeeLo:|r Can't read your target's name right now. Use /ceelo challenge <name>")
else
print("|cffff6600CeeLo:|r Target a player or use /ceelo challenge <name>")
end
end
elseif cmd == "accept" or cmd == "a" then
ns:AcceptChallenge()
elseif cmd == "decline" or cmd == "d" then
ns:DeclineChallenge()
elseif cmd == "cancel" then
-- A 1v1 game takes priority; otherwise close the table we're hosting
if ns.session.state == ns.STATE.IDLE and ns.Group:IsHosting() then
ns.Group:Cancel()
else
ns:CancelChallenge()
end
elseif cmd == "host" then
ns.Group:Host()
elseif cmd == "roll" or cmd == "r" then
ns.Group:RollDice()
elseif cmd == "table" then
if ns.GroupUI and ns.Group.table then
ns.GroupUI:Show(ns.Group.table)
else
print("|cffff6600CeeLo:|r No table is open. Start one with /ceelo host")
end
elseif cmd == "stats" then
ns:PrintStats()
elseif cmd == "rules" then
ns:PrintRules()
elseif cmd == "options" or cmd == "config" then
if ns.Options then
ns.Options:Show()
end
elseif cmd == "history" then
ns:PrintHistory()
else
print("|cffff6600CeeLo:|r Unknown command. Type /ceelo help")
end
end
end
function ns:PrintHelp()
print("|cff00ff00=== CeeLo Dice Commands ===|r")
print("|cff00ffff/ceelo|r - Challenge your current target")
print("|cff00ffff/ceelo challenge <name>|r - Challenge a player by name")
print("|cff00ffff/ceelo accept|r - Accept a challenge")
print("|cff00ffff/ceelo decline|r - Decline a challenge")
print("|cff00ffff/ceelo cancel|r - Cancel your pending challenge (or close the table you're hosting)")
print("|cff00ffff/ceelo host|r - Open a table for your party or raid (2+ players)")
print("|cff00ffff/ceelo roll|r - Roll your dice at an open table")
print("|cff00ffff/ceelo table|r - Show the table window again")
print("|cff00ffff/ceelo stats|r - Show your win/loss record")
print("|cff00ffff/ceelo rules|r - Show Cee-lo rules")
print("|cff00ffff/ceelo options|r - Open settings")
print("|cff00ffff/ceelo history|r - Show recent matches")
end
function ns:PrintStats()
local w, l = ns.charDB.wins, ns.charDB.losses
local total = w + l
local winRate = total > 0 and math.floor((w / total) * 100) or 0
print("|cff00ff00=== CeeLo Stats ===|r")
print(string.format("1v1 - Wins: |cff00ff00%d|r | Losses: |cffff0000%d|r", w, l))
print(string.format("1v1 - Total games: %d | Win rate: %d%%", total, winRate))
print(string.format("Tables - Wins: |cff00ff00%d|r | Games: %d",
ns.charDB.groupWins, ns.charDB.groupGames))
end
function ns:PrintRules()
print("|cff00ff00=== Cee-lo Rules ===|r")
print("Roll 3 dice. Best hand wins!")
print("|cff00ff004-5-6|r = Automatic WIN")
print("|cffff00001-2-3|r = Automatic LOSS")
print("|cff00ffffTriples|r (6-6-6 best, 1-1-1 worst)")
print("|cffffff00Pair + Point|r = Single die is your 'point' (higher wins)")
print("No pair and no 4-5-6 or 1-2-3 = \"nothing\": roll again")
end
function ns:PrintHistory()
if not ns.db.matchHistory or #ns.db.matchHistory == 0 then
print("|cffff6600CeeLo:|r No match history yet.")
return
end
print("|cff00ff00=== Recent CeeLo Matches ===|r")
local count = math.min(10, #ns.db.matchHistory)
for i = 1, count do
local m = ns.db.matchHistory[i]
local resultColor = m.result == "win" and "|cff00ff00" or (m.result == "lose" and "|cffff0000" or "|cffffff00")
if m.forfeit then
print(string.format("%s%s|r vs %s - %s (forfeit)",
resultColor, m.result:upper(), m.opponent, m.date))
elseif m.mode == "group" then
local winnerText = ""
if m.result ~= "win" and m.winnerName then
winnerText = string.format(" - won by %s%s", m.winnerName,
m.theirDice and " [" .. table.concat(m.theirDice, "-") .. "]" or "")
end
print(string.format("%s%s|r at %s - %s [%s]%s",
resultColor, m.result:upper(), m.opponent, m.date,
table.concat(m.myDice or {}, "-"), winnerText))
else
print(string.format("%s%s|r vs %s - %s [%s] vs [%s]",
resultColor, m.result:upper(), m.opponent, m.date,
table.concat(m.myDice or {}, "-"), table.concat(m.theirDice or {}, "-")))
end
end
end
-- ============================================================================
-- Game Flow
-- ============================================================================
function ns:Challenge(playerName)
if ns.session.state ~= ns.STATE.IDLE then
print("|cffff6600CeeLo:|r You're already in a game. Use /ceelo cancel first.")
return
end
if not playerName or playerName == "" then
print("|cffff6600CeeLo:|r Please specify a player name.")
return
end
-- Normalize name so replies (which arrive as "Name" or "Name-Realm") match
playerName = ns.Utils.NormalizeName(playerName)
-- A groupmate typed by first name only ("First" for "First Last" on WoW
-- Forever) can only be whispered by their full name
playerName = ns.Group:ResolveGroupMember(playerName) or playerName
if ns.Utils.NamesMatch(playerName, ns.Utils.MyName()) then
print("|cffff6600CeeLo:|r You can't challenge yourself!")
return
end
-- Check if in combat
if InCombatLockdown() then
print("|cffff6600CeeLo:|r Can't start a game while in combat.")
return
end
ns.session.state = ns.STATE.PENDING_INVITE
ns.session.opponent = playerName
ns.session.isChallenger = true
ns.session.gameId = string.format("%08x", math.random(0, 0x7fffffff))
-- Send invite via addon message
ns.Net:SendMessage("INVITE", { version = ns.version, proto = ns.PROTOCOL_VERSION }, playerName)
-- Broadcast challenge via emote
ns.Utils.SendEmote("challenges " .. playerName .. " to a game of Cee-lo!")
print(string.format("|cff00ff00CeeLo:|r Challenge sent to %s. Waiting for response...", playerName))
-- Set timeout, and tell the opponent so their popup closes too
ns:StartTimeout(ns.INVITE_TIMEOUT, function()
if ns.session.state == ns.STATE.PENDING_INVITE then
print("|cffff6600CeeLo:|r Challenge to " .. playerName .. " timed out.")
ns.Net:SendMessage("CANCEL", {}, ns.session.opponent)
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
end)
-- Show pending UI
if ns.UI then
ns.UI:ShowPendingChallenge(playerName)
end
end
function ns:AcceptChallenge()
if ns.session.state ~= ns.STATE.INVITED then
print("|cffff6600CeeLo:|r No pending challenge to accept.")
return
end
if InCombatLockdown() then
print("|cffff6600CeeLo:|r Can't accept while in combat.")
return
end
local opponent = ns.session.opponent
ns.session.state = ns.STATE.COUNTDOWN
ns.Net:SendMessage("ACCEPT", { proto = ns.PROTOCOL_VERSION }, opponent)
print(string.format("|cff00ff00CeeLo:|r Accepted challenge from %s!", opponent))
-- Start countdown
ns:StartCountdown()
end
function ns:DeclineChallenge()
if ns.session.state ~= ns.STATE.INVITED then
print("|cffff6600CeeLo:|r No pending challenge to decline.")
return
end
local opponent = ns.session.opponent
ns.Net:SendMessage("DECLINE", {}, opponent)
print("|cffff6600CeeLo:|r Declined challenge from " .. opponent)
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
function ns:CancelChallenge()
if ns.session.state == ns.STATE.IDLE then
print("|cffff6600CeeLo:|r No active game to cancel.")
return
end
local opponent = ns.session.opponent
if opponent then
ns.Net:SendMessage("CANCEL", {}, opponent)
end
print("|cffff6600CeeLo:|r Game cancelled.")
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
function ns:ResetSession()
ns:ClearTimeout()
ns.session = NewSession()
end
function ns:StartTiebreaker()
-- Keep the same opponent and isChallenger, but reset dice/commit/seed
ns.session.pendingTiebreaker = false
ns.session.tiebreakerRound = ns.session.tiebreakerRound + 1
ns.session.myCommit = nil
ns.session.mySeed = nil
ns.session.theirCommit = nil
ns.session.theirSeed = nil
ns.session.myDice = nil
ns.session.theirDice = nil
ns.session.result = nil
-- Notify player
local round = ns.session.tiebreakerRound
print(string.format("|cffffff00CeeLo:|r Tiebreaker round %d!", round))
ns.Utils.SendEmote(string.format("enters tiebreaker round %d against %s!", round, ns.session.opponent))
-- Go straight to countdown for tiebreaker
ns.session.state = ns.STATE.COUNTDOWN
ns:StartCountdown()
end
-- ============================================================================
-- Countdown and Game Phases
-- ============================================================================
function ns:StartCountdown()
ns.session.countdown = 3
if ns.UI then
ns.UI:ShowCountdown(3)
end
ns:DoCountdownTick()
end
function ns:DoCountdownTick()
local count = ns.session.countdown
if count > 0 then
ns.Utils.PlaySound("UI_BATTLEGROUND_COUNTDOWN_TIMER")
if ns.UI then
ns.UI:UpdateCountdown(count)
end
ns.session.countdown = count - 1
local session = ns.session
C_Timer.After(1, function()
if ns.session == session and session.state == ns.STATE.COUNTDOWN then
ns:DoCountdownTick()
end
end)
else
-- Countdown finished, start commit phase
ns:StartCommitPhase()
end
end
function ns:StartCommitPhase()
ns.session.state = ns.STATE.COMMITTING
-- Generate our seed and commit
local seed, commit = ns.CommitReveal:GenerateCommit()
ns.session.mySeed = seed
ns.session.myCommit = commit
ns.Utils.Debug("Sending commit to " .. (ns.session.opponent or "???"))
ns.Utils.Debug("My commit:", commit:sub(1, 16) .. "...")
-- Send our commit
ns.Net:SendMessage("COMMIT", { commit = commit, round = ns.session.tiebreakerRound }, ns.session.opponent)
if ns.UI then
ns.UI:ShowRolling()
end
-- Wait for their commit (with timeout)
ns:StartTimeout(10, function()
if ns.session.state == ns.STATE.COMMITTING then
print("|cffff6600CeeLo:|r Opponent didn't send commit. Game cancelled.")
ns.Utils.Debug("Their commit received: " .. tostring(ns.session.theirCommit ~= nil))
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
end)
end
function ns:OnReceivedCommit(commit)
ns.Utils.Debug("Received commit from opponent")
ns.Utils.Debug("Their commit:", commit:sub(1, 16) .. "...")
ns.session.theirCommit = commit
-- If we've also sent ours, move to reveal phase
if ns.session.myCommit then
ns.Utils.Debug("Both commits received, moving to reveal phase")
ns:StartRevealPhase()
else
ns.Utils.Debug("Waiting for our commit to be generated...")
end
end
function ns:StartRevealPhase()
ns.session.state = ns.STATE.REVEALING
ns:ClearTimeout()
ns.Utils.Debug("Sending reveal (seed) to " .. (ns.session.opponent or "???"))
-- Send our seed (reveal)
ns.Net:SendMessage("REVEAL", { seed = ns.session.mySeed, round = ns.session.tiebreakerRound }, ns.session.opponent)
-- Wait for their reveal. They have our seed by now and could work out the
-- result, so withholding theirs counts as a forfeit rather than a cancel.
ns:StartTimeout(10, function()
if ns.session.state == ns.STATE.REVEALING then
ns.Utils.Debug("Their seed received: " .. tostring(ns.session.theirSeed ~= nil))
ns:ResolveForfeit("didn't reveal their roll")
end
end)
end
function ns:OnReceivedReveal(seed)
ns.Utils.Debug("Received reveal from opponent")
-- Verify their seed matches their commit
local expectedCommit = ns.CommitReveal:Hash(seed)
if expectedCommit ~= ns.session.theirCommit then
ns.Utils.Debug("Expected: " .. tostring(ns.session.theirCommit and ns.session.theirCommit:sub(1, 16)))
ns.Utils.Debug("Got: " .. tostring(expectedCommit:sub(1, 16)))
ns:ResolveForfeit("revealed a roll that doesn't match their commit")
return
end
ns.Utils.Debug("Reveal verified successfully!")
ns.session.theirSeed = seed
-- If we've both revealed, resolve the game
if ns.session.mySeed and ns.session.theirSeed then
ns.Utils.Debug("Both reveals received, resolving game...")
ns:ResolveGame()
end
end
function ns:ResolveGame()
ns:ClearTimeout()
ns.session.state = ns.STATE.RESOLVED
-- Derive dice from combined seeds with roll broadcasting
local combinedSeed = ns.CommitReveal:CombineSeeds(ns.session.mySeed, ns.session.theirSeed)
-- Broadcast callback function for each roll attempt
local roundInfo = ns.session.tiebreakerRound > 0 and string.format(" (tiebreaker %d)", ns.session.tiebreakerRound) or ""
local function broadcastRoll(dice, isValid, attempt)
if isValid then
local hand = ns.Rules:EvaluateHand(dice)
ns.Utils.SendEmote(string.format("rolls [%s] (%s)%s in Cee-lo vs %s!",
table.concat(dice, "-"), ns.Rules:PlainName(hand), roundInfo, ns.session.opponent))
end
end
-- Determine who is "player 1" (challenger) for consistent dice assignment
local myDice, theirDice
if ns.session.isChallenger then
myDice = ns.CommitReveal:DeriveDiceWithCallback(combinedSeed, 1, broadcastRoll)
theirDice = ns.CommitReveal:DeriveDice(combinedSeed, 2) -- Don't broadcast opponent's rolls
else
theirDice = ns.CommitReveal:DeriveDice(combinedSeed, 1) -- Don't broadcast opponent's rolls
myDice = ns.CommitReveal:DeriveDiceWithCallback(combinedSeed, 2, broadcastRoll)
end
ns.session.myDice = myDice
ns.session.theirDice = theirDice
-- Evaluate hands using rules engine
local myHand = ns.Rules:EvaluateHand(myDice)
local theirHand = ns.Rules:EvaluateHand(theirDice)
if ns.UI then
ns.UI:CelebrateHand("You", myHand)
ns.UI:CelebrateHand(ns.Utils.ShortName(ns.session.opponent), theirHand)
end
local result = ns.Rules:CompareHands(myHand, theirHand)
-- Handle ties -> go to tiebreaker
if result == "tie" then
print("|cffffff00CeeLo:|r It's a tie! Starting tiebreaker round...")
if ns.UI then
ns.UI:ShowTiebreaker(myDice, theirDice, myHand, theirHand, ns.session.opponent)
end
-- Play tie sound
ns.Utils.PlaySound("UI_GARRISON_TOAST_MISSION_COMPLETE")
-- Start tiebreaker after a short delay (or sooner, if the opponent's
-- next-round commit arrives first - see Net:OnCommit)
ns.session.pendingTiebreaker = true
local session = ns.session
C_Timer.After(3, function()
if ns.session == session and session.pendingTiebreaker then
ns:StartTiebreaker()
end
end)
return
end
ns.session.result = result
-- Update stats (only on final resolution, not ties)
if result == "win" then
ns.charDB.wins = ns.charDB.wins + 1
elseif result == "lose" then
ns.charDB.losses = ns.charDB.losses + 1
end
-- Record in history
ns:RecordMatch(result, myDice, theirDice, myHand, theirHand)
-- Play sound
if result == "win" then
ns.Utils.PlaySound("UI_BONUS_EVENT_SYSTEM_VIGNETTES")
elseif result == "lose" then
ns.Utils.PlaySound("RAID_WARNING")
end
-- Show result UI
if ns.UI then
ns.UI:ShowResult(result, myDice, theirDice, myHand, theirHand, ns.session.opponent)
end
-- Only the winner sends the outcome emote, including both rolls, so
-- nearby players only see one message instead of one from each side.
if result == "win" then
local winnerRoll = table.concat(myDice, "-")
local loserRoll = table.concat(theirDice, "-")
local outcomeMsg = string.format("defeats %s in Cee-lo! [%s] vs [%s]",
ns.session.opponent, winnerRoll, loserRoll)
if ns.session.tiebreakerRound > 0 then
outcomeMsg = outcomeMsg:gsub("!$", string.format(" after %d tiebreaker round(s)!", ns.session.tiebreakerRound))
end
ns.Utils.SendEmote(outcomeMsg)
end
-- Reset after delay, unless a new game has started in the meantime
local session = ns.session
C_Timer.After(8, function()
if ns.session == session and session.state == ns.STATE.RESOLVED then
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
end)
end
--- End the game as a win because the opponent failed the reveal step
function ns:ResolveForfeit(reason)
local opponent = ns.session.opponent
print(string.format("|cffff0000CeeLo:|r %s %s. You win by forfeit.", opponent or "Opponent", reason))
-- Let them know, in case they're an honest client stuck waiting on us
if opponent then
ns.Net:SendMessage("CANCEL", {}, opponent)
end
ns.charDB.wins = ns.charDB.wins + 1
ns:RecordMatch("win", nil, nil, nil, nil, true)
ns.Utils.PlaySound("UI_BONUS_EVENT_SYSTEM_VIGNETTES")
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
function ns:RecordMatch(result, myDice, theirDice, myHand, theirHand, forfeit)
local match = {
opponent = ns.session.opponent,
result = result,
myDice = myDice,
theirDice = theirDice,
myHandName = myHand and myHand.name,
theirHandName = theirHand and theirHand.name,
forfeit = forfeit or nil,
date = date("%Y-%m-%d %H:%M"),
}
ns:AddHistory(match)
end
--- Add a match (1v1 or group table) to the front of the history, trimming old ones
function ns:AddHistory(match)
table.insert(ns.db.matchHistory, 1, match)
while #ns.db.matchHistory > ns.db.maxHistorySize do
table.remove(ns.db.matchHistory)
end
end
-- ============================================================================
-- Timeout Management
-- ============================================================================
function ns:StartTimeout(seconds, callback)
ns:ClearTimeout()
ns.session.timeout = C_Timer.NewTimer(seconds, callback)
end
function ns:ClearTimeout()
if ns.session.timeout then
ns.session.timeout:Cancel()
ns.session.timeout = nil
end
end
-- ============================================================================
-- Event Handling
-- ============================================================================
eventFrame:SetScript("OnEvent", function(self, event, ...)
if event == "ADDON_LOADED" then
local loadedAddon = ...
if loadedAddon == addonName then
ns:Initialize()
self:UnregisterEvent("ADDON_LOADED")
end
elseif event == "PLAYER_LOGOUT" then
-- Cancel any active game
if ns.session.state ~= ns.STATE.IDLE and ns.session.opponent then
ns.Net:SendMessage("CANCEL", {}, ns.session.opponent)
end
elseif event == "PLAYER_REGEN_DISABLED" then
-- Entered combat
local state = ns.session.state
if (state ~= ns.STATE.IDLE and state ~= ns.STATE.RESOLVED) or ns.session.pendingTiebreaker then
print("|cffff6600CeeLo:|r Game cancelled due to combat.")
if ns.session.opponent then
ns.Net:SendMessage("CANCEL", {}, ns.session.opponent)
end
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
elseif event == "PLAYER_REGEN_ENABLED" then
-- Left combat (could re-enable UI buttons here)
elseif event == "CHAT_MSG_SYSTEM" then
-- A whisper to a name the server doesn't know still reports success;
-- the failure only shows up as "No player named 'X' is currently
-- playing." So watch for it rather than waiting out the timeout.
local msg = ...
local opponent = ns.session.opponent
if ns.session.state ~= ns.STATE.IDLE and opponent and not ns.Utils.IsSecret(msg)
and msg == string.format(ERR_CHAT_PLAYER_NOT_FOUND_S or "No player named '%s' is currently playing.", opponent) then
print(string.format("|cffff6600CeeLo:|r Couldn't reach %s. They may be offline, or need their full name (WoW Forever: /ceelo challenge First Last).", opponent))
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
end
end)
-- ============================================================================
-- Expose API for other addons
-- ============================================================================
ns.API = {}
function ns.API.GetVersion()
return ns.version
end
function ns.API.Challenge(playerName)
ns:Challenge(playerName)
end
function ns.API.GetStats()
return {
wins = ns.charDB.wins,
losses = ns.charDB.losses,
ties = ns.charDB.ties,
}
end