~nromdotcom/gemif

ref: 0d4b60a8720279f402503491905f77a2a27b9d1e gemif/pkg/gamemanager/gamestate.go -rw-r--r-- 1.4 KiB
0d4b60a8Norm MacLennan Add a few more tests 1 year, 5 months ago
                                                                                
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
package gamemanager

// GameState contains state information about an active game in progress.
type GameState struct {
	StoryID     string   `json:"si"`
	CurrentRoom string   `json:"cr"`
	Conditions  []string `json:"cn"`
}

// MeetCondition adds a condtition to the list of met conditions if not already met.
func (gs *GameState) MeetCondition(cond string) {
	if index := isInSlice(gs.Conditions, cond); index == -1 {
		gs.Conditions = append(gs.Conditions, cond)
	}
}

// RemoveCondition removes a condtition from the list of met conditions if it exists.
func (gs *GameState) RemoveCondition(cond string) {
	if index := isInSlice(gs.Conditions, cond); index > -1 {
		gs.Conditions[index] = gs.Conditions[len(gs.Conditions)-1]
		gs.Conditions = gs.Conditions[:len(gs.Conditions)-1]
	}
}

// ConditionMet checks to see if a condition has been met.
func (gs GameState) ConditionMet(cond string) bool {
	return isInSlice(gs.Conditions, cond) > -1
}

// UseExit applies an exit's consequences to the GameState
// to produce a new GameState.
func (gs GameState) UseExit(exit Exit) GameState {
	newState := gs
	newState.CurrentRoom = exit.Destination

	if exit.SetCondition != "" {
		newState.MeetCondition(exit.SetCondition)
	}

	if exit.UnsetCondition != "" {
		newState.RemoveCondition(exit.UnsetCondition)
	}

	return newState
}

func isInSlice(slice []string, val string) int {
	for index, item := range slice {
		if item == val {
			return index
		}
	}

	return -1
}