Simplify duplicate command types

This commit is contained in:
Marc Di Luzio 2020-06-06 12:45:45 +01:00
parent 97d3583384
commit e3ce87e964
8 changed files with 28 additions and 56 deletions

View file

@ -1,14 +1,14 @@
package game
import "github.com/google/uuid"
const (
CommandMove = "move"
)
// A command is simply a function that acts on the a given rover in the world
type Command func() error
// Command represends a single command to execute
type Command struct {
Command string `json:"command"`
// CommandMove will move the rover in question
func (w *World) CommandMove(id uuid.UUID, bearing Direction, duration int) Command {
return func() error {
_, err := w.MoveRover(id, bearing, duration)
return err
}
// Used in the move command
Bearing string `json:"bearing,omitempty"`
Duration int `json:"duration,omitempty"`
}

View file

@ -23,8 +23,8 @@ func TestCommand_Move(t *testing.T) {
bearing := North
duration := 1
// Try the move command
moveCommand := world.CommandMove(a, bearing, duration)
assert.NoError(t, world.Execute(moveCommand), "Failed to execute move command")
moveCommand := Command{Command: CommandMove, Bearing: bearing.String(), Duration: duration}
assert.NoError(t, world.Execute(a, moveCommand), "Failed to execute move command")
newpos, err := world.RoverPosition(a)
assert.NoError(t, err, "Failed to set position for rover")

View file

@ -146,10 +146,17 @@ func (w World) RadarFromRover(id uuid.UUID) (RadarDescription, error) {
}
// Execute will run the commands given
func (w *World) Execute(commands ...Command) error {
func (w *World) Execute(id uuid.UUID, commands ...Command) error {
for _, c := range commands {
if err := c(); err != nil {
return err
switch c.Command {
case "move":
if dir, err := DirectionFromString(c.Bearing); err != nil {
return fmt.Errorf("unknown direction: %s", c.Bearing)
} else if _, err := w.MoveRover(id, dir, c.Duration); err != nil {
return err
}
default:
return fmt.Errorf("unknown command: %s", c.Command)
}
}
return nil