-
Notifications
You must be signed in to change notification settings - Fork 52
/
settings.go
90 lines (73 loc) · 2.26 KB
/
settings.go
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
package rules
import "strconv"
// Settings contains all settings relevant to a game.
// The settings are stored as raw string values, which should not be accessed
// directly. Calling code should instead use the Int/Bool methods to parse them.
type Settings struct {
rawValues map[string]string
rand Rand
seed int64
}
func NewSettings(params map[string]string) Settings {
rawValues := make(map[string]string, len(params))
// Copy incoming params into a new map
for key, value := range params {
rawValues[key] = value
}
return Settings{
rawValues: rawValues,
}
}
func NewSettingsWithParams(params ...string) Settings {
rawValues := map[string]string{}
for index := 1; index < len(params); index += 2 {
rawValues[params[index-1]] = params[index]
}
return Settings{
rawValues: rawValues,
}
}
// Get a random number generator initialized based on the seed and current turn.
func (settings Settings) GetRand(turn int) Rand {
// Allow overriding the random generator for testing
if settings.rand != nil {
return settings.rand
}
if settings.seed != 0 {
return NewSeedRand(settings.seed + int64(turn))
}
// Default to global random number generator if neither seed or rand are set.
return GlobalRand
}
func (settings Settings) WithRand(rand Rand) Settings {
settings.rand = rand
return settings
}
func (settings Settings) Seed() int64 {
return settings.seed
}
func (settings Settings) WithSeed(seed int64) Settings {
settings.seed = seed
return settings
}
// Bool returns the boolean value for the specified parameter.
// If the parameter doesn't exist, the default value will be returned.
// If the parameter does exist, but is not "true", false will be returned.
func (settings Settings) Bool(paramName string, defaultValue bool) bool {
if val, ok := settings.rawValues[paramName]; ok {
return val == "true"
}
return defaultValue
}
// Int returns the int value for the specified parameter.
// If the parameter doesn't exist, the default value will be returned.
// If the parameter does exist, but is not a valid int, the default value will be returned.
func (settings Settings) Int(paramName string, defaultValue int) int {
if val, ok := settings.rawValues[paramName]; ok {
i, err := strconv.Atoi(val)
if err == nil {
return i
}
}
return defaultValue
}