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

import (
	"golang.org/x/exp/slices"
)

// A WinCondition determines if there are winners using the current game state.
type WinCondition func(*LocalState) []*Player

// DummyWinCondition always return an empty winner slice.
func DummyWinCondition(*LocalState) []*Player {
	return []*Player{}
}

// KingGame reports the winners of a game using kings.
func KingGame(s *LocalState) []*Player {
	foundKings := map[*Player]struct{}{}
	for _, u := range s.Units() {
		if u.card.Name != "King" {
			continue
		}

		foundKings[u.owner] = struct{}{}
	}

	if len(foundKings) == len(s.Players()) {
		return []*Player{}
	}

	loosers := make([]*Player, 0, len(s.Players()))
	copy(loosers, s.Players())
	for p := range foundKings {
		i := slices.Index(loosers, p)
		loosers[i] = loosers[len(loosers)-1]
		loosers = loosers[:len(loosers)-1]
	}

	winners := []*Player{}
	for _, p := range s.Players() {
		if !slices.Contains(loosers, p) {
			winners = append(winners, p)
		}
	}
	return winners
}