aboutsummaryrefslogtreecommitdiff
path: root/go/game/card.go
blob: d4515676052c162043e61399b9beb58b3f0dbae2 (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
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
package game

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"path"
	"strconv"
	"strings"

	"golang.org/x/exp/slices"
	"gopkg.in/yaml.v3"
)

type CardType int

const (
	undefinedCardType CardType = iota
	unitType
	spellType
	artifactType
	equipmentType
	potionType
	intentionType
)

func (ct CardType) String() string {
	switch ct {
	case undefinedCardType:
		return "undefined"
	case unitType:
		return "unit"
	case spellType:
		return "spell"
	case artifactType:
		return "artifact"
	case equipmentType:
		return "equipment"
	case potionType:
		return "potion"
	case intentionType:
		return "intention"
	}
	log.Panicf("Switch not exhausting %d", ct)
	return ""
}

var CardTypes = struct {
	Unit      CardType
	Spell     CardType
	Artifact  CardType
	Equipment CardType
	Potion    CardType
	Intention CardType
}{
	Unit:      unitType,
	Spell:     spellType,
	Artifact:  artifactType,
	Equipment: equipmentType,
	Potion:    potionType,
	Intention: intentionType,
}

var CardTypeNames = map[string]CardType{
	"unit":      unitType,
	"spell":     spellType,
	"artifact":  artifactType,
	"equipment": equipmentType,
	"potion":    potionType,
	"intention": intentionType,
}

type cardImplementation interface {
	spawnTiles(*State, *Player) []*Tile
	fullActionPrototypes(*Unit) []*FullActionPrototype
	freeActionPrototypes(Permanent) []*FreeActionPrototype
}

// Default implementation of the cardImplementation interface.
//
// Card Implementations should embed this struct to "inherit" the
// default behavior.
type cardImplementationBase struct{}

func (impl *cardImplementationBase) spawnTiles(*State, *Player) []*Tile {
	return nil
}

func (impl *cardImplementationBase) fullActionPrototypes(*Unit) []*FullActionPrototype {
	return nil
}

func (impl *cardImplementationBase) freeActionPrototypes(Permanent) []*FreeActionPrototype {
	return nil
}

// Map of all card implementations
var cardImplementations map[string]cardImplementation

func getCardImplementation(c *Card) cardImplementation {
	if impl, found := cardImplementations[c.Path()]; found {
		return impl
	}

	impl := newParsedCardImplementation(c)
	cardImplementations[c.Path()] = impl
	return impl
}

const (
	CARD_DATA_URL string = "data/cards"
	NOT_BUYABLE   int    = -1 // Maybe this needs to be changed some day to allow more design space
)

type Card struct {
	Name    string
	Set     SetIdentifier
	Type    CardType
	BuyCost int
	Values  map[string]interface{}
	Impl    cardImplementation
}

var cardDefinitions = map[string]map[string][]byte{}

func getCardDefinition(set, cardName string) []byte {
	cardDefinition, found := cardDefinitions[set][cardName]
	if !found {
		cardDefinition = retrieveCardDefinition(path.Join(set, cardName))
		if cardDefinitions[set] == nil {
			cardDefinitions[set] = map[string][]byte{}
		}
		cardDefinitions[set][cardName] = cardDefinition
	}
	return cardDefinition
}

func retrieveCardDefinition(cardPath string) []byte {
	url := PROTOCOL + path.Join(BASE_URL, CARD_DATA_URL, cardPath+".yml")
	log.Printf("loading %s\n", url)
	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	return data
}

func (card *Card) parseDefinition(definition []byte) {
	data := make(map[interface{}]interface{})
	err := yaml.Unmarshal(definition, &data)
	if err != nil {
		log.Fatalf("parsing %s failed with: %v\n", definition, err)
	}

	name, found := data["name"]
	if !found {
		log.Fatalf("no name in card yaml %s\n", definition)
	}
	delete(data, "name")

	switch nameYml := name.(type) {
	case string:
		card.Name = nameYml
	case map[string]interface{}:
		cardName := nameYml["en"]
		card.Name = cardName.(string)
	default:
		log.Fatalf("Unexpected type %T of yml card field 'Name'\n", name)
	}

	t, found := data["type"]
	if !found {
		log.Fatalf("no type in card yaml %s\n", definition)
	}
	delete(data, "type")

	card.Type = CardTypeNames[t.(string)]

	bc, found := data["buy"]
	if found {
		card.BuyCost = bc.(int)
	} else {
		card.BuyCost = NOT_BUYABLE
	}
	delete(data, "buy")

	for k, v := range data {
		card.Values[k.(string)] = v
	}

	card.Impl = getCardImplementation(card)
}

func (card *Card) getCanonicalValues(key string) []string {
	var values []string
	untypedValues, found := card.Values[key]
	if !found {
		return []string{}
	}

	switch typedValues := untypedValues.(type) {
	case map[string]interface{}:
		enValues := typedValues["en"]
		switch typedEnValues := enValues.(type) {
		case string:
			values = []string{typedEnValues}
		case []string:
			values = typedEnValues
		case []interface{}:
			values = []string{}
			for _, v := range typedEnValues {
				values = append(values, v.(string))
			}
		}
	case string:
		values = []string{typedValues}
	case int:
		values = []string{strconv.Itoa(typedValues)}
	case []string:
		values = typedValues
	}

	for i, value := range values {
		values[i] = strings.ToLower(value)
	}

	return values
}

func (card *Card) getEffects() []string {
	return card.getCanonicalValues("effect")
}

func (card *Card) hasEffect(effect string) bool {
	return slices.Contains(card.getEffects(), effect)
}

func (card *Card) getXEffect(effect string) (int, error) {
	for _, e := range card.getEffects() {
		if !strings.Contains(e, effect) {
			continue
		}

		tokens := strings.SplitN(e, " ", 2)
		return strconv.Atoi(tokens[1])
	}
	return 0, fmt.Errorf("Crad %s has no effect %s", card.Name, effect)
}

func (card *Card) hasPlacementConstrain(effect string) bool {
	if slices.Contains(card.getEffects(), effect) {
		return true
	} else if card.Type != CardTypes.Unit {
		return false
	}

	movementDesc := card.getCanonicalValues("movement")[0]
	return strings.Contains(movementDesc, effect)
}

func (card *Card) getAI() string {
	aiDesc := card.getCanonicalValues("ai")
	if len(aiDesc) == 0 {
		return ""
	}
	return strings.Split(aiDesc[0], " ")[0]
}

func NewCard(cardPath string) *Card {
	cardName := path.Base(cardPath)
	set := path.Dir(cardPath)

	cardDefinition := getCardDefinition(set, cardName)

	c := Card{
		Name:    "",
		Set:     SetIdentifierNames[set],
		Type:    undefinedCardType,
		BuyCost: NOT_BUYABLE,
		Values:  map[string]interface{}{},
	}
	c.parseDefinition(cardDefinition)
	return &c
}

func (c *Card) Path() string {
	fileName := strings.ReplaceAll(strings.ToLower(c.Name), " ", "_")
	return path.Join(c.Set.String(), fileName)
}

func (c *Card) IsPermanent() bool {
	return c.Type == CardTypes.Unit ||
		c.Type != CardTypes.Artifact ||
		c.Type != CardTypes.Equipment ||
		c.Type != CardTypes.Potion
}

func (c *Card) IsBuyable() bool {
	return c.BuyCost != NOT_BUYABLE
}

func (c *Card) PlayCosts() int {
	switch c.Type {
	case CardTypes.Unit:
		return c.Values["upkeep"].(int)
	default:
		return c.Values["play"].(int)
	}
}