FSMMachine

interface FSMNode {  

    enter(): void;  

    exit(): void;  

    tick(interval: number): void;  

    release?(): void; // 可选方法,用于释放资源  

}  

class StateA implements FSMNode {  

    enter() {  

        console.log("Entered State A");  

    }  

    exit() {  

        console.log("Exited State A");  

    }  

    tick(interval: number) {  

        console.log(`State A ticked with interval ${interval}`);  

    }  

    // 假设StateA不需要释放资源  

}  

class StateB implements FSMNode {  

    enter() {  

        console.log("Entered State B");  

    }  

    exit() {  

        console.log("Exited State B");  

    }  

    tick(interval: number) {  

        console.log(`State B ticked with interval ${interval}`);  

    }  

    // 假设StateB也不需要释放资源  

}

class FSMMachine {  

    private currentState: FSMNode | null = null;  

    private states: { [id: string]: FSMNode } = {};  

    addState(id: string, state: FSMNode): void {  

        if (this.states[id]) {  

            throw new Error(`State with ID '${id}' already exists.`);  

        }  

        this.states[id] = state;  

    }  

    setInitialState(id: string): void {  

        if (!this.states[id]) {  

            throw new Error(`State with ID '${id}' does not exist.`);  

        }  

        if (this.currentState) {  

            this.currentState.exit();  

        }  

        this.currentState = this.states[id];  

        this.currentState.enter();  

    }  

    changeState(newId: string): void {  

        if (!this.states[newId]) {  

            throw new Error(`State with ID '${newId}' does not exist.`);  

        }  

        if (this.currentState) {  

            this.currentState.exit();  

        }  

        this.currentState = this.states[newId];  

        this.currentState.enter();  

    }  

    tick(interval: number): void {  

        if (this.currentState) {  

            this.currentState.tick(interval);  

        }  

    }  

    // 假设FSMMachine不需要一个单独的release方法,因为状态可以在需要时单独释放  

}

// 创建状态实例  

const stateA = new StateA();  

const stateB = new StateB();  

// 创建FSMMachine实例并添加状态  

const fsm = new FSMMachine();  

fsm.addState("A", stateA);  

fsm.addState("B", stateB);  

// 设置初始状态  

fsm.setInitialState("A");  

// 更改状态  

fsm.changeState("A");  

// 调用tick方法  

fsm.tick(1000); // 假设这是以毫秒为单位的间隔  

// 如果需要,可以回到状态A  

fsm.changeState("A");  

fsm.tick(500); // 再次调用tick,这次是在状态A中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值