目录

MoonBit Extended FSM

An Enterprise-grade Extended Finite State Machine (FSM) engine for the MoonBit ecosystem.

License MoonBit Wasm Ready Static Validation


🌟 Introduction

State machines are an essential architectural pattern for managing complex business logic, UI component lifecycles, and NPC behaviors in games. moon-fsm brings the power of an Extended State Machine to the MoonBit ecosystem, allowing you to combine deterministic state transitions with dynamic generic context bindings.

✨ Core Features

  • Extended Context: Standard FSMs only track the current state. moon-fsm allows you to bind generic business data (Context) directly into the state machine memory.
  • Static Validator: Automatically detect unreachable or orphaned states via internal graph traversal before the engine even runs.
  • Dynamic Guards: Conditionally allow or block transitions based on the current Context data.
  • Mermaid Export: Visually export your state machine as a Mermaid Diagram natively from MoonBit code!
  • Zero Dependencies: 100% pure MoonBit, fully Wasm ready.

🚀 Quick Start

Installation

moon add Rz-coder8848/moon-fsm

Basic Usage with Context

Here is an example of a simple vending machine that counts coins before unlocking.

let builder : @fsm.Builder[String, String, Int] = @fsm.Builder::new()
  .transition(from="Idle", event="InsertCoin", to="Counting")
  // Guards allow transitions only if condition is true
  .transition_if(from="Counting", event="CheckBalance", to="Unlocked", guard_cond=fn(_s, _e, ctx) { ctx >= 10 })
  .transition_if(from="Counting", event="CheckBalance", to="Idle", guard_cond=fn(_s, _e, ctx) { ctx < 10 })
  .on_enter("Unlocked", fn(state, event, ctx) {
    println("Item Dispensed! Total coins: \{ctx}")
  })

// Build engine starting at Idle with 0 initial coins
let engine = builder.build("Idle", 0)

let _ = engine.send("InsertCoin")

📊 Visualizing your State Machine

You can generate a Mermaid string directly from your builder!

let diagram = @fsm.to_mermaid(builder)
println(diagram)

Renders natively in Markdown tools:

stateDiagram-v2
    Idle --> Counting : InsertCoin
    Counting --> Unlocked : CheckBalance [Guard]
    Counting --> Idle : CheckBalance [Guard]

🏗️ Architecture

Read the Architecture Document and API Reference for deeper insights into the separation of Builder, Validator, and Engine phases.

🤝 Contributing

We welcome community contributions. Please read the Contributing Guidelines before opening a PR.

📜 License

Apache-2.0

关于

本项目为 MoonBit 生态系统提供了一个轻量级、类型安全且高可扩展的有限状态机 (Finite State Machine, FSM) 核心引擎。 在复杂系统工程中(例如 WebAssembly 游戏开发中的 NPC 逻辑控制、UI 组件的复杂状态流转,以及网络协议栈的握手解析),状态机是必不可少的基础设施。然而,目前 MoonBit 官方及第三方包管理平台中尚缺乏通用的状态图控制框架

72.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802047560号