Last active
February 21, 2021 08:25
-
-
Save adlrocha/239c9a8b86b1126d844f62580784e849 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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