-
Notifications
You must be signed in to change notification settings - Fork 2
/
monster.go
executable file
·78 lines (62 loc) · 1.52 KB
/
monster.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
package monster
import (
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/oklog/ulid"
)
type Monster struct {
ID string `jsonapi:"primary,monsters"`
Name string `jsonapi:"attr,name"`
Attack int `jsonapi:"attr,attack"`
Defense int `jsonapi:"attr,defense"`
Type MonsterType `json:"type" jsonapi:"attr,type"`
}
func NewMonster() *Monster {
t := time.Now().UTC()
entropy := rand.New(rand.NewSource(t.UnixNano()))
ID := strings.ToUpper(ulid.MustNew(ulid.Timestamp(t), entropy).String())
return &Monster{ID: ID}
}
type MonsterType string
const (
WaterType MonsterType = "water"
FireType = "fire"
WindType = "wind"
EarthType = "earth"
)
func allowedMonsterTypes() map[string]MonsterType {
return map[string]MonsterType{
string(WaterType): WaterType,
string(FireType): FireType,
string(WindType): WindType,
string(EarthType): EarthType,
}
}
func (t *MonsterType) Check() error {
if _, ok := allowedMonsterTypes()[string(*t)]; !ok {
return fmt.Errorf("The type %s is not supported", string(*t))
}
return nil
}
const (
maxAttack = 999
maxDefense = 999
)
func (m *Monster) Validate() error {
if m.Name == "" {
return errors.New("The name is required")
}
if m.Attack > maxAttack {
return fmt.Errorf("The monster only have max %d attack", maxAttack)
}
if m.Defense > maxDefense {
return fmt.Errorf("The monster only have max % dedense", maxDefense)
}
if err := m.Type.Check(); err != nil {
return err
}
return nil
}