-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
3128 lines (2680 loc) · 110 KB
/
main.lua
File metadata and controls
3128 lines (2680 loc) · 110 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
-- Manastorm - Wizard Duel Game
-- Main game file
-- Load dependencies
local AssetCache = require("core.AssetCache")
local AssetPreloader = require("core.assetPreloader")
local Constants = require("core.Constants")
local Input = require("core.Input")
local Pool = require("core.Pool")
local Wizard = require("wizard")
local ManaPool = require("manapool")
local UI = require("ui")
local VFX = require("vfx")
local Keywords = require("keywords")
local SpellCompiler = require("spellCompiler")
local EventRunner = require("systems.EventRunner")
local SpellsModule = require("spells") -- Now using the modular spells structure
local SustainedSpellManager = require("systems.SustainedSpellManager")
local SustainedIndicatorRenderer = require("systems.SustainedIndicatorRenderer")
local AttractModeInput = require("systems.AttractModeInput")
local Settings = require("core.Settings")
local Tips = require("core.Tips")
local OpponentAI = require("ai.OpponentAI")
local SelenePersonality = require("ai.personalities.SelenePersonality")
local AshgarPersonality = require("ai.personalities.AshgarPersonality")
local SilexPersonality = require("ai.personalities.SilexPersonality")
local BorrakPersonality = require("ai.personalities.BorrakPersonality")
local CharacterData = require("characterData")
-- Resolution settings
local baseWidth = 800 -- Base design resolution width
local baseHeight = 600 -- Base design resolution height
local scale = 1 -- Current scaling factor
local offsetX = 0 -- Horizontal offset for pillarboxing
local offsetY = 0 -- Vertical offset for letterboxing
-- Screen shake variables
local shakeTimer = 0
local shakeIntensity = 0
-- Hitstop variables
local hitstopTimer = 0
-- Game state (globally accessible)
game = {
wizards = {},
manaPool = nil,
font = nil,
characterData = CharacterData,
rangeState = Constants.RangeState.FAR, -- Initial range state (NEAR or FAR)
gameOver = false,
winner = nil,
winScreenTimer = 0,
winScreenDuration = 5, -- How long to show the win screen before auto-reset
keywords = Keywords,
spellCompiler = SpellCompiler,
eventRunner = EventRunner,
-- State management
currentState = "MENU", -- Start in the menu state (MENU, CHARACTER_SELECT, BATTLE, GAME_OVER, BATTLE_ATTRACT, GAME_OVER_ATTRACT, CAMPAIGN_MENU, CAMPAIGN_VICTORY, CAMPAIGN_DEFEAT)
campaignProgress = nil, -- Holds campaign run info when active
-- Game mode
useAI = false, -- Whether to use AI for the second player
-- Gamepad identifiers (assigned when controllers connect)
p1GamepadID = nil,
p2GamepadID = nil,
p2UsingGamepad = false,
-- Attract mode properties
attractModeActive = false,
menuIdleTimer = 0,
ATTRACT_MODE_DELAY = 15, -- Start attract mode after 15 seconds of inactivity
settings = Settings,
settingsMenu = {
selected = 1,
mode = nil,
waitingForKey = nil,
bindOrder = {
{"p1","slot1","P1 Slot 1"},
{"p1","slot2","P1 Slot 2"},
{"p1","slot3","P1 Slot 3"},
{"p1","cast","P1 Cast"},
{"p2","slot1","P2 Slot 1"},
{"p2","slot2","P2 Slot 2"},
{"p2","slot3","P2 Slot 3"},
{"p2","cast","P2 Cast"}
},
rebindIndex = 1,
rebindSelection = 1,
rebindPlayerType = nil,
rebindActionList = nil,
rebindOptions = nil
},
-- Resolution properties
baseWidth = baseWidth,
baseHeight = baseHeight,
scale = scale,
offsetX = offsetX,
offsetY = offsetY,
currentTip = nil
}
-- Helper function to trigger screen shake
function triggerShake(duration, intensity)
shakeTimer = duration or 0.5
shakeIntensity = intensity or 5
print("Screen shake triggered: " .. duration .. "s, intensity " .. intensity)
end
-- Helper function to trigger hitstop (game pause)
function triggerHitstop(duration)
hitstopTimer = duration or 0.1
print("Hitstop triggered: " .. duration .. "s")
end
-- Make these functions available to other modules through the game table
game.triggerShake = triggerShake
game.triggerHitstop = triggerHitstop
-- Define token types and images (globally available for consistency)
game.tokenTypes = {
Constants.TokenType.FIRE,
Constants.TokenType.WATER,
Constants.TokenType.SALT,
Constants.TokenType.SUN,
Constants.TokenType.MOON,
Constants.TokenType.STAR,
Constants.TokenType.LIFE,
Constants.TokenType.MIND,
Constants.TokenType.VOID
}
game.tokenImages = {
[Constants.TokenType.FIRE] = "assets/sprites/v2Tokens/fire-token.png",
[Constants.TokenType.WATER] = "assets/sprites/v2Tokens/water-token.png",
[Constants.TokenType.SALT] = "assets/sprites/v2Tokens/salt-token.png",
[Constants.TokenType.SUN] = "assets/sprites/v2Tokens/sun-token.png",
[Constants.TokenType.MOON] = "assets/sprites/v2Tokens/moon-token.png",
[Constants.TokenType.STAR] = "assets/sprites/v2Tokens/star-token.png",
[Constants.TokenType.LIFE] = "assets/sprites/v2Tokens/life-token.png",
[Constants.TokenType.MIND] = "assets/sprites/v2Tokens/mind-token.png",
[Constants.TokenType.VOID] = "assets/sprites/v2Tokens/void-token.png"
}
-- Character roster and unlocks
game.characterRoster = {
"Ashgar", "Borrak", "Silex",
"Brightwulf", "Selene", "Klaus",
"Ohm", "Archive", "End"
}
game.unlockedCharacters = {
Ashgar = true,
Borrak = true,
Silex = false,
Selene = true,
Brightwulf = true,
Klaus = false,
Ohm = false,
Archive = false,
End = false
}
-- Spells unlocked for customization
game.unlockedSpells = {
conjurefire = true,
firebolt = true,
fireball = true,
burnToAsh = true,
blastwave = true,
saltcircle = true,
eruption = true,
conjuremoonlight = true,
wrapinmoonlight = true,
moondance = true,
infiniteprocession = true,
eclipse = true,
gravityTrap = true,
fullmoonbeam = true,
conjuresalt = true,
glitterfang = true,
imprison = true,
stoneshield = true,
shieldbreaker = true,
saltstorm = true,
conjurewater = true,
watergun = true,
riptideguard = true,
tidalforce = true,
brinechain = true,
maelstrom = true,
wavecrash = true,
desperationfire = true,
moondrain = true,
}
-- Custom spellbooks configured by the player
game.customSpellbooks = {}
game.compendium = {
page = 1,
cursor = 1,
scrollOffset = 0,
assignFeedback = {
active = false,
slot = 0,
timer = 0
}
}
-- Temporary state for the campaign character selection menu
game.campaignMenu = {
selectedCharacterIndex = 1
}
-- Get a list of all unlocked characters in the roster
local function getUnlockedCharacterList()
local list = {}
for _, name in ipairs(game.characterRoster) do
if game.unlockedCharacters[name] then
table.insert(list, name)
end
end
return list
end
-- Helper to grab an AI personality for a given character name
local function getPersonalityFor(name)
if name == "Selene" then
return SelenePersonality
elseif name == "Ashgar" then
return AshgarPersonality
elseif name == "Borrak" then
return BorrakPersonality
elseif name == "Silex" then
return SilexPersonality
else
return nil
end
end
game.characterSelect = {
stage = 1, -- 1: choose player, 2: choose opponent, 3: confirm
cursor = 1,
selected = {nil, nil}
}
-- Helper function to add a random token to the mana pool
function game.addRandomToken()
local randomType = game.tokenTypes[math.random(#game.tokenTypes)]
game.manaPool:addToken(randomType, game.tokenImages[randomType])
return randomType
end
-- Calculate the appropriate scaling for the current window size
function calculateScaling()
local windowWidth, windowHeight = love.graphics.getDimensions()
-- Calculate potential scales based on window dimensions
local scaleX = windowWidth / baseWidth
local scaleY = windowHeight / baseHeight
-- Use the smaller scale factor to maintain aspect ratio and fit within the window
scale = math.min(scaleX, scaleY)
-- Calculate offsets needed to center the scaled content
offsetX = (windowWidth - baseWidth * scale) / 2
offsetY = (windowHeight - baseHeight * scale) / 2
-- Update global references
game.scale = scale
game.offsetX = offsetX
game.offsetY = offsetY
print("Window resized: " .. windowWidth .. "x" .. windowHeight .. " -> Simple scale: " .. scale .. ", Offset: (" .. offsetX .. ", " .. offsetY .. ")")
end
-- Set a scissor rectangle taking current scale and offsets into account
local function setScaledScissor(x, y, w, h)
love.graphics.setScissor(
offsetX + x * scale,
offsetY + y * scale,
w * scale,
h * scale
)
end
-- Handle window resize events
function love.resize(width, height)
calculateScaling()
end
-- Set up pixel art-friendly scaling
-- function configurePixelArtRendering()
-- -- Disable texture filtering for crisp pixel art
-- love.graphics.setDefaultFilter("nearest", "nearest", 1)
--
-- -- Use integer scaling when possible
-- love.graphics.setLineStyle("rough")
-- end
function love.load()
-- Set up window
love.window.setTitle("Manastorm - Realtime Strategic Wizard Duels")
-- Configure pixel art rendering -- REMOVE THIS CALL
-- configurePixelArtRendering()
-- Set default texture filtering for crisp chunky pixels
love.graphics.setDefaultFilter("nearest", "nearest")
love.graphics.setLineStyle("rough")
-- Calculate initial scaling
calculateScaling()
-- Load background image
game.backgroundImage = AssetCache.getImage("assets/sprites/background.png")
-- Preload all assets to prevent in-game loading hitches
print("Preloading game assets...")
local preloadStats = AssetPreloader.preloadAllAssets()
print(string.format("Asset preloading complete: %d images, %d sounds in %.2f seconds",
preloadStats.imageCount,
preloadStats.soundCount,
preloadStats.loadTime))
-- Load persisted settings
Settings.load()
Constants.setCastSpeedSet(Settings.get("gameSpeed") or "FAST")
-- Set up game object to have calculateScaling function that can be called by Input
game.calculateScaling = calculateScaling
-- Load game font
-- For now, fall back to system font if custom font isn't available
local fontPath = "assets/fonts/LionscriptNew-Regular.ttf"
local fontExists = love.filesystem.getInfo(fontPath)
if fontExists then
game.font = love.graphics.newFont(fontPath, 16)
print("Using custom game font: " .. fontPath)
else
game.font = love.graphics.newFont(16) -- Default system font
print("Custom font not found, using system font")
end
-- Set default font for normal rendering
love.graphics.setFont(game.font)
-- Load gameplay tips
Tips.load("assets/text/tips.json")
-- Create mana pool positioned above the battlefield, but below health bars
game.manaPool = ManaPool.new(baseWidth/2, 120) -- Positioned between health bars and wizards
-- Create wizards - moved lower on screen to allow more room for aerial movement
local d1 = CharacterData.Ashgar
local d2 = CharacterData.Selene
game.wizards[1] = Wizard.new("Ashgar", 200, 370, d1.color, d1.spellbook)
game.wizards[2] = Wizard.new("Selene", 600, 370, d2.color, d2.spellbook)
-- Set up references
for _, wizard in ipairs(game.wizards) do
wizard.manaPool = game.manaPool
wizard.gameState = game
end
-- Initialize VFX system
game.vfx = VFX.init()
-- Make screen shake and hitstop functions directly available to VFX module
VFX.triggerShake = triggerShake
VFX.triggerHitstop = triggerHitstop
-- Precompile all spells for better performance
print("Precompiling all spells...")
-- Create a compiledSpells table and do the compilation ourselves
game.compiledSpells = {}
-- Get all spells from the SpellsModule
local allSpells = SpellsModule.spells
-- Compile each spell
for id, spell in pairs(allSpells) do
game.compiledSpells[id] = game.spellCompiler.compileSpell(spell, game.keywords)
print("Compiled spell: " .. spell.name)
end
-- Count compiled spells
local count = 0
for _ in pairs(game.compiledSpells) do
count = count + 1
end
print("Precompiled " .. count .. " spells")
-- Create custom shield spells just for hotkeys
-- These are complete, independent spell definitions
game.customSpells = {}
-- Define Moon Ward with minimal dependencies
game.customSpells.moonWard = {
id = "customMoonWard",
name = "Moon Ward",
description = "A mystical ward that blocks projectiles and remotes",
attackType = Constants.AttackType.UTILITY,
castTime = 4.5,
cost = {Constants.TokenType.MOON, Constants.TokenType.MOON},
keywords = {
block = {
type = Constants.ShieldType.WARD,
blocks = {Constants.AttackType.PROJECTILE, Constants.AttackType.REMOTE},
manaLinked = true
}
},
vfx = "moon_ward",
sfx = "shield_up",
}
-- Define Mirror Shield with minimal dependencies
game.customSpells.mirrorShield = {
id = "customMirrorShield",
name = "Mirror Shield",
description = "A reflective barrier that returns damage to attackers",
attackType = Constants.AttackType.UTILITY,
castTime = 5.0,
cost = {Constants.TokenType.MOON, Constants.TokenType.MOON, Constants.TokenType.STAR},
keywords = {
block = {
type = Constants.ShieldType.BARRIER,
blocks = {Constants.AttackType.PROJECTILE, Constants.AttackType.ZONE},
manaLinked = false,
reflect = true,
hitPoints = 3
}
},
vfx = "mirror_shield",
sfx = "crystal_ring",
}
-- Compile custom spells too
for id, spell in pairs(game.customSpells) do
game.compiledSpells[id] = game.spellCompiler.compileSpell(spell, game.keywords)
print("Compiled custom spell: " .. spell.name)
end
-- Initialize mana pool with a single random token to start
local tokenType = game.addRandomToken()
-- Log which token was added
print("Starting the game with a single " .. tokenType .. " token")
-- Initialize input system with game state reference
Input.init(game)
print("Input system initialized")
-- Initialize SustainedSpellManager
game.sustainedSpellManager = SustainedSpellManager
print("SustainedSpellManager initialized")
-- We'll initialize the AI opponent when starting a game with AI
-- instead of here, so it's not always active
end
-- Display hotkey help overlay
function drawHotkeyHelp()
local x = baseWidth - 300
local y = 50
local lineHeight = 20
love.graphics.setColor(0, 0, 0, 0.7)
love.graphics.rectangle("fill", x - 10, y - 10, 290, 500)
love.graphics.setColor(1, 1, 1, 0.9)
love.graphics.print("HOTKEY REFERENCE", x, y)
y = y + lineHeight * 2
-- System keys
love.graphics.setColor(0.8, 0.8, 1, 1)
love.graphics.print("SYSTEM:", x, y)
y = y + lineHeight
love.graphics.setColor(1, 1, 1, 0.8)
for i, key in ipairs(Input.reservedKeys.system) do
love.graphics.print(" " .. key, x, y)
y = y + lineHeight
end
y = y + lineHeight/2
-- Player 1 keys
love.graphics.setColor(1, 0.5, 0.5, 1)
love.graphics.print("PLAYER 1:", x, y)
y = y + lineHeight
love.graphics.setColor(1, 1, 1, 0.8)
for i, key in ipairs(Input.reservedKeys.player1) do
love.graphics.print(" " .. key, x, y)
y = y + lineHeight
end
y = y + lineHeight/2
-- Player 2 keys
love.graphics.setColor(0.5, 0.5, 1, 1)
love.graphics.print("PLAYER 2:", x, y)
y = y + lineHeight
love.graphics.setColor(1, 1, 1, 0.8)
for i, key in ipairs(Input.reservedKeys.player2) do
love.graphics.print(" " .. key, x, y)
y = y + lineHeight
end
y = y + lineHeight/2
-- Debug keys
love.graphics.setColor(0.8, 1, 0.8, 1)
love.graphics.print("DEBUG:", x, y)
y = y + lineHeight
love.graphics.setColor(1, 1, 1, 0.8)
for i, key in ipairs(Input.reservedKeys.debug) do
love.graphics.print(" " .. key, x, y)
y = y + lineHeight
end
-- Testing keys
y = y + lineHeight/2
love.graphics.setColor(1, 0.8, 0.5, 1)
love.graphics.print("TESTING:", x, y)
y = y + lineHeight
love.graphics.setColor(1, 1, 1, 0.8)
for i, key in ipairs(Input.reservedKeys.testing) do
love.graphics.print(" " .. key, x, y)
y = y + lineHeight
end
end
-- Reset the game
function resetGame()
-- Reset game state
game.gameOver = false
game.winner = nil
game.winScreenTimer = 0
game.currentTip = nil
-- Reset wizards
for _, wizard in ipairs(game.wizards) do
wizard.health = 100
wizard.elevation = Constants.ElevationState.GROUNDED
wizard.elevationTimer = 0
if wizard.statusEffects and wizard.statusEffects[Constants.StatusType.STUN] then
wizard.statusEffects[Constants.StatusType.STUN].active = false
wizard.statusEffects[Constants.StatusType.STUN].duration = 0
wizard.statusEffects[Constants.StatusType.STUN].elapsed = 0
wizard.statusEffects[Constants.StatusType.STUN].totalTime = 0
end
-- Reset spell slots
for i = 1, 3 do
wizard.spellSlots[i] = {
active = false,
progress = 0,
spellType = nil,
castTime = 0,
tokens = {},
isShield = false,
defenseType = nil,
shieldStrength = 0,
blocksAttackTypes = nil,
wasAlreadyCast = false -- Add this flag to prevent repeated spell casts
}
end
-- Reset status effects
wizard.statusEffects[Constants.StatusType.BURN].active = false
wizard.statusEffects[Constants.StatusType.BURN].duration = 0
wizard.statusEffects[Constants.StatusType.BURN].tickDamage = 0
wizard.statusEffects[Constants.StatusType.BURN].tickInterval = 1.0
wizard.statusEffects[Constants.StatusType.BURN].elapsed = 0
wizard.statusEffects[Constants.StatusType.BURN].totalTime = 0
-- Reset blockers
if wizard.blockers then
for blockType in pairs(wizard.blockers) do
wizard.blockers[blockType] = 0
end
end
-- Reset spell keying
wizard.activeKeys = {[1] = false, [2] = false, [3] = false}
wizard.currentKeyedSpell = nil
end
-- Reset range state
game.rangeState = Constants.RangeState.FAR
-- Clear sustained spells
if game.sustainedSpellManager then
game.sustainedSpellManager.activeSpells = {}
end
-- Clear mana pool and add a single token to start
if game.manaPool then
game.manaPool:clear()
local tokenType = game.addRandomToken()
print("Game reset! Starting with a single " .. tokenType .. " token")
end
-- Reinitialize AI opponent if AI mode is enabled and not being set up by campaign
if game.useAI then
if not game.isSettingUpCampaignBattle then
local aiWizard = game.wizards[2]
local personality = getPersonalityFor(aiWizard.name)
if personality then
print("Initializing " .. aiWizard.name .. " AI personality")
else
print("Unknown wizard type: " .. aiWizard.name .. ". Using default personality.")
end
game.opponentAI = OpponentAI.new(aiWizard, game, personality)
print("AI opponent reinitialized with personality: " .. (personality and personality.name or "Default"))
end
else
-- Disable AI if we're switching to PvP mode
game.opponentAI = nil
end
-- Reset health display animation state
if UI and UI.healthDisplay then
for i = 1, 2 do
local display = UI.healthDisplay["player" .. i]
if display then
display.currentHealth = 100
display.targetHealth = 100
display.pendingDamage = 0
display.lastDamageTime = 0
end
end
end
-- The current state is handled by the caller
print("Game reset complete")
end
-- Add resetGame function to game state so Input system can call it
function game.resetGame()
resetGame()
end
-- Function to start an AI vs AI attract mode game
function startGameAttractMode()
print("Starting attract mode...")
-- Mark attract mode as active
game.attractModeActive = true
-- Reset the game to clear any existing state
resetGame()
-- Choose two random unlocked characters
local unlocked = getUnlockedCharacterList()
if #unlocked < 2 then
print("Not enough unlocked characters for attract mode")
return
end
local name1 = unlocked[math.random(#unlocked)]
local name2 = unlocked[math.random(#unlocked)]
while name2 == name1 do
name2 = unlocked[math.random(#unlocked)]
end
setupWizards(name1, name2)
-- Temporarily store input routes so we can restore them later
game.savedInputRoutes = AttractModeInput.snapshotAndDisable(Input.Routes)
-- Make sure AI mode is enabled but not tracked by the normal flag
-- This way we can have two AI players without affecting the normal mode
game.useAI = false
-- Create AIs for both players
game.player1AI = OpponentAI.new(game.wizards[1], game, getPersonalityFor(name1))
game.player2AI = OpponentAI.new(game.wizards[2], game, getPersonalityFor(name2))
-- Reset idle timer
game.menuIdleTimer = 0
-- Transition to the attract mode battle state
game.currentState = "BATTLE_ATTRACT"
print("Attract mode started: " .. game.wizards[1].name .. " vs " .. game.wizards[2].name)
end
-- Function to exit attract mode and return to the menu
function exitAttractMode()
print("Exiting attract mode...")
-- Disable attract mode
game.attractModeActive = false
-- Clean up AI instances
game.player1AI = nil
game.player2AI = nil
-- Reset the game
resetGame()
-- Restore input routes if we saved them
if game.savedInputRoutes then
AttractModeInput.restore(Input.Routes, game.savedInputRoutes)
game.savedInputRoutes = nil
end
-- Reset idle timer
game.menuIdleTimer = 0
-- Return to menu
game.currentState = "MENU"
print("Attract mode ended, returned to menu")
end
-- Handle successful completion of a campaign
function handleCampaignVictory()
if not game.campaignProgress then return end
print(game.campaignProgress.characterName .. " campaign complete! Wins: " .. game.campaignProgress.wins)
game.currentState = "CAMPAIGN_VICTORY"
end
-- Handle failure of a campaign run
function handleCampaignDefeat()
if not game.campaignProgress then return end
print(game.campaignProgress.characterName .. " campaign failed at opponent " .. game.campaignProgress.currentOpponentIndex)
resetGame()
game.currentState = "CAMPAIGN_DEFEAT"
end
-- Restart the entire campaign from the first opponent
function restartCampaign()
if not game.campaignProgress then return end
game.campaignProgress.currentOpponentIndex = 1
game.campaignProgress.wins = 0
startCampaignBattle()
end
-- Retry the current campaign battle
function retryCampaignBattle()
if not game.campaignProgress then return end
startCampaignBattle()
end
-- Expose campaign helpers
game.restartCampaign = restartCampaign
game.retryCampaignBattle = retryCampaignBattle
-- Placeholder implementation for starting a campaign battle
function startCampaignBattle()
if not game.campaignProgress then
print("ERROR: startCampaignBattle called without campaignProgress")
return
end
local playerCharacterName = game.campaignProgress.characterName
local opponentIndex = game.campaignProgress.currentOpponentIndex or 1
local playerData = game.characterData[playerCharacterName] or {}
local opponentName
if playerData.campaignOpponents then
opponentName = playerData.campaignOpponents[opponentIndex]
end
if not opponentName then
if handleCampaignVictory then
handleCampaignVictory()
else
print("Campaign complete for " .. tostring(playerCharacterName))
end
return
end
setupWizards(playerCharacterName, opponentName)
game.useAI = true
local personality = getPersonalityFor(opponentName)
game.opponentAI = OpponentAI.new(game.wizards[2], game, personality)
game.isSettingUpCampaignBattle = true
resetGame()
game.isSettingUpCampaignBattle = nil
game.currentState = "BATTLE"
end
-- Initialize wizards for battle based on selected names
function setupWizards(name1, name2)
local data1 = game.characterData[name1] or {}
local data2 = game.characterData[name2] or {}
local book1 = game.customSpellbooks[name1] or data1.spellbook
local book2 = game.customSpellbooks[name2] or data2.spellbook
game.wizards[1] = Wizard.new(name1, 200, 370, data1.color or {255,255,255}, book1)
game.wizards[2] = Wizard.new(name2, 600, 370, data2.color or {255,255,255}, book2)
for _, wizard in ipairs(game.wizards) do
wizard.manaPool = game.manaPool
wizard.gameState = game
end
end
-- Start character selection
function game.startCharacterSelect()
game.characterSelect.stage = 1
game.characterSelect.cursor = 1
game.characterSelect.selected = {nil,nil}
game.useAI = true -- default to AI opponent
game.p2UsingGamepad = false
game.currentState = "CHARACTER_SELECT"
end
-- Move selection cursor
function game.characterSelectMove(dir)
local count = #game.characterRoster
local idx = game.characterSelect.cursor
repeat
idx = ((idx -1 + dir -1) % count) + 1
until game.unlockedCharacters[game.characterRoster[idx]]
game.characterSelect.cursor = idx
end
-- Confirm selection or start fight
function game.characterSelectConfirm()
local idx = game.characterSelect.cursor
local name = game.characterRoster[idx]
if not game.unlockedCharacters[name] then return end
if game.characterSelect.stage == 1 then
game.characterSelect.selected[1] = name
game.characterSelect.stage = 2
elseif game.characterSelect.stage == 2 then
game.characterSelect.selected[2] = name
game.characterSelect.stage = 3
else
setupWizards(game.characterSelect.selected[1], game.characterSelect.selected[2])
resetGame()
game.currentState = "BATTLE"
end
end
-- Back out of selection
function game.characterSelectBack(toMenu)
if toMenu then
game.currentState = "MENU"
return
end
if game.characterSelect.stage == 2 then
game.characterSelect.stage = 1
game.characterSelect.selected[1] = nil
elseif game.characterSelect.stage == 3 then
game.characterSelect.stage = 2
game.characterSelect.selected[2] = nil
else
game.currentState = "MENU"
end
end
-- Start settings menu
function game.startSettings()
game.settingsMenu.selected = 1
game.settingsMenu.mode = nil
game.settingsMenu.waitingForKey = nil
game.settingsMenu.rebindIndex = 1
game.settingsMenu.rebindSelection = 1
game.settingsMenu.rebindPlayerType = nil
game.settingsMenu.rebindActionList = nil
game.settingsMenu.rebindOptions = {
{playerType = "keyboardP1", label = "Player 1 Keyboard"},
{playerType = "keyboardP2", label = "Player 2 Keyboard"},
{playerType = "gamepadP1", label = "Player 1 Gamepad"}
}
game.currentState = "SETTINGS"
end
function game.settingsMove(dir)
if game.settingsMenu.mode == "rebind_select_player" or game.settingsMenu.mode == "rebind_action_list" then
local list = (game.settingsMenu.mode == "rebind_select_player") and game.settingsMenu.rebindOptions or game.settingsMenu.rebindActionList
if not list then return end
local count = #list
local idx = game.settingsMenu.rebindSelection + dir
if idx < 1 then idx = count end
if idx > count then idx = 1 end
game.settingsMenu.rebindSelection = idx
return
elseif game.settingsMenu.mode then
return
end
local count = 4
local idx = game.settingsMenu.selected + dir
if idx < 1 then idx = count end
if idx > count then idx = 1 end
game.settingsMenu.selected = idx
end
function game.settingsAdjust(dir)
if game.settingsMenu.mode then return end
if game.settingsMenu.selected == 1 then
if dir ~= 0 then
local val = Settings.get("dummyFlag")
Settings.set("dummyFlag", not val)
end
elseif game.settingsMenu.selected == 2 then
if dir ~= 0 then
local current = Settings.get("gameSpeed") or "FAST"
if current == "FAST" then
current = "SLOW"
else
current = "FAST"
end
Settings.set("gameSpeed", current)
Constants.setCastSpeedSet(current)
end
end
end
function game.unlockAll()
-- Unlock all characters
for _, characterName in ipairs(game.characterRoster) do
game.unlockedCharacters[characterName] = true
end
-- Unlock all spells
local allSpellIds = {
-- Fire
"conjurefire", "firebolt", "fireball", "blastwave", "combustMana",
"blazingascent", "eruption", "battleshield",
-- Mind
"thoughtscalp",
-- Moon
"conjuremoonlight", "tidalforce", "lunardisjunction", "moondance",
"gravity", "eclipse", "fullmoonbeam", "lunartides", "wrapinmoonlight",
"gravityTrap", "infiniteprocession", "enhancedmirrorshield",
-- Salt
"conjuresalt", "glitterfang", "burnToAsh", "saltstorm", "imprison",
"jaggedearth", "saltcircle", "stoneshield", "shieldbreaker",
-- Star
"conjurestars", "adaptivesurge", "cosmicrift",
-- Sun
"radiantbolt", "fusionRay", "meteor", "emberlift", "novaconjuring",
"burnTheSoul", "SpaceRipper", "StingingEyes", "CoreBolt", "NuclearFurnace",
"forcebarrier", "radiantfield",
-- Void
"conjurenothing", "riteofemptiness", "quenchPower", "heartripper",
-- Water
"watergun", "forceblast", "conjurewater", "maelstrom", "riptideguard",
"brinechain", "wavecrash",
-- Generic
"none"
}
for _, spellId in ipairs(allSpellIds) do
game.unlockedSpells[spellId] = true
end
print("[DEV] All characters and spells unlocked!")
end
function game.settingsSelect()
if game.settingsMenu.mode == "rebind_select_player" then
local option = game.settingsMenu.rebindOptions[game.settingsMenu.rebindSelection]
if option then
game.settingsMenu.rebindPlayerType = option.playerType
local controls = Settings.get("controls")[option.playerType] or {}
game.settingsMenu.rebindActionList = {}
for action, binding in pairs(controls) do
table.insert(game.settingsMenu.rebindActionList, {action = action, binding = binding})
end
table.sort(game.settingsMenu.rebindActionList, function(a,b) return a.action < b.action end)
game.settingsMenu.rebindSelection = 1
game.settingsMenu.mode = "rebind_action_list"
end
elseif game.settingsMenu.mode == "rebind_action_list" then
local entry = game.settingsMenu.rebindActionList[game.settingsMenu.rebindSelection]
if entry then
game.settingsMenu.waitingForKey = {playerType = game.settingsMenu.rebindPlayerType, action = entry.action, label = entry.action}
end
else
if game.settingsMenu.selected == 3 then
game.unlockAll()
elseif game.settingsMenu.selected == 4 then
game.settingsMenu.mode = "rebind_select_player"
game.settingsMenu.rebindSelection = 1
else
game.settingsAdjust(1)
end
end
end
function game.settingsBack()
if game.settingsMenu.waitingForKey then
game.settingsMenu.waitingForKey = nil
return
end
if game.settingsMenu.mode == "rebind_action_list" then
game.settingsMenu.mode = "rebind_select_player"
game.settingsMenu.rebindSelection = 1
return
elseif game.settingsMenu.mode == "rebind_select_player" then
game.settingsMenu.mode = nil
game.settingsMenu.rebindPlayerType = nil