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
|
package game
import (
"errors"
"fmt"
"slices"
"strconv"
"strings"
"muhq.space/muhqs-game/go/log"
"muhq.space/muhqs-game/go/utils"
)
type (
TargetConstraintFunc func(any) error
TargetDesc struct {
target, req string
}
TargetRequirement struct {
min, max int
}
Target struct {
s *LocalState
desc string
requirement TargetRequirement
constraint TargetConstraintFunc
sel []any
}
Targets struct {
idx int
ts []*Target
}
)
var INVALID_TARGET_DESC = TargetDesc{}
func (t *Target) String() string {
if len(t.sel) == 0 {
return "undecided target"
}
if len(t.sel) == 1 {
return fmt.Sprintf("%v", t.sel[0])
}
s := "["
for _, sel := range t.sel {
s += fmt.Sprintf("%v ", sel)
}
return s[:len(s)-1] + "]"
}
func (t *Targets) String() string {
if len(t.ts) == 0 {
return "no targets"
}
if len(t.ts) == 1 {
return t.ts[0].String()
}
s := "["
for _, t := range t.ts {
s += fmt.Sprintf("%v ", t)
}
return s[:len(s)-1] + "]"
}
func newTargetWithSel(s *LocalState, desc TargetDesc, action Action, sel []any) *Target {
t := &Target{
s: s,
desc: desc.target,
constraint: targetConstraint(desc.target, s, action),
requirement: desc.requirement(),
sel: sel,
}
return t
}
func newTarget(s *LocalState, desc TargetDesc, action Action) *Target {
return newTargetWithSel(s, desc, action, []any{})
}
func newUnitAiTarget(s *LocalState, desc TargetDesc, ai *UnitAI) *Target {
// Dummy action allowing the parsing code to determine the controller of the AI
dummyAction := NewPassPriority(ai.u.controller)
return newTargetWithSel(s, desc, dummyAction, []any{})
}
func newConstraintTarget(s *LocalState, desc TargetDesc, constraint TargetConstraintFunc, action Action,
) *Target {
return &Target{
s: s,
desc: desc.target,
constraint: constraint,
requirement: desc.requirement(),
}
}
func newTargets(targets ...*Target) *Targets {
return &Targets{0, targets}
}
func newTargetDesc(desc string) TargetDesc {
return TargetDesc{desc, "1"}
}
func newPileDropTargets(s *LocalState, a *PileDropAction) *Targets {
pile := a.pile
targets := newTargets()
targets.ts = make([]*Target, 0, len(pile))
desc := newTargetDesc("adjacent tile")
for i, p := range pile {
constraints := parseTileTargetConstraint(desc.target, s, a)
// The selected tile must be available for the individual dropped card
constraints = append(constraints, availableTileConstraint(a, p.Card()))
// The selected tile must be not be previously selected in this action
constraints = append(constraints, noPreviousSelectionConstraint(targets, i))
targets.ts = append(targets.ts, newConstraintTarget(s, desc, conjunction(constraints...), a))
}
return targets
}
func newArtifactMoveTargets(s *LocalState, a *ArtifactMoveAction) *Targets {
targets := newTargets()
targets.ts = make([]*Target, 0, 2)
u := a.Source().(*Unit)
desc := newTargetDesc("available tile")
constraints := []TargetConstraintFunc{tileTargetConstraint}
constraints = append(constraints, availableTileConstraint(a, u.Card()))
constraints = append(constraints, moveConstraint(s, a, u))
moveTarget := newConstraintTarget(s, desc, conjunction(constraints...), a)
targets.ts = append(targets.ts, moveTarget)
constraints = []TargetConstraintFunc{tileTargetConstraint}
constraints = append(constraints, availableTileConstraint(a, a.Artifact.Card()))
constraints = append(constraints, func(t any) error {
c := rangeTargetConstraint(moveTarget.sel[0], 1)
return c(t)
})
constraints = append(constraints, noPreviousSelectionConstraint(targets, 1))
targets.ts = append(targets.ts, newConstraintTarget(s, desc, conjunction(constraints...), a))
return targets
}
func (d *TargetDesc) requirement() TargetRequirement {
switch d.req {
case "?":
return TargetRequirement{0, 1}
case "+":
return TargetRequirement{1, -1}
case "*":
return TargetRequirement{0, -1}
default:
if strings.Contains(d.req, "-") {
tokens := strings.SplitN(d.req, "-", 2)
min, err := strconv.Atoi(tokens[0])
if err != nil {
log.Panicf("failed to parse target requirement %s: %v", d.req, err)
}
max, err := strconv.Atoi(tokens[1])
if err != nil {
log.Panicf("failed to parse target requirement %s: %v", d.req, err)
}
return TargetRequirement{min, max}
}
x, err := strconv.Atoi(d.req)
if err != nil {
log.Panicf("failed to parse target requirement %s: %v", d.req, err)
}
return TargetRequirement{x, x}
}
}
var ErrTargetAlreadySelected = errors.New("already selected")
// AddSelection adds an object as selection to the target.
// If the provided object does not satisfy the target contraint err != nil is returned.
// Selecting the same object multiple times results in an error.
func (t *Target) AddSelection(sel any) (err error) {
if slices.Contains(t.sel, sel) {
return ErrTargetAlreadySelected
}
if err = t.constraint(sel); err == nil {
t.sel = append(t.sel, sel)
}
return
}
func (t *Target) RequireSelection() bool { return len(t.sel) < t.requirement.min }
func (t *Target) HasSelection() bool { return len(t.sel) > 0 }
func (t *Target) AllowSelection() bool {
return (t.requirement.max == -1 || len(t.sel) < t.requirement.max) && len(t.Options()) > 0
}
func (t *Target) ClearSelection() { t.sel = []any{} }
func (t *Target) NoSelection() bool { return len(t.sel) == 0 }
func (t *Target) Selection() []any { return t.sel }
func (t *Target) Options() (options []any) {
candidates := t.candidates()
for _, candidate := range candidates {
err := t.constraint(candidate)
// TODO: Fix this if a single target allows multiple selections of the same object.
if err == nil && slices.Contains(t.sel, candidate) {
err = ErrTargetAlreadySelected
}
if err == nil {
options = append(options, candidate)
} else {
log.Debug("no valid option", "candidate", candidate, "error", err)
}
}
return options
}
// HasOptions reports if there is at least one possible target.
func (t *Target) HasOptions() bool {
for _, candidate := range t.candidates() {
if err := t.constraint(candidate); err == nil {
return true
}
}
return false
}
func (t *Target) CheckSelection(s *LocalState) error {
if t.RequireSelection() {
return errors.New("number of selected targets and required ones does not match")
}
if t.requirement.max != -1 && len(t.sel) > t.requirement.max {
return fmt.Errorf("to many selection %d (%d allowed)", len(t.sel), t.requirement.max)
}
for _, sel := range t.sel {
if err := t.constraint(sel); err != nil {
return fmt.Errorf("selected target %s does not fit its desciption %s: %s",
sel, t.desc, err)
}
}
return nil
}
// AddSelection adds an object as selection to the current target.
func (t *Targets) AddSelection(sel any) error { return t.ts[t.idx].AddSelection(sel) }
func (t *Targets) HasSelections() bool {
for _, t := range t.ts {
if !t.HasSelection() {
return false
}
}
return true
}
func (t *Targets) ClearSelections() {
for _, t := range t.ts {
t.ClearSelection()
}
}
func (t *Targets) NoSelections() bool {
for _, t := range t.ts {
if !t.NoSelection() {
return false
}
}
return true
}
// Options returns the options of the current target.
func (t *Targets) Options() (options []any) { return t.ts[t.idx].Options() }
// HasOptions reports if each target has at least one possible target option.
func (ts *Targets) HasOptions() bool {
for _, t := range ts.ts {
if !t.HasOptions() {
return false
}
}
return true
}
func (t *Targets) Cur() *Target { return t.ts[t.idx] }
func (t *Targets) Next() { t.idx++ }
func (t *Targets) Targets() []*Target { return t.ts }
func (t *Targets) CheckTargets(s *LocalState) error {
log.Debug("Check all sub targets", "targets", t.ts)
for _, target := range t.ts {
if err := target.CheckSelection(s); err != nil {
return err
}
}
return nil
}
// RequireSelection reports if any of the targets require a selection.
func (targets *Targets) RequireSelection() bool {
for _, t := range targets.ts {
if t.RequireSelection() {
return true
}
}
return false
}
// AllowSelection reports if any of the targets allow a selection.
func (targets *Targets) AllowSelection() bool {
for _, t := range targets.ts {
if t.AllowSelection() {
return true
}
}
return false
}
func conjunction(constraints ...TargetConstraintFunc) TargetConstraintFunc {
return func(t any) error {
for _, constraint := range constraints {
if err := constraint(t); err != nil {
return err
}
}
return nil
}
}
func disjunction(constraints ...TargetConstraintFunc) TargetConstraintFunc {
return func(t any) error {
var err error
for _, constraint := range constraints {
if err = constraint(t); err == nil {
return nil
}
}
return err
}
}
func noPreviousSelectionConstraint(targets *Targets, idx int) TargetConstraintFunc {
return func(t any) error {
for i := 0; i < idx && i < targets.idx; i++ {
target := targets.ts[i]
if slices.Contains(target.sel, t) {
return fmt.Errorf("Selection %v already selected for target %d", t, i)
}
}
return nil
}
}
func targetConstraint(desc string, s *LocalState, action Action) TargetConstraintFunc {
if !strings.Contains(desc, " or ") {
return singleTargetConstraint(desc, s, action)
}
descs := strings.Split(desc, " or ")
constraints := make([]TargetConstraintFunc, 0, len(descs))
for _, desc := range descs {
constraints = append(constraints, singleTargetConstraint(desc, s, action))
}
return disjunction(constraints...)
}
func singleTargetConstraint(desc string, s *LocalState, action Action) TargetConstraintFunc {
constraints := []TargetConstraintFunc{}
if strings.Contains(desc, "permanent") {
constraints = append(constraints, parsePermanentTargetConstraint(desc, s, action)...)
} else if strings.Contains(desc, "unit") {
constraints = append(constraints, parseUnitTargetConstraint(desc, s, action)...)
} else if strings.Contains(desc, "artifact") {
constraints = append(constraints, parseArtifactTargetConstraint(desc, s, action)...)
} else if strings.Contains(desc, "tile") {
constraints = append(constraints, parseTileTargetConstraint(desc, s, action)...)
} else if strings.Contains(desc, "card") {
constraints = append(constraints, parseCardTargetConstraint(desc, s, action)...)
// } else if strings.Contains(desc, "action") {
// constraints = append(constraints, parseActionTargetConstraint(desc, s, action)...)
} else if strings.Contains(desc, "spell") {
constraints = append(constraints, parseSpellTargetConstraint(desc, s, action)...)
}
return conjunction(constraints...)
}
func enemyPermanentTargetConstraint(action Action) TargetConstraintFunc {
var sourceController *Player
switch source := action.Source().(type) {
case *Player:
sourceController = source
case Permanent:
sourceController = source.Controller()
default:
log.Panicf("Unhandled source type %T in enemyPermanentTargetConstraint", source)
}
return func(t any) (err error) {
p, _ := t.(Permanent)
if !p.Controller().IsEnemy(sourceController) {
err = fmt.Errorf("Controller %v of target %v is not an enemy of %v",
p.Controller(), t, sourceController)
}
return
}
}
func controlledPermanentTargetConstraint(action Action) TargetConstraintFunc {
var sourceController *Player
switch source := action.Source().(type) {
case *Player:
sourceController = source
case Permanent:
sourceController = source.Controller()
default:
log.Panicf("Unhandled source type %T in enemyPermanentTargetConstraint", source)
}
return func(t any) (err error) {
p, _ := t.(Permanent)
if p.Controller() != sourceController {
err = fmt.Errorf("Controller %v of target %v is %v",
p.Controller(), t, sourceController)
}
return
}
}
var (
ErrTargetNotAttackable = errors.New("not attackable")
ErrTargetOutOfRange = errors.New("not in range")
ErrTargetRangeProtected = errors.New("range protected")
)
func attackableTargetConstraint(action Action) TargetConstraintFunc {
return func(t any) error {
p, _ := t.(Permanent)
if !p.Attackable() {
return ErrTargetNotAttackable
}
if attackAction, ok := action.(*AttackAction); ok {
attacker := attackAction.Source().(*Unit)
ok, _ := attacker.AttackableTile(p.Tile())
if !ok {
return ErrTargetOutOfRange
}
d := DistanceBetweenPermanents(attacker, p)
if d > 1 && p.RangeProtected() {
return ErrTargetRangeProtected
}
}
return nil
}
}
func posFromTileOrPermanent(tileOrPermanent any) Position {
switch obj := tileOrPermanent.(type) {
case Position:
return obj
case *Tile:
return obj.Position
case Permanent:
return TileOrContainingPermTile(obj).Position
default:
log.Panicf("Unhandled source type %T in posFromTileOrPermanent", tileOrPermanent)
return INVALID_POSITION()
}
}
func rangeTargetConstraint(source any, r int) TargetConstraintFunc {
return func(t any) (err error) {
sourcePos := posFromTileOrPermanent(source)
targetPos := posFromTileOrPermanent(t)
if !IsPositionInRange(sourcePos, targetPos, r) {
err = fmt.Errorf("Position %v of target %v not in range %d of source's position %v",
targetPos, t, r, sourcePos)
}
return
}
}
func typeTargetConstraint[T any](typeDesc string) TargetConstraintFunc {
return func(t any) (err error) {
_, ok := t.(T)
if !ok {
err = fmt.Errorf("unexpected target type %T not %s", t, typeDesc)
}
return
}
}
func permanentCardTypeConstraint(f func(CardType) bool) TargetConstraintFunc {
return func(t any) (err error) {
p, ok := t.(Permanent)
if !ok {
err = fmt.Errorf("unexpected target type %T not Permanent", t)
return
}
c := p.Card()
if !f(c.Type) {
err = fmt.Errorf("unexpected target card type %v", c.Type)
return
}
return
}
}
func cardTypeConstraint(cardType CardType) TargetConstraintFunc {
return func(t any) (err error) {
c, ok := t.(*Card)
if !ok {
err = fmt.Errorf("unexpected target type %T not *Card", t)
return
}
if c.Type != cardType {
err = fmt.Errorf("unexpected card type: %v not %v", c.Type, cardType)
return
}
return
}
}
var (
permanentTargetConstraint TargetConstraintFunc = typeTargetConstraint[Permanent]("Permanent")
unitTargetConstraint TargetConstraintFunc = typeTargetConstraint[*Unit]("*Unit")
tileTargetConstraint TargetConstraintFunc = typeTargetConstraint[*Tile]("*Tile")
artifactTargetConstraint TargetConstraintFunc = permanentCardTypeConstraint(CardType.IsArtifact)
cardTargetConstraint TargetConstraintFunc = typeTargetConstraint[*Card]("*Card")
playActionTargetConstraint TargetConstraintFunc = typeTargetConstraint[*PlayAction]("*PlayAction")
spellTargetConstraint TargetConstraintFunc = cardTypeConstraint(CardTypes.Spell)
)
var ErrTargetHasShroud = errors.New("target has shroud")
func shroudedTargetContraint(t any) (err error) {
p := t.(Permanent)
if p.HasEffect("shroud") {
err = ErrTargetHasShroud
}
return
}
func parsePermanentTargetConstraint(desc string, s *LocalState, action Action) []TargetConstraintFunc {
constraints := []TargetConstraintFunc{permanentTargetConstraint, shroudedTargetContraint}
if strings.Contains(desc, "enemy permanent") {
constraints = append(constraints, enemyPermanentTargetConstraint(action))
}
if strings.Contains(desc, "attackable ") {
constraints = append(constraints, attackableTargetConstraint(action))
}
if strings.Contains(desc, " in range ") {
tokens := strings.SplitN(desc, " in range ", 2)
r, err := strconv.Atoi(tokens[1])
if err != nil {
log.Panicf("Invalid range %s in target constraint %s", tokens[1], desc)
}
constraints = append(constraints, rangeTargetConstraint(action.Source(), r))
}
return constraints
}
func parseUnitTargetConstraint(desc string, _ *LocalState, action Action) []TargetConstraintFunc {
constraints := []TargetConstraintFunc{unitTargetConstraint, shroudedTargetContraint}
if strings.Contains(desc, "enemy unit") {
constraints = append(constraints, enemyPermanentTargetConstraint(action))
}
if strings.Contains(desc, "you control") || strings.Contains(desc, "allied unit") {
constraints = append(constraints, controlledPermanentTargetConstraint(action))
}
if strings.Contains(desc, " in range ") {
tokens := strings.SplitN(desc, " in range ", 2)
r, err := strconv.Atoi(tokens[1])
if err != nil {
log.Panicf("Invalid range %s in target constraint %s", tokens[1], desc)
}
constraints = append(constraints, rangeTargetConstraint(action.Source(), r))
}
return constraints
}
func parseArtifactTargetConstraint(constraint string, s *LocalState, action Action) []TargetConstraintFunc {
constraints := []TargetConstraintFunc{artifactTargetConstraint}
return constraints
}
func _relaxedTileTarget(t any) *Tile {
switch t := t.(type) {
case *Tile:
return t
case *Unit:
return t.Tile()
default:
log.Panicf("Not handled target type %T", t)
}
return nil
}
func relaxedTileTarget(action Action, t any) *Tile {
switch action.(type) {
// Some actions allow to also move to Tile occupied by a crewable permanent
case *MoveAction:
return _relaxedTileTarget(t)
case *ArtifactMoveAction:
return _relaxedTileTarget(t)
case *ArtifactSwitchAction:
return _relaxedTileTarget(t)
// Strict case
default:
return t.(*Tile)
}
}
func availableTileConstraint(action Action, card *Card) TargetConstraintFunc {
return func(t any) (err error) {
tile := relaxedTileTarget(action, t)
if card == nil {
log.Panicf("Not implemented availability tile constraint for %T", action)
}
if tile.IsAvailableForCard(card) {
return nil
}
log.Debug("tile not available", "tile", tile, "card", card)
return fmt.Errorf("tile %v is not available for %s", tile, card.Name)
}
}
func moveConstraint(_ *LocalState, action Action, u *Unit) TargetConstraintFunc {
return func(t any) (err error) {
// Some actions allow also unit targets as though they were tiles
tile := relaxedTileTarget(action, t)
if slices.Contains(u.MoveRangeTiles(), tile) {
return nil
}
return fmt.Errorf("tile %v is not in %v's movement range", tile, u)
}
}
var (
ErrTargetWrongTileType = errors.New("wrong tile type")
ErrTargetNotConnectedTile = errors.New("not connected")
)
func parseTileTargetConstraint(desc string, s *LocalState, action Action) []TargetConstraintFunc {
constraints := []TargetConstraintFunc{}
if moveAction, ok := action.(*MoveAction); ok {
u := moveAction.Source().(*Unit)
constraints = append(constraints, moveConstraint(s, action, u))
} else {
constraints = append(constraints, tileTargetConstraint)
}
var player *Player
switch a := action.(type) {
case *PlayAction:
player = a.Source().(*Player)
}
var card *Card
switch a := action.(type) {
case *PlayAction:
card = a.Card
case *MoveAction:
card = a.Card
case *StreetAction:
card = a.Card
case *FullAction:
card = a.Card
}
if strings.Contains(desc, "spawn") {
if player == nil {
log.Panicf("Not implemented spawn tile constraint for %T", action)
}
constraints = append(constraints, func(t any) (err error) {
tile := relaxedTileTarget(action, t)
availableSpawnTiles := s.AvailableSpawnTiles(player, card)
log.Debug("check possible spawn tile", "tile", tile, "spawns", availableSpawnTiles)
if slices.Contains(availableSpawnTiles, tile) {
log.Debug("is spawn tile", "tile", tile)
return nil
}
return fmt.Errorf("tile %v is no spawn tile", tile)
})
}
if strings.Contains(desc, "available") {
constraints = append(constraints, availableTileConstraint(action, card))
}
if strings.Contains(desc, "water") {
constraints = append(constraints, func(t any) (err error) {
tile := t.(*Tile)
if tile.Water {
return nil
}
return fmt.Errorf("tile %v is not a water tile", tile)
})
}
if strings.Contains(desc, "adjacent") {
var origin any
if pda, ok := action.(*PileDropAction); ok {
origin = pda.tile
} else {
origin = action.Source()
}
constraints = append(constraints, rangeTargetConstraint(origin, 1))
}
if strings.Contains(desc, "free") {
constraints = append(constraints, func(t any) (err error) {
tile := t.(*Tile)
if tile.IsFree() {
return nil
}
return fmt.Errorf("tile %v is occupied by %v", tile, tile.Permanent)
})
}
for name := range TileNames {
if strings.Contains(desc, name) {
// FIXME: skip spawn tile type constraint since it colides with available water spawns
if name == "spawn" {
continue
}
tileType := TileNames[name]
if strings.Contains(desc, "connected") {
// Find connected tiles
u := action.Source().(*Unit)
graph := s.Map().generateConnectedMovementRangeGraphFor(u, tileType)
tiles := []*Tile{}
for _, pos := range PositionsInRange(u.Tile().Position, u.Movement.Range, false) {
tile := s.Map().TileAt(pos)
if tile == nil || tile.Type != tileType {
continue
}
_, err := findPathTo(graph, u, pos)
if err != nil {
continue
}
tiles = append(tiles, tile)
}
// Check if tile is connected
constraints = append(constraints, func(t any) (err error) {
tile := t.(*Tile)
if !slices.Contains(tiles, tile) {
err = ErrTargetNotConnectedTile
}
return
})
}
// Tile type constraint
constraints = append(constraints, func(t any) error {
tile := t.(*Tile)
if tile.Type == tileType {
return nil
}
return ErrTargetWrongTileType
})
}
}
return constraints
}
func parseCardTargetConstraint(desc string, s *LocalState, action Action) []TargetConstraintFunc {
constraints := []TargetConstraintFunc{cardTargetConstraint}
player := action.Source().(*Player)
origins := []*Player{player}
originDesc := player.Name + "'s"
if strings.Contains(desc, "opponent") {
originDesc = "a opponent's"
origins = []*Player{}
for _, p := range s.Players() {
if p.IsEnemy(player) {
origins = append(origins, p)
}
}
}
if strings.Contains(desc, "hand") || strings.Contains(desc, "store") ||
strings.Contains(desc, "discard pile") {
if player == nil {
log.Panicf("Not implemented PileOfCards constraint for %T", action)
}
var pocs []PileOfCards
pocDesc := ""
if strings.Contains(desc, "hand") {
pocDesc = "hand"
} else if strings.Contains(desc, "store") {
pocDesc = "store"
} else if strings.Contains(desc, "discard pile") {
pocDesc = "discard pile"
}
// TODO: support player specific constraints
for _, p := range origins {
switch pocDesc {
case "hand":
pocs = append(pocs, p.Hand)
case "store":
if p.gameState.Map().HasStores() {
for _, s := range p.AvailableStores() {
pocs = append(pocs, s)
}
} else {
pocs = append(pocs, p.Store)
}
case "discard pile":
pocs = append(pocs, p.DiscardPile)
}
}
constraints = append(constraints, func(t any) (err error) {
c := t.(*Card)
for _, poc := range pocs {
if poc.Contains(c) {
return nil
}
}
return fmt.Errorf("card %s is not in %s %s", c.Name, originDesc, pocDesc)
})
}
return constraints
}
func playedCardTypeConstraint(cardType CardType) TargetConstraintFunc {
return func(t any) error {
pa := t.(*PlayAction)
if pa.Card.Type != cardType {
return fmt.Errorf("played cardtype %s not %s", pa.Card.Type, cardType)
}
return nil
}
}
func parseSpellTargetConstraint(desc string, s *LocalState, action Action) []TargetConstraintFunc {
var constraints []TargetConstraintFunc
// The target has to be a declared play action
if strings.Contains(desc, "declared") {
constraints = []TargetConstraintFunc{
playActionTargetConstraint,
playedCardTypeConstraint(CardTypes.Spell),
func(t any) error {
pa := t.(*PlayAction)
if !utils.InterfaceSliceContains(utils.TypedSliceToInterfaceSlice(s.stack.Actions), pa) {
return fmt.Errorf("action %s not declared", pa)
}
return nil
},
}
// The target may be any spell card
} else {
constraints = []TargetConstraintFunc{
cardTargetConstraint,
spellTargetConstraint,
}
}
return constraints
}
func (t *Target) candidates() []any {
c := []any{}
if strings.Contains(t.desc, "unit") ||
strings.Contains(t.desc, "artifact") ||
strings.Contains(t.desc, "permanent") {
c = append(c, utils.TypedSliceToInterfaceSlice(t.s.Permanents())...)
}
if strings.Contains(t.desc, "tile") {
c = append(c, utils.TypedSliceToInterfaceSlice(t.s.Map().AllTiles())...)
}
if strings.Contains(t.desc, "card") {
cards := NewPileOfCards()
switch t.desc {
case "hand card":
for _, p := range t.s.Players() {
cards.AddPoc(p.Hand)
}
case "store card":
if t.s.Map().HasStores() {
for _, store := range t.s.Stores() {
cards.AddPoc(store)
}
} else {
for _, p := range t.s.Players() {
cards.AddPoc(p.Store)
}
}
default:
log.Panicf("Unimplemented card options for %s", t.desc)
}
c = append(c, utils.TypedSliceToInterfaceSlice(cards.Cards())...)
}
if strings.Contains(t.desc, "declared") {
c = append(c, utils.TypedSliceToInterfaceSlice(t.s.stack.Actions)...)
}
return c
}
|