fsm – How do you separate or separate a player / non-player movement, action or behavior in one or more components?

Suppose we use finite state machine. What is the best or cleanest way to organize states?

Assuming I have one StateComponentAll states are here.

MOVEMENT (Parallel) - Can be for player and non player
        (stand, walk, run)
        (forward, backward)
        (left, right)
        (jump, attack)
BEHAVIOR - For non player only
       (patrol, follow, chase, evade)

If we separate the states in MovementState, AttackState and BehaviorState Do you find it cleaner

Python – wildcard matching with DFS and FSM

I'm trying to solve wildcard matching on Leetcode. I found a great solution with the finite state machine. The author creates an FSM and searches with BFS.

I rewrite the solution with the same idea (FSM) but use DFS:

class Solution:

    def isMatch(self, s: str, p: str) -> bool:
        # build the fsm
        fsm = {}
        state = 0
        for i in range(len(p)):
            if p(i) == "*":
                # connect to state itself
                fsm(state, p(i)) = state
                fsm(state, p(i)) = state + 1
                state += 1

        self.accept = state

        self.fsm = fsm
        return self.dfs(s, idx=0, state=0)

    def dfs(self, s: str, idx: int, state: int) -> bool:
        """deep first search through the finite state machine"""
        if idx == len(s):
            # processing string finished
            if state == self.accept:
                return True
                return False

        for value in (s(idx), "*", "?"):
            if (state, value) not in self.fsm:
                # invaild state

            next_state = self.fsm(state, value)
            if self.dfs(s, idx + 1, next_state):
                return True

        return False

We have to iterate the whole string sI think the temporal complexity of DFS and BFS is the same. However, I had timed out for the test case:

  1. Is the temporal complexity of DFS and BFS the same?
  2. Is there something wrong with my code?

Design – Tiered / Grouped / Layered FSM for Development Software?

Well, in the past, while thinking about integrated systems, we've been thinking a lot about FSM and how to design it. It was a good tool to "talk" about complicated systems and create a common baseline.

When we update our application (a kind of webshop that is integrated with many other tools), the "status" of the application sometimes gets "blurry," even though it's difficult to say exactly. As such, I want to apply the techniques that I notice about FSM.

However, as I've used it, FSM has a big "problem": it seems to work very poorly with "layered" systems or subsystems. In a FSM one should always design all states and for each input each state should have a well-defined new state. This works with a few states and some inputs, but what if the number of states gets bigger, for example a dozen or two?

Or if the input matrix also gets bigger with many interconnected settings? I, a user, have a login status, but also a cookie acceptance status, and the items displayed on the page depend on them (as well as other items). Naively, this would mean that I already have many states: a copy for the login status and for each cookie status, multiplied by the number of actual content pages.

Are there any techniques that will make fsm more scalable?

State Machine – Is this the right way to implement a basic FSM in Lua?

Hello SE Code Review Community! I'm trying to implement a basic FSM for the AI ​​in my Roblox game based on my FSM diagram. I show the modules after the diagram and an example, as I use it in my NPC module. I've looked at many FSM implementations in other languages ​​that look simpler because I'm relatively new to Lua. Does this look like a decent start to an FSM implementation? If not, what could I improve and what features are most commonly used in FSM? I'm trying to capture the head of the FSM model because I'm working on AI games and do not want insane amounts of If, Boolean, etc. Many thanks to all who can give me more insight on how I can learn this topic more! I asked this question about StackOverflow, but someone suggested asking for help in this forum.


AI FSM chart

State module:

local state = {}
State .__ Index = State

Function Condition: New ()
local newState = {
Init = function () print ("Init ran") end,
Update = function () print ("refresh") end,
Enter = Function () Print ("Enter") End,
Exit = function () print ("Exiting") end
setmetatable (newState, self)

print ("Created new state")
return newState
The End

country of return

State machine module:

local ReplicatedStorage = game: GetService ("ReplicatedStorage")
local State = required (ReplicatedStorage: WaitForChild ("State"))

local StateMachine = {}
StateMachine .__ Index = StateMachine

StateMachine function: Create ()
local machine = {}
machine.initState = State: New ()
machine.currentState = machine.initState
machine.currentState.Init ()

adjustable (machine, self)
Return the machine
The End

Function StateMachine: Update ()
if self.currentState ~ = null
self.currentState: Update ()
The End
The End

StateMachine function: SetState (state)
assert (state ~ = nil, "can not set a nil state.")
self.currentState: Exit ()
self.currentState = state
self.currentState.Init ()
self.currentState.Enter ()
The End

Return State Machine

So I use my version of a FSM.


newZombie.stateMachine = StateMachine: Create ()

newZombie.idleState = State: New ()
newZombie.idleState.Init = function ()
Print ("Idle Init")
The End
newZombie.idleState.Enter = function ()
Print ("Enter hibernation!")
The End
newZombie.idleState.Update = function ()
print ("Hibernate update!")
If not, then newZombie.target
print ("retrieve destination")
newZombie.target = newZombie: GetNearestTarget ()
The End

If then newZombie.zombieTarget
print ("Destination found")
newZombie.stateMachine: SetState (newZombie.chaseState)
The End
The End

newZombie.chaseState = State: New ()
newZombie.chaseState.Init = function ()
print ("chaseState init")
The End
newZombie.chaseState.Enter = function ()
print ("chaseState enter")
The End
newZombie.chaseState.Update = function ()
print ("chaseState update!")
if newZombie.target then
local direction = (newZombie.target.position - newZombie.rootPart.Position) .Unit * 0.5
local distanceToTarget = (newZombie.target.Position - newZombie.rootPart.Position) .magnitude
local ray = Ray.new (newZombie.rootPart.Position, (newZombie.target.Position - newZombie.rootPart.Position) .Unit * 500)
local ignoreList = {}
for i, v in pairs (ZombiesServerFolder: GetChildren ())
table.insert (ignoreList, v)
The End
Local hit, position, normal = workspace: FindPartOnRayWithIgnoreList (ray, ignoreList)

If not hit.Parent: FindFirstChild ("Humanoid") then
print ("Walk Path")
The End

If distanceToTarget> = MAX_ATTACK_RADIUS, then
newZombie.rootPart.CFrame = newZombie.rootPart.CFrame + direction
newZombie.stateMachine: SetState (newZombie.attackState)
The End
newZombie.stateMachine: SetState (newZombie.idleState)
The End
The End

newZombie.attackState = State: New ()
newZombie.attackState.Init = function ()
print ("attackState init")
The End
newZombie.attackState.Enter = function ()
print ("attackState enter")
The End
newZombie.attackState.Update = function ()
print ("attackState update!")
if newZombie.target then
local distanceToTarget = (newZombie.target.Position - newZombie.rootPart.Position) .magnitude

If distanceToTarget> = MAX_ATTACK_RADIUS, then
newZombie.stateMachine: SetState (newZombie.chaseState)
The End
The End
The End
-------------------------------------------------- -
---- STARTSTAAT ----
-------------------------------------------------- -
newZombie.stateMachine: SetState (newZombie.idleState)
-------------------------------------------------- -

Also in the NPC update function, I update the status update function of the state machines.

if self. state machine then
self.stateMachine: Update ()
The End

Algorithm Analysis – FSM (Finite State Automaton and PDA (Push Down Automaton)

Suppose we have the following language, a number of a and b, followed by three a, followed by a number of a and b

Show how you can create a state machine that accepts the words in the language and rejects words, not in the language. Display the transition rules.

Show how you can create a PDA or press down vending machines that accept the words in the language and reject words, not in the language. Display the transition rules.

How strong is a FSM with sufficient volume (but not infinite)?

Like Turingmachine, but your band is finally. To validate a program, it should have a borderline result if the tape length becomes infinite.

Whether the tape has two ends or is cyclic does not matter, because placing a specific point on a cyclic tape is like a two end tape and ends up running on a two-end tape that is cyclic.

It can also solve its own hold problem by testing the runtime. The conflict program is invalid, there is no result limit.

What is more?

FSM substring by schema

I've been working on a function that returns an FSM that searches a particular word based on the argument of the constructor. The idea was to use these routines as a means of learning regular expressions and possibly implementing a very simple regex system. So I thought that matching a normal string was a good first step in that direction.

This is actually my first "complex" program in Scheme. I learned to program in C, so it was a bit difficult to turn my thinking into a functional approach. Therefore, any comment in my Scheme programming would be very useful.


  1. I know that using lists may not be the most efficient, but I've allowed myself to program more functionally without using vector sets!

  2. If you want to add or fix something, please do not just put the answer. That's not how I learn it. Use code only when needed.

  3. Unfortunately, Emacs uses indent tabs so the formatting may be a bit messy.

Automata in my code are represented as a list of states in which each is described as a pair of the form (a.b), where a is the matching sign and b is the index of the state to which it passes.
If no pair contains a specific character, the invalid status is used by default (index = 0).

the Run machine The function searches a matching substring and returns its offset, or #f is not included in it line,

Thank you for your time!

(define (string-null? s) (= (string-length s) 0))
(define (string-append -c s c) (string-append s (string c)))
(define (string-tail str) (substring str 1 (string-length str)))

;; Is s2 a prefix of s1?
;; [TODO] - Use offset instead of string tail
(define (string prefix? s1 s2)
(cond ((string-null? s2) #t)
((string-null? s1) #f)
((not (char =? (string-ref s2 0))
(string-ref s1 0))) #f)
(otherwise (string prefix? (string end piece s1))
(string-tail s2))))

(Define (start list)
(Define (Iter Start End Acc)
(if (> start end)
(iter start (- end 1) (cons end acc))

(iter start end & # 39; ())

(Define (build automaton needle)
(define (max-suffix-that-is-prefix str)
(cond ((string-null? str) "")
((not (string-prefix? needle str))
(max-suffix-that-is-prefix (string-tail str)))
(otherwise str))

(Define (build transition status string dictionary)
(if (null? dictionary)
(let * ((c (vehicle dictionary)))
(Suffix (max-suffix-that-is-prefix)
(string-append -c state-string c))))
Status string
(if (string-null? suffix)
(cons (cons c (string length suffix)) transitions))
(cdr dictionary)

;; For the last state, no transition is required because it is the final state.
;; "We are done at this point".
(let ((dictionary (string-> list "abcdefghijkmnopqrstuvwxyz"))))
(Map (lambda (n))
(Build transitions (dividing needle 0n) & # 39; ()
(Enumeration 0 (- (needle cord) 1))

;; Takes an automatic and a string and returns the pattern's offset
;; Vending machines were built to look for
(define (automaton string for automatic runners))
(Define (search transition c state transitions)
(cond ((zero? state transitions) 0)
((char =? (caar state transitions) c) (cdar state transitions))
(otherwise (search transition c (cdr state transitions))))

(Define (step state machine size offset)
(cond ((= state machine size))
(- offset machine size))
((> = offset (stringlength)) #f)
(Step (String-Ref String Offset))
(Machine status list-ref))
machine size
(+ Offset 1))))

(Step 0 (length machines) 0)

FSM, Test Script, UIO – Computer Science Stack Exchange

I stay with it. I have the system displayed here: https://imgur.com/a/kcmf8NR

a) Find W and P (UIO)

b) Write the following two scripts with P (UIO) from the previous question:
S1 verification (1, b / y, 4)
S2 check (0, a / y, 2). (2, b / y, 1)

c) A script was run on this IUT that had the same goal as S1. The output was: zero, y, x, x, y, x, x, x
How do you interpret this issue? (FAIL, OK or INCLUDED)

d) A tester receives an error from its test and output: zero, x, x, y.
What can you derive from it?

First, I minimized the system as follows: https://imgur.com/a/5TLcjet
For a) I found the following:
w = {bb}

For S1, I did the following: RN, ay, by, bx, by
S2: RN ay, by, RN, ay, bx, bx

I think S1 is okay, but not sure about S2. I do not know how to check after the first transition if you have actually reached 2.

c) I think it's a mixed mistake. We do not get y as output before you reach the status 1. So it looks like we would choose a / x of 1 instead of b / y, which would be a transmission error + output error (ie mixed).

d) I think they tested (0, b / x, 0) and got another mixed mistake. Not sure.

Can anyone help me?