XFsm - Declarative Finite State Machine Library

Hi,

I’m excited to announce the initial release of XFsm, it’s got a declarative API that allows you to define your states and transition requirements, and also handle complex logic in predictable and robust ways.

See example snippet below–assuming you’re asked to build an online multiplayer tictactoe server;

defmodule TicTacToe do
  use XFsm.Actor
  use XFsm.Machine
  
  import XFsm.Actions

  initial(:x)
  context(%{input: i}, do: context_from_input(i))

  state :x do
    on :move do
      target(:o)
      guard(%{method: :can_move?, params: %{player: :x}})
      action(:make_move)
    end
  end

  state :o do
    on :move do
      target(:x)
      guard(%{method: :can_move?, params: %{player: :o}})
      action(:make_move)
    end
  end

  state :end do
    # You most likely want to persist the game state and terminate the
    # process, assuming you're building an online multiplayer game.
  end

  root do
    always do
      target(:end)
      guard(%{method: :won?, params: %{player: :o}})
      action(assigns(%{winner: :o}))
    end

    always do
      target(:end)
      guard(%{method: :won?, params: %{player: :x}})
      action(assigns(%{winner: :x}))
    end

    always do
      target(:end)
      guard(%{method: :drawn?, params: %{player: :x}})
    end
  end
  
  # ...
end

The complete example can be found in the project repository. Let me know what you think; any contributions are appreciated.

3 Likes