-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
session.go
2121 lines (1804 loc) · 56.3 KB
/
session.go
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
package game
import (
"bytes"
"context"
"encoding/gob"
"errors"
"fmt"
"github.com/BigJk/end_of_eden/internal/fs"
"github.com/BigJk/end_of_eden/internal/lua/ludoc"
"github.com/BigJk/end_of_eden/system/gen"
"github.com/BigJk/end_of_eden/system/gen/faces"
"github.com/BigJk/end_of_eden/system/localization"
"github.com/BigJk/end_of_eden/ui"
"github.com/samber/lo"
lua "github.com/yuin/gopher-lua"
"golang.org/x/exp/slices"
"io"
"log"
"math/rand"
"oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/d2layouts/d2dagrelayout"
"oss.terrastruct.com/d2/d2lib"
"oss.terrastruct.com/d2/d2renderers/d2svg"
"oss.terrastruct.com/d2/d2themes/d2themescatalog"
"oss.terrastruct.com/d2/lib/textmeasure"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
func init() {
gob.Register(FightState{})
gob.Register(MerchantState{})
}
// GameState represents the current state of the game.
type GameState string
const (
GameStateFight = GameState("FIGHT")
GameStateMerchant = GameState("MERCHANT")
GameStateEvent = GameState("EVENT")
GameStateRandom = GameState("RANDOM")
GameStateGameOver = GameState("GAME_OVER")
)
const (
// DefaultUpgradeCost is the default cost for upgrading a card.
DefaultUpgradeCost = 65
// DefaultRemoveCost is the default cost for removing a card.
DefaultRemoveCost = 50
// PointsPerRound is the amount of points the player gets per round.
PointsPerRound = 3
// DrawSize is the amount of cards the player draws per round.
DrawSize = 3
)
type Hook string
const (
HookNextFightEnd = Hook("NextFightEnd")
)
// FightState represents the current state of the fight in regard to the
// deck of the player.
type FightState struct {
Round int
Description string
CurrentPoints int
Deck []string
Hand []string
Used []string
Exhausted []string
}
// MerchantState represents the current state of the merchant.
type MerchantState struct {
Face string
Text string
Cards []string
Artifacts []string
}
// LuaError represents an error that occurred in lua.
type LuaError struct {
File string
Line int
Callback string
Type string
Err error
}
// Session represents the state inside a game session.
type Session struct {
log *log.Logger
luaState *lua.LState
luaDocs *ludoc.Docs
resources *ResourcesManager
state GameState
actors map[string]Actor
instances map[string]any
stagesCleared int
currentEvent string
currentFight FightState
merchant MerchantState
eventHistory []string
randomHistory []string
ctxData map[string]any
hooks map[Hook][]func()
loadedMods []string
stateCheckpoints []StateCheckpoint
closer []func() error
onLuaError func(file string, line int, callback string, typeId string, err error)
luaErrors chan LuaError
Logs []LogEntry
}
// NewSession creates a new game session.
func NewSession(options ...func(s *Session)) *Session {
session := &Session{
log: log.New(io.Discard, "", 0),
state: GameStateEvent,
actors: map[string]Actor{
PlayerActorID: NewActor(PlayerActorID),
},
instances: map[string]any{},
ctxData: map[string]any{},
hooks: map[Hook][]func(){
HookNextFightEnd: {},
},
stagesCleared: 0,
onLuaError: nil,
luaErrors: make(chan LuaError, 25),
eventHistory: []string{},
randomHistory: []string{},
}
session.SetOnLuaError(nil)
session.luaState, session.luaDocs = SessionAdapter(session)
for i := range options {
if options[i] == nil {
continue
}
options[i](session)
}
session.resources = NewResourcesManager(session.luaState, session.luaDocs, session.log)
session.resources.MarkBaseGame()
session.loadMods(session.loadedMods)
session.log.Println("Session started!")
session.UpdatePlayer(func(actor *Actor) bool {
actor.HP = 80
actor.MaxHP = 80
actor.Gold = 50 + rand.Intn(50)
return true
})
session.SetEvent("START")
return session
}
// WithDebugEnabled enables the lua debugging. With lua debugging a server will be started
// on the given bind port. This exposes the /ws route to connect over websocket to. In essence,
// it exposes REPL access to the internal lua state which is helpful to debug problems. You can use
// the debug_r function to send data back to the websocket.
//
// Tip: Use https://github.com/websockets/wscat to connect and talk with it.
func WithDebugEnabled(port int) func(s *Session) {
return func(s *Session) {
s.closer = append(s.closer, ExposeDebug(port, s, s.luaState, s.log))
}
}
// WithLogging sets the internal logger.
func WithLogging(logger *log.Logger) func(s *Session) {
return func(s *Session) {
s.log = logger
}
}
// WithMods sets the mods that should be loaded.
func WithMods(mods []string) func(s *Session) {
return func(s *Session) {
s.loadedMods = mods
}
}
// WithOnLuaError sets the function that will be called when a lua error happens.
func WithOnLuaError(fn func(file string, line int, callback string, typeId string, err error)) func(s *Session) {
return func(s *Session) {
s.onLuaError = fn
}
}
// SetOnLuaError sets the function that will be called when a lua error happens.
func (s *Session) SetOnLuaError(fn func(file string, line int, callback string, typeId string, err error)) {
if fn == nil {
s.onLuaError = func(file string, line int, callback string, typeId string, err error) {}
} else {
s.onLuaError = fn
}
}
// LuaDocs returns the documentation of the lua state.
func (s *Session) LuaDocs() *ludoc.Docs {
return s.luaDocs
}
// Close closes the internal lua state and everything else.
func (s *Session) Close() {
for i := range s.closer {
if err := s.closer[i](); err != nil {
s.log.Println("Close error:", err)
}
}
s.luaState.Close()
}
// LuaErrors returns a channel that will receive all lua errors that happen during the session.
// Only a single channel is used for all errors, so be wary when using this in multiple goroutines.
func (s *Session) LuaErrors() chan LuaError {
return s.luaErrors
}
// ToSavedState creates a saved state of the session that can be serialized with Gob.
func (s *Session) ToSavedState() SavedState {
return SavedState{
State: s.state,
Actors: s.actors,
Instances: s.instances,
StagesCleared: s.stagesCleared,
CurrentEvent: s.currentEvent,
CurrentFight: s.currentFight,
Merchant: s.merchant,
EventHistory: s.eventHistory,
StateCheckpoints: s.stateCheckpoints,
CtxData: s.ctxData,
LoadedMods: s.loadedMods,
}
}
// LoadSavedState applies a saved state to the session. This will overwrite all game related data, but
// not the lua state, logging etc. This also means that for a save file to work the same lua scripts
// should be loaded or the state could be corrupted.
func (s *Session) LoadSavedState(save SavedState) {
s.state = save.State
s.actors = lo.MapValues(save.Actors, func(item Actor, key string) Actor {
return item.Sanitize()
})
s.instances = save.Instances
s.stagesCleared = save.StagesCleared
s.currentEvent = save.CurrentEvent
s.currentFight = save.CurrentFight
s.merchant = save.Merchant
s.eventHistory = save.EventHistory
s.stateCheckpoints = lo.Map(save.StateCheckpoints, func(item StateCheckpoint, index int) StateCheckpoint {
item.Session = s
return item
})
s.ctxData = save.CtxData
s.loadedMods = save.LoadedMods
// Don't load mods from settings but from the saved list!
s.loadMods(s.loadedMods)
}
func (s *Session) GobEncode() ([]byte, error) {
buf := &bytes.Buffer{}
enc := gob.NewEncoder(buf)
err := enc.Encode(s.ToSavedState())
return buf.Bytes(), err
}
func (s *Session) GobDecode(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
var saved SavedState
if err := dec.Decode(&saved); err != nil {
return err
}
s.LoadSavedState(saved)
return nil
}
// GetResources returns the resources manager.
func (s *Session) GetResources() *ResourcesManager {
return s.resources
}
// GetLoadedMods returns the list of loaded mods.
func (s *Session) GetLoadedMods() []string {
return s.loadedMods
}
//
// Internal
//
func (s *Session) logLuaError(callback string, typeId string, err error) {
_, file, no, ok := runtime.Caller(1)
if ok {
s.log.Printf("%s:%d Error from Lua:%s type=%s %s\n", file, no, callback, typeId, err.Error())
s.onLuaError(file, no, callback, typeId, err)
s.luaErrors <- LuaError{
File: file,
Line: no,
Callback: callback,
Type: typeId,
Err: err,
}
} else {
s.log.Printf("Error from Lua:%s type=%s %s\n", callback, typeId, err.Error())
s.onLuaError("", 0, callback, typeId, err)
s.luaErrors <- LuaError{
File: "",
Line: 0,
Callback: callback,
Type: typeId,
Err: err,
}
}
}
func (s *Session) loadMods(mods []string) {
for i := range mods {
mod, err := ModDescription(filepath.Join("./mods", mods[i]))
if err != nil {
log.Println("Error loading mod:", err)
} else {
log.Println("Loading mod:", mod.Name)
}
_ = fs.Walk(filepath.Join("./mods", mods[i]), func(path string, isDir bool) error {
if strings.Contains(path, "__") {
return nil
}
// If we find a locals folder we add it to the localization
if isDir && filepath.Base(path) == "locals" {
_ = localization.Global.AddFolder(path)
}
if !isDir && strings.HasSuffix(path, ".lua") {
luaBytes, err := fs.ReadFile(path)
if err != nil {
// TODO: error handling
panic(err)
}
if strings.HasPrefix(string(luaBytes), "---@meta") {
return nil
}
if err := s.luaState.DoString(string(luaBytes)); err != nil {
s.logLuaError("ModLoader", "", err)
}
}
return nil
})
}
}
//
// Checkpoints
//
// MarkState creates a checkpoint of the session state that can be used to diff and see what happened
// between two points in time.
func (s *Session) MarkState() StateCheckpointMarker {
return StateCheckpointMarker{checkpoints: s.stateCheckpoints}
}
// PushState pushes a new state to the session. New states are relevant information like damage done,
// money received, actor death etc.
func (s *Session) PushState(events map[StateEvent]any) {
savedState := *s
// Only have the current session have the state checkpoints
savedState.stateCheckpoints = make([]StateCheckpoint, 0)
savedState.actors = lo.MapValues(CopyMap(savedState.actors), func(actor Actor, key string) Actor {
return actor.Clone()
})
savedState.instances = CopyMap(savedState.instances)
s.stateCheckpoints = append(s.stateCheckpoints, StateCheckpoint{
Session: &savedState,
Events: events,
})
}
// GetFormerState iterates backwards over the states, so index == -1 means the last state and so on.
func (s *Session) GetFormerState(index int) *Session {
if index == 0 {
return s
}
index = len(s.stateCheckpoints) + index
if index >= len(s.stateCheckpoints) {
return nil
}
return s.stateCheckpoints[index].Session
}
//
// Game State Functions
//
// GetGameState returns the current game state.
func (s *Session) GetGameState() GameState {
return s.state
}
// SetGameState sets the game state and applies all needed setups for the new state to be valid.
func (s *Session) SetGameState(state GameState) {
s.state = state
switch s.state {
case GameStateFight:
s.SetupFight()
case GameStateRandom:
s.LetTellerDecide()
case GameStateMerchant:
s.SetupMerchant()
}
}
// SetEvent changes the active event, but won't set the game state to EVENT. So this can be used
// to set the next event even before a fight or merchant interaction is over.
func (s *Session) SetEvent(id string) {
s.currentEvent = id
if _, ok := s.resources.Events[id]; ok {
s.eventHistory = append(s.eventHistory, id)
_, _ = s.resources.Events[id].OnEnter.Call(CreateContext("type_id", id))
}
}
// GetEventID returns the id of the current event.
func (s *Session) GetEventID() string {
return s.currentEvent
}
// GetEvent returns the event definition of the current event. Will be nil if no event is present.
// It is not allowed to change the Event data, as this points to the event data created in lua!
func (s *Session) GetEvent() *Event {
if len(s.currentEvent) == 0 {
return nil
}
return s.resources.Events[s.currentEvent]
}
// CleanUpFight resets the fight state.
func (s *Session) CleanUpFight() {
s.currentFight.CurrentPoints = PointsPerRound
s.currentFight.Deck = lo.Shuffle(s.GetPlayer().Cards.ToSlice())
s.currentFight.Hand = []string{}
s.currentFight.Exhausted = []string{}
s.currentFight.Used = []string{}
s.currentFight.Round = 0
}
// SetupFight setups the fight state, which means removing all leftover status effects, cleaning the state
// drawing the initial hand size and trigger the first wave of OnPlayerTurn callbacks.
//
// Additionally, this will create a save file as this is a clean state to save.
func (s *Session) SetupFight() {
s.RemoveAllStatusEffects()
s.CleanUpFight()
s.PlayerDrawCard(DrawSize)
// Trigger OnPlayerTurn callbacks
TriggerCallbackSimple(s, CallbackOnPlayerTurn, TriggerAll, nil)
// Save after each fight
{
save, err := s.GobEncode()
if err != nil {
s.log.Println("Error saving file:", save)
} else {
if err := fs.WriteFile("./session.save", save); err != nil {
s.log.Println("Error saving file:", save)
}
}
}
}
// GetFight returns the fight state. This will return a fight state even if no fight is active at the moment.
func (s *Session) GetFight() FightState {
return s.currentFight
}
// GetStagesCleared returns the amount of stages cleared so far. Each fight represent a stage.
func (s *Session) GetStagesCleared() int {
return s.stagesCleared
}
// FinishPlayerTurn signals that the player is done with its turn. All enemies act now, status effects are
// evaluated, if the fight is over is checked and if not this will advance to the next round and draw cards
// for the player.
func (s *Session) FinishPlayerTurn() {
// Enemies are allowed to act.
s.EnemyTurn()
// Turn over so we remove all dead status effects.
var removeStatus []string
instanceKeys := lo.Keys(s.instances)
for _, guid := range instanceKeys {
switch instance := s.instances[guid].(type) {
case StatusEffectInstance:
// TODO: investigate why this was here
// if instance.Owner == PlayerActorID && instance.RoundEntered == s.currentFight.Round {
// continue
// }
se := s.resources.StatusEffects[instance.TypeID]
// If it can decay we reduce rounds.
if se.Decay != DecayNone {
instance.RoundsLeft -= 1
s.instances[guid] = instance
}
// Enemy StatusEffect OnTurn were already done in EnemyTurn(). We only let
// the player owned ones turn now.
if instance.Owner == PlayerActorID {
if _, err := s.GetStatusEffect(guid).Callbacks[CallbackOnTurn].Call(CreateContext("type_id", instance.TypeID, "guid", guid, "owner", instance.Owner, "round", s.currentFight.Round, "stacks", instance.Stacks)); err != nil {
s.logLuaError(CallbackOnTurn, instance.TypeID, err)
}
}
switch se.Decay {
// Decay stacks by one and re-set rounds if stacks left.
case DecayOne:
if instance.RoundsLeft <= 0 {
instance.Stacks -= 1
instance.RoundsLeft = se.Rounds
s.instances[guid] = instance
if instance.Stacks <= 0 {
removeStatus = append(removeStatus, guid)
}
}
// Remove all.
case DecayAll:
if instance.RoundsLeft <= 0 {
removeStatus = append(removeStatus, guid)
}
}
}
}
for i := range removeStatus {
s.RemoveStatusEffect(removeStatus[i])
}
if s.FinishFight() {
return
}
// Advance to new Round
s.currentFight.CurrentPoints = PointsPerRound
s.currentFight.Round += 1
s.currentFight.Used = append(s.currentFight.Used, s.currentFight.Hand...)
s.currentFight.Hand = []string{}
s.PlayerDrawCard(DrawSize)
// Trigger OnPlayerTurn callbacks
TriggerCallbackSimple(s, CallbackOnPlayerTurn, TriggerAll, nil)
}
// EnemyTurn lets all enemies act. This will also trigger the OnTurn callbacks of all status effects and
// artifacts. If a status effect or artifact returns true, the enemy turn will be skipped. This is used
// for example by the "FEAR" status effect.
func (s *Session) EnemyTurn() {
for k, v := range s.actors {
if k == PlayerActorID || v.IsNone() {
continue
}
if enemy, ok := s.resources.Enemies[v.TypeID]; ok {
skipTurn := false
s.TraverseArtifactsStatus(append(v.Artifacts.ToSlice(), v.StatusEffects.ToSlice()...),
func(instance ArtifactInstance, artifact *Artifact) {
res, err := artifact.Callbacks[CallbackOnTurn].Call(CreateContext("type_id", artifact.ID, "guid", instance.GUID, "owner", instance.Owner, "round", s.GetFightRound()))
if err != nil {
s.logLuaError(CallbackOnTurn, artifact.ID, err)
} else if skip, ok := res.(bool); ok && skip {
skipTurn = true
}
},
func(instance StatusEffectInstance, statusEffect *StatusEffect) {
res, err := statusEffect.Callbacks[CallbackOnTurn].Call(CreateContext("type_id", statusEffect.ID, "guid", instance.GUID, "owner", instance.Owner, "round", s.GetFightRound(), "stacks", instance.Stacks))
if err != nil {
s.logLuaError(CallbackOnTurn, statusEffect.ID, err)
} else if skip, ok := res.(bool); ok && skip {
skipTurn = true
}
},
)
// An effect like FEAR aborted the turn for this actor.
if skipTurn {
continue
}
if _, err := enemy.Callbacks[CallbackOnTurn].Call(CreateContext("type_id", v.TypeID, "guid", k, "round", s.currentFight.Round)); err != nil {
s.logLuaError(CallbackOnTurn, v.TypeID, err)
}
}
}
}
// FinishFight tries to finish the fight. This will return true if the fight is really over.
func (s *Session) FinishFight() bool {
if s.GetOpponentCount(PlayerActorID) == 0 {
s.currentFight.Description = ""
s.stagesCleared += 1
s.CleanUpFight()
s.RemoveAllStatusEffects()
// If an event is already set we switch to it
if len(s.currentEvent) > 0 {
s.SetGameState(GameStateEvent)
} else if s.stagesCleared%10 == 0 {
s.SetEvent("MERCHANT")
} else {
s.SetGameState(GameStateRandom)
}
// Trigger HookNextFightEnd
s.TriggerHooks(HookNextFightEnd)
}
return false
}
// FinishEvent finishes an event with the given choice. If the game state is not in the EVENT state this
// does nothing.
func (s *Session) FinishEvent(choice int) {
if len(s.currentEvent) == 0 || s.state != GameStateEvent {
return
}
s.RemoveNonPlayer()
event := s.resources.Events[s.currentEvent]
s.currentEvent = ""
// If choice was selected and valid we try to use the next game state from the choice.
if choice >= 0 && choice < len(event.Choices) {
nextState, _ := event.Choices[choice].Callback(CreateContext("type_id", event.ID, "choice", choice+1))
// If the choice dictates a new state we take that
if nextState != nil {
if len(nextState.(string)) > 0 {
s.SetGameState(GameState(nextState.(string)))
} else {
s.SetGameState(GameStateRandom)
}
_, _ = event.OnEnd.Call(CreateContext("type_id", event.ID, "choice", choice+1))
return
}
// Otherwise we allow OnEnd to dictate the new state
nextState, _ = event.OnEnd.Call(CreateContext("type_id", event.ID, "choice", choice+1))
if nextState != nil && len(nextState.(string)) > 0 {
s.SetGameState(GameState(nextState.(string)))
} else {
s.SetGameState(GameStateRandom)
}
return
}
nextState, _ := event.OnEnd.Call(CreateContext("type_id", event.ID, "choice", nil))
if nextState != nil && len(nextState.(string)) > 0 {
s.SetGameState(GameState(nextState.(string)))
} else {
s.SetGameState(GameStateRandom)
}
}
// SetFightDescription sets the description of the fight.
func (s *Session) SetFightDescription(description string) {
s.currentFight.Description = description
}
// GetFightRound returns the current round of the fight.
func (s *Session) GetFightRound() int {
return s.currentFight.Round
}
// HadEvent checks if the given event already happened in this run.
func (s *Session) HadEvent(id string) bool {
return lo.Contains(s.eventHistory, id)
}
// HadEvents checks if the given events already happened in this run.
func (s *Session) HadEvents(ids []string) bool {
return lo.Every(s.eventHistory, ids)
}
// HadEventsAny checks if at least one of the given events already happened in this run.
func (s *Session) HadEventsAny(ids []string) bool {
return lo.Some(s.eventHistory, ids)
}
// GetEventHistory returns the ordered list of all events encountered so far.
func (s *Session) GetEventHistory() []string {
return s.eventHistory
}
func (s *Session) GetEventChoiceDescription(i int) string {
event := s.GetEvent()
if event == nil || i < 0 || i >= len(event.Choices) {
return ""
}
if event.Choices[i].DescriptionFn == nil {
return event.Choices[i].Description
}
res, err := event.Choices[i].DescriptionFn.Call(CreateContext("type_id", event.ID, "choice", i))
if err != nil {
s.logLuaError("DescriptionFn", event.ID, err)
return event.Choices[i].Description
}
if res, ok := res.(string); ok {
return res
}
s.logLuaError("DescriptionFn", event.ID, errors.New("didn't return a string"))
return event.Choices[i].Description
}
//
// Merchant
//
// SetupMerchant sets up the merchant, which means generating a new face, text and initial wares.
func (s *Session) SetupMerchant() {
s.merchant.Artifacts = nil
s.merchant.Cards = nil
s.merchant.Face = faces.Global.GenRand()
s.merchant.Text = gen.GetRandom("merchant_lines")
for i := 0; i < 3; i++ {
s.AddMerchantArtifact()
s.AddMerchantCard()
}
}
// LeaveMerchant finishes the merchant state and lets the storyteller decide what to do next.
func (s *Session) LeaveMerchant() {
s.SetGameState(GameStateRandom)
}
// GetMerchant return the merchant state.
func (s *Session) GetMerchant() MerchantState {
return s.merchant
}
// GetMerchantGoldMax returns what the max cost of a artifact or card is that the merchant might offer.
func (s *Session) GetMerchantGoldMax() int {
return 150 + s.stagesCleared*30
}
func (s *Session) PushRandomHistory(id string) {
s.randomHistory = append([]string{id}, s.randomHistory...)
if len(s.randomHistory) > 10 {
s.randomHistory = s.randomHistory[:10]
}
}
// GetRandomArtifact returns the type id of a random artifact with a price lower than the given value.
func (s *Session) GetRandomArtifact(maxGold int) string {
possible := lo.Filter(lo.Values(s.resources.Artifacts), func(item *Artifact, index int) bool {
return item.Price >= 0 && item.Price < maxGold
})
possibleNoDupes := lo.Filter(possible, func(item *Artifact, index int) bool {
return !lo.Contains(s.randomHistory, item.ID)
})
if len(possible) > 0 {
var chosen string
if len(possibleNoDupes) > 0 {
chosen = lo.Shuffle(possibleNoDupes)[0].ID
} else {
chosen = lo.Shuffle(possible)[0].ID
}
s.PushRandomHistory(chosen)
return chosen
}
return ""
}
// GetRandomCard returns the type id of a random card with a price lower than the given value.
func (s *Session) GetRandomCard(maxGold int) string {
possible := lo.Filter(lo.Values(s.resources.Cards), func(item *Card, index int) bool {
return item.Price >= 0 && item.Price < maxGold
})
possibleNoDupes := lo.Filter(possible, func(item *Card, index int) bool {
return !lo.Contains(s.randomHistory, item.ID)
})
if len(possible) > 0 {
var chosen string
if len(possibleNoDupes) > 0 {
chosen = lo.Shuffle(possibleNoDupes)[0].ID
} else {
chosen = lo.Shuffle(possible)[0].ID
}
s.PushRandomHistory(chosen)
return chosen
}
return ""
}
// AddMerchantArtifact adds another artifact to the wares of the merchant.
func (s *Session) AddMerchantArtifact() {
if val := s.GetRandomArtifact(s.GetMerchantGoldMax()); len(val) > 0 {
// Don't add duplicates
if lo.SomeBy(s.GetPlayer().Artifacts.ToSlice(), func(guid string) bool {
a, _ := s.GetArtifact(guid)
return a.ID == val
}) {
return
}
s.merchant.Artifacts = append(s.merchant.Artifacts, val)
}
}
// AddMerchantCard adds another card to the wares of the merchant.
func (s *Session) AddMerchantCard() {
if val := s.GetRandomCard(s.GetMerchantGoldMax()); len(val) > 0 {
s.merchant.Cards = append(s.merchant.Cards, val)
}
}
// PlayerBuyCard buys the card with the given type id. The card needs to be in the wares of the merchant.
func (s *Session) PlayerBuyCard(t string) bool {
if !lo.Contains(s.merchant.Cards, t) {
return false
}
card, _ := s.GetCard(t)
if s.GetPlayer().Gold < card.Price {
return false
}
s.UpdatePlayer(func(actor *Actor) bool {
actor.Gold -= card.Price
return true
})
firstFound := false
s.merchant.Cards = lo.Filter(s.merchant.Cards, func(item string, index int) bool {
if firstFound {
return true
}
isType := item == t
if isType {
firstFound = true
return false
}
return true
})
s.GiveCard(card.ID, PlayerActorID)
return true
}
// PlayerBuyArtifact buys the artifact with the given type id. The artifact needs to be in the wares of the merchant.
func (s *Session) PlayerBuyArtifact(t string) bool {
if !lo.Contains(s.merchant.Artifacts, t) {
return false
}
art, _ := s.GetArtifact(t)
if s.GetPlayer().Gold < art.Price {
return false
}
s.UpdatePlayer(func(actor *Actor) bool {
actor.Gold -= art.Price
return true
})
firstFound := false
s.merchant.Artifacts = lo.Filter(s.merchant.Artifacts, func(item string, index int) bool {
if firstFound {
return true
}
isType := item == t
if isType {
firstFound = true
return false
}
return true
})
s.GiveArtifact(art.ID, PlayerActorID)
return true
}
//
// StoryTeller
//
// ActiveTeller returns the active storyteller. The storyteller is responsible for deciding what enemies or events
// the player will encounter next.
func (s *Session) ActiveTeller() *StoryTeller {
teller := lo.Filter(lo.Values(s.resources.StoryTeller), func(teller *StoryTeller, index int) bool {
res, err := teller.Active(CreateContext("type_id", teller.ID))
if err != nil {
s.logLuaError("Active", teller.ID, err)
return false
}
if val, ok := res.(float64); ok {
return val > 0
}
return false
})
if len(teller) == 0 {
s.log.Printf("No active teller found!")
return nil
}
slices.SortFunc(teller, func(a, b *StoryTeller) bool {
aOrder, _ := a.Active(CreateContext("type_id", a.ID))
bOrder, _ := b.Active(CreateContext("type_id", b.ID))
return aOrder.(float64) > bOrder.(float64)
})
return teller[0]
}
// LetTellerDecide lets the currently active storyteller decide what the next game state will be.
func (s *Session) LetTellerDecide() {
active := s.ActiveTeller()
if active == nil {
s.log.Printf("No active teller found! Can't decide")
return
}
res, err := active.Decide(CreateContext("type_id", active.ID))
if err != nil {
s.logLuaError("Decide", active.ID, err)
return
}
if val, ok := res.(string); ok {
s.SetGameState(GameState(val))
} else {
s.logLuaError("Decide", active.ID, errors.New("return wasn't a game state"))
}
}
//
// Instances
//
// GetInstances returns all instances in the session.
func (s *Session) GetInstances() []string {
return lo.Keys(s.instances)
}
// GetInstance returns an instance by guid. An instance is a CardInstance or ArtifactInstance.
func (s *Session) GetInstance(guid string) any {
return s.instances[guid]
}
// TraverseArtifactsStatus traverses all artifacts and status effects in the session and calls the given functions