Skip to content

Instantly share code, notes, and snippets.

@adlrocha

adlrocha/fsm.go

Last active Feb 21, 2021
Embed
What would you like to do?
package main
import (
"fmt"
"github.com/looplab/fsm"
)
type Turnstile struct {
To string
FSM *fsm.FSM
// InternalState for the FSM
Profit int
}
func NewTurnstile(to string) *Turnstile {
t := &Turnstile{
To: to,
}
// List of events
var events = fsm.Events{
{Name: "push", Src: []string{"closed", "open"}, Dst: "closed"},
{Name: "coin", Src: []string{"open", "closed"}, Dst: "open"},
}
// List of callbacks
var callbacks = fsm.Callbacks{
// The function we run when we enter the state
"enter_state": func(e *fsm.Event) { t.enterState(e) },
// Callback to change internal state
"coin": func(e *fsm.Event) { t.Profit++ },
}
// Start new FSM with events and callbacks.
t.FSM = fsm.NewFSM(
"closed",
// Define the transitions
events,
// Callbacks for the state changes
callbacks,
)
return t
}
func (t *Turnstile) enterState(e *fsm.Event) {
fmt.Printf("The turnstile to %s is %s\n", t.To, e.Dst)
}
func main() {
t := NewTurnstile("heaven")
fmt.Println("Enter coin! ")
err := t.FSM.Event("coin")
if err != nil {
fmt.Println(err)
}
fmt.Println("Current profit: ", t.Profit)
fmt.Println("Push!")
err = t.FSM.Event("push")
if err != nil {
fmt.Println(err)
}
fmt.Println("Enter coin! ")
err = t.FSM.Event("coin")
if err != nil {
fmt.Println(err)
}
fmt.Println("Enter coin! ")
err = t.FSM.Event("coin")
if err != nil {
fmt.Println(err)
}
fmt.Println("Current profit: ", t.Profit)
fmt.Println("Push!")
err = t.FSM.Event("push")
if err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment