diff --git a/animation.go b/animation.go index 22ce12b..7104a0d 100644 --- a/animation.go +++ b/animation.go @@ -30,6 +30,10 @@ func parseDurations(durations interface{}, frameCount int) []time.Duration { for i := range val { result[i] = val[i] } + case []interface{}: + for i := range val { + result[i] = parseDurationValue(val[i]) + } case map[string]time.Duration: for key, duration := range val { min, max, step := parseInterval(key) @@ -37,12 +41,37 @@ func parseDurations(durations interface{}, frameCount int) []time.Duration { result[i-1] = duration } } + case map[string]interface{}: + for key, duration := range val { + min, max, step := parseInterval(key) + for i := min; i <= max; i += step { + result[i-1] = parseDurationValue(duration) + } + } + case interface{}: + for i := 0; i < frameCount; i++ { + result[i] = parseDurationValue(val) + } default: - log.Fatal(fmt.Sprintf("durations must be time.Duration or []time.Duration or map[string]time.Duration. was %v", durations)) + log.Fatal(fmt.Sprintf("failed to parse durations: type=%T val=%+v", durations, durations)) } return result } +func parseDurationValue(value interface{}) time.Duration { + switch val := value.(type) { + case time.Duration: + return val + case int: + return time.Millisecond * time.Duration(val) + case float64: + return time.Millisecond * time.Duration(val) + default: + log.Fatal(fmt.Sprintf("failed to parse duration value: %+v", value)) + } + return 0 +} + func parseIntervals(durations []time.Duration) ([]time.Duration, time.Duration) { result := []time.Duration{0} var time time.Duration = 0 diff --git a/animation_test.go b/animation_test.go index 2ab993e..423ccfd 100644 --- a/animation_test.go +++ b/animation_test.go @@ -1,6 +1,7 @@ package ganim8_test import ( + "fmt" "image" "testing" "time" @@ -40,18 +41,28 @@ func assertEqualDurations(a, b []time.Duration) bool { func TestParsingDuration(t *testing.T) { var tests = []struct { - name string - args time.Duration + args []interface{} want []time.Duration }{ - {"reads a simple array", 3, []time.Duration{3, 3, 3, 3}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - anim := ganim8.NewAnimation(mockSprite(4), tt.args, ganim8.Nop) + { + args: []interface{}{time.Duration(3)}, + want: []time.Duration{3}, + }, + { + args: []interface{}{int(3)}, + want: []time.Duration{time.Millisecond * 3}, + }, + { + args: []interface{}{float64(3.0)}, + want: []time.Duration{time.Millisecond * 3}, + }, + } + for i, tt := range tests { + t.Run(fmt.Sprintf("testing-%d", i), func(t *testing.T) { + anim := ganim8.NewAnimation(mockSprite(1), tt.args, ganim8.Nop) got := anim.Durations() if assertEqualDurations(got, tt.want) == false { - t.Errorf("%s: got %v; want %v", tt.name, got, tt.want) + t.Errorf("got %v; want %v", got, tt.want) } }) }