将 Lua 有限状态机类从 CS50 游戏转换为 JavaScript

我正在尝试将此 Lua 有限状态机类转换为 JavaScript,但我认为我没有正确实现 change 方法。有人知道如何将此代码转换为 JavaScript 吗?

StateMachine = Class{}

function StateMachine:init(states)
    self.empty = {
        render = function() end,
        update = function() end,
        enter = function() end,
        exit = function() end
    }
    self.states = states or {} -- [name] -> [function that returns states]
    self.current = self.empty
end

function StateMachine:change(stateName, enterParams)
    assert(self.states[stateName]) -- state must exist!
    self.current:exit()
    self.current = self.states[stateName]()
    self.current:enter(enterParams)
end

function StateMachine:update(dt)
    self.current:update(dt)
end

function StateMachine:render()
    self.current:render()
end

这是我想出来的,但我无法正确更改状态。

class StateMachine {
    constructor(states={}){
        this.states = states
        this.empty = {
            render: function(){},
            update: function(){},
            enter: function(){},
            exit: function(){},
        }
        this.current = this.empty
    }

    change(stateName, enterParams){
        this.current.exit()
        this.current =this.states.stateName
        this.current.enter(enterParams)
    }

    update(dt){
        this.current.update(dt)
    }

    render(){
        this.current.render()
        console.log('render')
        console.log(this.states)
    }
}
点赞