58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
package westworldwithmessaging
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand"
|
|
"sync"
|
|
)
|
|
|
|
// doHousework is Elsa's everyday default state - the singleton
|
|
// pattern is the same one used throughout this package.
|
|
type doHousework struct{}
|
|
|
|
var (
|
|
doHouseworkInstance *doHousework
|
|
doHouseworkOnce sync.Once
|
|
)
|
|
|
|
// DoHousework is the Go stand-in for "DoHousework::Instance()".
|
|
func DoHousework() *doHousework {
|
|
doHouseworkOnce.Do(func() {
|
|
doHouseworkInstance = &doHousework{}
|
|
})
|
|
return doHouseworkInstance
|
|
}
|
|
|
|
var _ State[Elsa] = (*doHousework)(nil)
|
|
|
|
// chores is our own small stand-in for the book's actual chore list
|
|
// - it only ever showed two examples in its sample output ("Moppin'
|
|
// the floor", "Makin' the bed"), so that's exactly what's reused
|
|
// here. One gets picked at random each tick.
|
|
var chores = []string{
|
|
"Moppin' the floor",
|
|
"Makin' the bed",
|
|
}
|
|
|
|
// Enter does nothing - the book's sample output never shows a
|
|
// message when Elsa starts doing housework, only while she's doing
|
|
// it (Execute) and when she leaves the bathroom back into it.
|
|
func (s *doHousework) Enter(e *Elsa) {}
|
|
|
|
// Execute announces one randomly chosen chore per tick.
|
|
func (s *doHousework) Execute(e *Elsa) {
|
|
fmt.Printf("\n%s: %s", GetNameOfEntity(e.ID()), chores[rand.Intn(len(chores))])
|
|
}
|
|
|
|
// Exit does nothing, for the same reason as Enter.
|
|
func (s *doHousework) Exit(e *Elsa) {}
|
|
|
|
// OnMessage is required now that State[T] includes it, so that every
|
|
// state satisfies the interface. This state doesn't do anything
|
|
// special with messages yet - false means "I didn't handle it,"
|
|
// which lets StateMachine.HandleMessage fall through and try the
|
|
// global state instead.
|
|
func (s *doHousework) OnMessage(e *Elsa, msg Telegram) bool {
|
|
return false
|
|
}
|