Skip to content

Commit 38e6476

Browse files
committed
interpreter
1 parent 379e58b commit 38e6476

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

Interpreter/demo.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,18 @@ type IExpression interface {
3333
type Expression struct {
3434
}
3535

36+
// Interpret : 解釋器, 參數多帶一個IExpression 讓繼承的可以使用他的Execute
3637
func (e *Expression) Interpret(context *PlayContext, ie IExpression) {
37-
// fmt.Println("context.Text() ", context.Text())
3838
if len(context.Text()) == 1 {
3939
return
4040
}
4141
playKey := context.Text()[0:1]
4242
context.SetText(context.Text()[2:])
4343
spaceIndex := strings.Index(context.Text(), " ")
44-
// fmt.Println("spaceIndex ", spaceIndex)
4544
if spaceIndex < 0 {
4645
spaceIndex = 0
4746
}
4847
playVal, _ := strconv.Atoi(string(context.Text()[0:spaceIndex]))
49-
// fmt.Println("playVal", string(context.Text()[0]))
5048
context.SetText(context.Text()[strings.Index(context.Text(), " ")+1:])
5149

5250
ie.Execute(playKey, playVal)
@@ -81,7 +79,7 @@ func (n *Note) Execute(key string, val int) {
8179
case "B":
8280
note = "7"
8381
}
84-
fmt.Printf("%s", note)
82+
fmt.Printf("%s ", note)
8583
}
8684

8785
type Scale struct {
@@ -102,5 +100,25 @@ func (s *Scale) Execute(key string, val int) {
102100
case 3:
103101
scale = "高音"
104102
}
105-
fmt.Printf("%s", scale)
103+
fmt.Printf("%s ", scale)
104+
}
105+
106+
type Speed struct {
107+
Expression
108+
}
109+
110+
func NewSpeed() *Speed {
111+
return &Speed{Expression{}}
112+
}
113+
114+
func (s *Speed) Execute(key string, val int) {
115+
var speed string
116+
if val < 500 {
117+
speed = "快速"
118+
} else if val >= 1000 {
119+
speed = "慢速"
120+
} else {
121+
speed = "中速"
122+
}
123+
fmt.Printf("%s ", speed)
106124
}

Interpreter/demo_test.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,21 @@ import (
77

88
func TestDemo(t *testing.T) {
99
context := new(PlayContext)
10-
context.SetText("O 2 E 4 G 4 A 3 E 4 G 4 D 3 E 4 G 4 A 4 O 3 C 1 O 2 A 4 G 1 C 4 E 4 D 3")
11-
// expression := NewScale()
12-
// expression.Interpret(context)
13-
10+
context.SetText("O 2 T 1500 E 4 G 4 A 3 E 4 T 500 G 4 D 3 E 4 G 4 A 4 O 3 C 1 O 2 A 4 G 1 C 4 E 4 D 3")
11+
// 中音 慢速 3 5 6 3 中速 5 2 3 5 6 高音 1 中音 6 5 1 3 2
1412
fmt.Println(context.Text())
1513
for len(context.Text()) > 1 {
1614
str := context.Text()[0:1]
1715
var expression IExpression
1816
switch str {
1917
case "O":
2018
expression = NewScale()
19+
case "T":
20+
expression = NewSpeed()
2121
case "C", "D", "E", "F", "G", "A", "B", "P":
2222
// fmt.Println("dd")
2323
expression = NewNote()
2424
}
25-
// expression := NewScale()
2625
expression.Interpret(context, expression)
2726
}
28-
2927
}

0 commit comments

Comments
 (0)