aboutsummaryrefslogtreecommitdiff
path: root/go/game/state.go
blob: 5cab94585834b3108414adf286266f8052646a9c (plain)
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
package game

import (
	"image/color"
	"math/rand"
)

type State struct {
	Decks        []*Deck
	Stores       []*Store
	Map          *Map
	Stack        *Stack
	Hands        []*Hand
	DiscardPiles []*DiscardPile
	Players      []*Player
	Permanents   []Permanent
	Units        []*Unit
	Artifacts    []*Artifact
	Rand         rand.Rand
}

func NewState() *State {
	s := &State{}
	s.Stack = NewStack(s)
	return s
}

func (s *State) AddNewPlayer(name string, deck *Deck, color color.Color) {
	p := NewPlayer(len(s.Players), name, deck, s, color)
	s.Players = append(s.Players, p)
}

func (s *State) AddNewUnit(card string, pos Position, owner *Player) {
	unit := NewUnit(card, s.Map.TileAt(pos), owner)
	s.Permanents = append(s.Permanents, unit)
	s.Units = append(s.Units, unit)
}

func (s *State) removePermanent(p Permanent) {
	for i, perm := range s.Permanents {
		if perm == p {
			s.Permanents[i] = s.Permanents[len(s.Permanents)-1]
			s.Permanents = s.Permanents[:len(s.Permanents)-1]
		}
	}
}

func removePtr[P *Unit | *Artifact](collection []P, ptr P) []P {
	for i, p := range collection {
		if p == ptr {
			collection[i] = collection[len(collection)-1]
			return collection[:len(collection)-1]
		}
	}
	return collection
}

func (s *State) DestroyPermanent(p Permanent) {
	s.removePermanent(p)

	switch p := p.(type) {
	case *Unit:
		s.Units = removePtr(s.Units, p)
	case *Artifact:
		s.Artifacts = removePtr(s.Artifacts, p)
	}
}

func (s *State) AddNewArtifact(card string, pos Position, owner *Player) {
	artifact := NewArtifact(card, s.Map.TileAt(pos), owner)
	s.Permanents = append(s.Permanents, artifact)
	s.Artifacts = append(s.Artifacts, artifact)
}

func (s *State) Fight(p1, p2 Permanent) {
	p1.Fight(p2)
	p2.Fight(p1)
	if p1.IsDestroyed() {
		s.DestroyPermanent(p1)
	}
	if p2.IsDestroyed() {
		s.DestroyPermanent(p2)
	}
}

func (s *State) MoveUnit(u *Unit, t *Tile) {
	u.move(s, t)
}

func (s *State) EnemyUnits(player *Player) []*Unit {
	// TODO: support coop / teams
	enemyUnits := []*Unit{}
	for _, u := range s.Units {
		if u.GetController() != player {
			enemyUnits = append(enemyUnits, u)
		}
	}
	return enemyUnits
}