-
Notifications
You must be signed in to change notification settings - Fork 1
/
part_def.go
117 lines (107 loc) · 2.48 KB
/
part_def.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
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
package main
import (
"fmt"
"github.com/ByteArena/box2d"
"github.com/hajimehoshi/ebiten/v2"
"strconv"
"strings"
)
type PartType string
const (
PartTypeBox PartType = "box"
PartTypeCabin PartType = "cab"
PartTypeEngine PartType = "eng"
PartTypeCrane PartType = "crn"
PartTypeLeg PartType = "leg"
PartTypeLegFastening PartType = "lft"
)
type PartParam string
const (
PartParamDir PartParam = "dir"
PartParamPower PartParam = "pow"
PartParamSize PartParam = "size"
PartParamKeys PartParam = "keys"
)
type PartDef interface {
Construct(world *box2d.B2World,
tanker Tank,
ps *ParticleSystem,
shipPos box2d.B2Vec2,
shipSize box2d.B2Vec2,
pos box2d.B2Vec2) Part
}
func ParsePartDef(strP *string) PartDef {
if strP == nil {
return nil
}
str := *strP
tp := strings.ToLower(str[:3])
params := parsePartParams(str[3:])
switch PartType(tp) {
case PartTypeBox:
return &BoxDef{}
case PartTypeCabin:
return &CabinDef{
Dir: params[PartParamDir].AsDirection(),
}
case PartTypeEngine:
size := 1.0
if s, ok := params[PartParamSize]; ok {
size = s.AsFloat()
}
return &EngineDef{
Dir: params[PartParamDir].AsDirection(),
Power: params[PartParamPower].AsFloat(),
Keys: params[PartParamKeys].AsKeys(),
Size: size,
}
case PartTypeCrane:
return &CraneDef{
Dir: params[PartParamDir].AsDirection(),
}
case PartTypeLeg:
return &LegDef{
Dir: params[PartParamDir].AsDirection(),
}
case PartTypeLegFastening:
return &LegFasteningDef{
Dir: params[PartParamDir].AsDirection(),
}
default:
checkErr(fmt.Errorf("unknown part type %v", tp))
return nil
}
}
type paramVal string
func (v paramVal) AsDirection() Direction {
return Direction(v)
}
func (v paramVal) AsFloat() float64 {
result, err := strconv.ParseFloat(string(v), 64)
checkErr(err)
return result
}
func (v paramVal) AsKeys() Keys {
result := make(Keys)
for _, elem := range strings.Split(string(v), ",") {
k, err := strconv.Atoi(elem)
checkErr(err)
result[ebiten.Key(k)] = struct{}{}
}
return result
}
func parsePartParams(str string) map[PartParam]paramVal {
result := make(map[PartParam]paramVal)
params := strings.Split(str, ";")
if len(params) == 1 && params[0] == "" {
return result
}
for _, param := range params {
kv := strings.Split(param, "=")
if len(kv) != 2 {
checkErr(fmt.Errorf("bad part param %v", str))
}
result[PartParam(strings.Trim(kv[0], " "))] = paramVal(strings.Trim(kv[1], " "))
}
return result
}