Let's Learn Python #19 - Finite-State Machines (FSM)

  Переглядів 83,126

Trevor Payne

Trevor Payne

День тому

This week, I cover what a Finite-State Machine (FSM) is, how to plan one out, how to create two different ones and why we use them!
LINK TO AI BOOK:
www.amazon.com/Programming-Gam...
Please leave me a comment or question below! Like and Subscribe to show your support! :D
=========================================
/ tpayneexperience
/ tpaynexperience
/ tpayneexperience
Music by Juto: Link Coming Soon!
=========================================
-- SUPER TUTORIAL LIST!!! --
LLP #25 - UI with PyQt & OpenGL - • Let's Learn Python #25...
LLP #24 - UI with Python, PyQt & Qt Designer - • Let's Learn Python #24...
LLP #23 - Regular Expressions - • Let's Learn Python #23...
LLP #22 - Multithreading - • Let's Learn Python #22...
LLP #21 - Min Max Algorithm - • Let's Learn Python #21...
LLP #20 - A* Algorithm - • Let's Learn Python #20...
LLP #19 - Finite-State Machines (FSM) - • Let's Learn Python #19...
LLP #18 - Factory and @classmethod - • Let's Learn Python #18...
LLP #17 - Type Class Creation, Metaclass - • Let's Learn Python #17...
LLP #16 - Singletons - • Let's Learn Python #16...
LLP #15 - Nesting Functions and Decorators - • Let's Learn Python #15...
LLP #14 - *Args, **Kwargs - • Let's Learn Python #14...
LLP #13 - UML - Unified Modeling Language - • Let's Learn Python #13...
LLP #12 - Abstract Classes, Multiple Inheritance - OOP 3 of 3 - • Let's Learn Python #12...
LLP #11 - Overriding & File Mng. - OOP 2 of 3 - • Let's Learn Python #11...
LLP #10 - Inheritance - OOP 1 of 3 - • Let's Learn Python #10...
LLP #9 - Creating Text Files - • Let's Learn Python #9 ...
LLP #8 of 8 - Classes - • Let's Learn Python - B...
LLP #7 of 8 - Files and User Input - • Let's Learn Python - B...
LLP #6 of 8 - Functions - • Let's Learn Python - B...
LLP #5 - Exception Handling - • Let's Learn Python - B...
LLP #4 - Loops - • Let's Learn Python - B...
LLP #3 - Conditionals, If, Else, Elif - • Let's Learn Python - B...
LLP #2 - Strings, Lists, Tuples and Dictionaries - • Let's Learn Python - B...
LLP #1 - Integers, Floats and Maths - • Let's Learn Python - B...
PLAYLISTS
BASICS - • Let's Learn Python: Ba...
OBJECT ORIENTED PROGRAMMING - • Let's Learn Python: Ob...
SCRIPTING PLAYLIST - • Let's Learn: Python Sc...
=========================================

КОМЕНТАРІ: 95
@pinch-of-salt
@pinch-of-salt 3 роки тому
I love your videos!! I love these advanced programming concepts unlike the other tutorials that keep going on about loops and stuff. Make a python 3 version of these and add more things please! Thank you!
@mag748
@mag748 10 років тому
This is an excellent tutorial. I had to watch the whole thing about 3 times but was able to use your method to create my own functioning FSM in about an hour. I appreciate it!
@TPayneExperience
@TPayneExperience 10 років тому
Right on! You are more than welcome! :)
@VeronikaAlexander
@VeronikaAlexander 8 років тому
Thanks for this video! I have your book, but the link to the source code leads to nowhere... Is there another place where I can download the scripts?
@daydreamer4196
@daydreamer4196 8 років тому
Lovely tutorial Man!! Can we use customised ContextManagers for enter and exit states?
@torylva
@torylva 5 років тому
Hello! Thanks for an really nice tutorial, but I have one question (If you see this) If I would want to have multiple robot maids with unique IDs (As in the book "Programming Game AI by Example"), should I make the Char an actual class and have it produce A unique ID for each? Or should I simply make a Dictionary in the main function that stores each object with a unique ID assigned as the Key? Which would you recommend?
@fuhodev9548
@fuhodev9548 6 років тому
thank you very much, your tutorial is very helpful
@RobbieNerve
@RobbieNerve 6 років тому
Thanks for creating this! It helped me understand the concept better. cheers!
@TPayneExperience
@TPayneExperience 6 років тому
You're very welcome! :D
@sivaa3356
@sivaa3356 10 років тому
Thanks Trevor it was very informative
@steampunk6
@steampunk6 7 років тому
well that's a clear and not so long way to explain how to implement a FSM. thanks a lot
@TPayneExperience
@TPayneExperience 7 років тому
You're very welcome! :)
@calabiyou
@calabiyou 3 роки тому
Thanks. Really inspiring.
@AnuragBisht
@AnuragBisht 8 років тому
Amazing tutorial like your series :) just one thing though in actual state e.g. CleanDishes you don't need __init__.
@billma2168
@billma2168 Рік тому
Hi, thank you for the video. Where can we find the files/codes in the video? Thanks
@abhinabmohanty8689
@abhinabmohanty8689 6 років тому
Hi Trevor, Thanks for this video it was really helpful. As i am building a FSM for one of my projects... I tried implementing the code but i keep getting this error: self.FSM.AddState("Sleep",Sleep(self.FSM)) AttributeError: 'FSM' object has no attribute 'AddState' i checked for spelling but everything seems fine. Could you help please?
@dsdsdsds6501
@dsdsdsds6501 7 років тому
this video was really helpful. thank you!
@TPayneExperience
@TPayneExperience 7 років тому
+Darius Sadighi you're very welcome! :D
@daixtr
@daixtr 9 років тому
why are you not using os.sleep() ?
@FabianoChagas
@FabianoChagas 4 роки тому
Awesome explanation
@assermahmoud8571
@assermahmoud8571 9 років тому
i want to use python in applying LL and LR Grammar. Could you help me ?
@PrathamGupta2408
@PrathamGupta2408 4 роки тому
Can you please share the code you used in the example, please?
@danielchan6572
@danielchan6572 8 років тому
it is a great idea of F.S.M. I had try the codes of robotfsm.py In raspberrypi. it works good , but fail some times after running for five or ten seconds. do you have any idea to fix it? I had checked with the video carefully with/nothing wrong. Thankyou your tutorial!
@Randelprandel
@Randelprandel 8 років тому
Where can i find some good text on State Machines? The tutorial is awesome +Trevor Payne. can someone direct me to some good literature on FSM ? python Novice.
@Jericho99
@Jericho99 3 роки тому
Спасибо за подробный урок! :)
@californiaesnuestra
@californiaesnuestra 8 років тому
In the second example you need to initialize the current state for the RobotMaid, example: r.FSM.SetState("Sleep"), otherwise you will get: AttributeError: 'NoneType' object has no attribute 'Execute'
@jwadaow
@jwadaow 5 років тому
Using python 3?
@bluegiger
@bluegiger 5 років тому
Hey Trevor, I like your video. I have a small bit of feedback: For your actual code, you might find that using a monospaced font makes it easier to read.
@TPayneExperience
@TPayneExperience 5 років тому
Yeah, I’ve learned a lot over the years since I made these videos.
@BBRR442
@BBRR442 Рік тому
from time import clock " line is deprecated
@nabi7600
@nabi7600 4 роки тому
Why so many classes
@alexandrumarianlita3914
@alexandrumarianlita3914 9 років тому
If I have a complex game and I have there for example state for menu, for play, for exit, etc. I need to create a different state machine to handle player states and a different state machine to handle menu state and other things? A game event in a MMORPG can be a state to?
@TPayneExperience
@TPayneExperience 9 років тому
Alexandru Marian Lita Menu/GUI programming is typically handle by the game engine, or at least 60% of it. Look into Unity, it's my fav game engine.
@huseyiner6470
@huseyiner6470 9 років тому
Great work.
@TPayneExperience
@TPayneExperience 9 років тому
Hüseyin ER Thanks! :)
@sofianfadli7910
@sofianfadli7910 6 років тому
Hey,Trevor. I want to ask. Why I just showing "Transitioning..." when I run the code. Where i had created mistakes. Thank you very much from random import randint from time import clock ##======================================= State = type("State", (object,), {}) class LightOn(State): def Execute(self): print ("Light is On!") class LightOff(State): def Execute(self): print ("Light is Off!") ##======================================= class Transition(object): def __init__(self, toState): self.toState = toState def Execute(self): print ("Transitioning...") ##======================================= class SimpleFSM(object): def __init__(self, char): self.char = char self.states = {} self.transitions = {} self.curState = None self.trans = None def SetState(self, stateName): self.curState = self.states[stateName] def Transition(self, transName): self.trans = self.transitions[transName] def Execute(self): if (self.trans): self.trans.Execute() self.SetState(self.trans.toState) self.trans = None self.curState.Execute ##======================================= class Char(object): def __init__(self): self.FSM = SimpleFSM(self) self.LightOn = True ##======================================= if __name__ == "__main__": light = Char() light.FSM.states["On"] = LightOn() light.FSM.states["Off"] = LightOff() light.FSM.transitions["toOn"] = Transition("On") light.FSM.transitions["toOff"] = Transition("Off") light.FSM.SetState("On") for i in range(20): startTime = clock() timeInterval = 1 while (startTime + timeInterval > clock()): pass if (randint(0,2)): if (light.LightOn): light.FSM.Transition("toOff") light.LightOn = False else: light.FSM.Transition("toOn") light.LightOn = True light.FSM.Execute()
@vzuzukin
@vzuzukin 10 років тому
I like your series on Python. This and another called "Python By Osmosis" are the most informative nuggets of Python I've found on UKposts broken down in 5-10 minute bytes. Would you be interested in doing some videos on Rasberry Pi DIY projects in Python?
@TPayneExperience
@TPayneExperience 10 років тому
Currently a little too busy, atm. Thank you, though! :D
@timtruo
@timtruo 8 років тому
Hi Trevor, I have an error with new Python 3.4, and I did try to look for a remedy online but no luck. please help: 'randint' is not defined?
@timtruo
@timtruo 8 років тому
+Cody Kitterman Thanks, from _random import randint: error: cannot import name randint
@tyler24601
@tyler24601 Рік тому
Life saving
@thestarseekers2811
@thestarseekers2811 10 років тому
Is it possible for us to see the full source code? I keep on comparing your lightbulb FSM to the one I made, and keep on running into this error: Traceback (most recent call last): File "C:\Users\Brian_2\Desktop\Lets Learn\lightbulb_FSM.py", line 76, in light.FSM.Transition("toOn") File "C:\Users\Brian_2\Desktop\Lets Learn\lightbulb_FSM.py", line 38, in Transition self.trans = self.transitions[transName] KeyError: 'toOn' Is it just a Python 3.x problem, or is it just a problem in my program?
@thestarseekers2811
@thestarseekers2811 10 років тому
Hmm... It seems to be compiling correctly now - It was a typo. Doesn't seem to be looping now though. I'm going to check the last portion of your code to see if I wrote it correctly.
@TPayneExperience
@TPayneExperience 10 років тому
TheStarSeekers I'm glad you could solve your own problem! You're on your way to becoming a great programmer! :D Looping problems could be caused by indentation, breaks, change the size of what you're looping, and a number of other things. Good luck! :)
@uekhmer2028
@uekhmer2028 6 років тому
Great tutorial, but I have a problem, could you help me please? I keep getting this error: File "C:\Python27\RobotMaid_FSM.py", line 143, in r = RobotMaid() File "C:\Python27\RobotMaid_FSM.py", line 129, in __init__ self.FSM.AddState("Sleep", Sleep(self.FSM)) AttributeError: 'FSM' object has no attribute 'AddState' Please any help would be very much appreciated. Thank you.
@TPayneExperience
@TPayneExperience 6 років тому
looks like you may have misspelled your 'AddState' function within the class.
@SpeciedPower
@SpeciedPower 9 років тому
All mine finishes with is Transitioning... Light is Off! >>
@alialzaedy761
@alialzaedy761 9 років тому
thank u for this information my friend can i ask u something ? Can you explain the simple machine operating system (F S M) ?
@Awesomekid2283
@Awesomekid2283 6 років тому
Could you remind me what the purpose of if __name__ == "__main__" is again?
@TPayneExperience
@TPayneExperience 6 років тому
It says if this is the main python file running, then execute the code below.
@Awesomekid2283
@Awesomekid2283 6 років тому
Since Python does not have a main function, is this the equivalent of a main function in something like C++ or Java?
@jwadaow
@jwadaow 6 років тому
It has a main function it just might not go by that name.
@bhuvankumar2240
@bhuvankumar2240 4 роки тому
ukposts.info/have/v-deo/q6WYqqR_eG12zY0.html
@Yorkane915
@Yorkane915 9 років тому
Please help, I seem to keep getting this error, I'm probably making a really dumb mistake. I have included the code below along with the error. Traceback (most recent call last): File "C:/Users/Karkand/Desktop/Python/Intermediate/FSM/lightbulb_FSM.py", line 65, in light.FSM.SetState("On") AttributeError: 'SimpleFSM' object has no attribute 'SetState' from random import randint from time import clock ##=================================================== State = type("State",(object,),{}) class LightOn(State): def Execute(self): print ("Light is ON") class LightOff(State): def Execute(self): print ("Light is OFF") ##=================================================== class Transition(object): def __init__(self, toState): self.toState = toState def Execute(self): print ("Transitioning...") ##=================================================== class SimpleFSM(object): def __init__(self, char): self.char = char self.states = {} self.transitions = {} self.curState = None self.trans = None def SetState(self, StateName): self.curState = self.states[stateName] def Transition(self, transName): self.trans = self.transitions[transName] def Execute(self): if (self.trans): self.trans.Execute() self.SetState(self.trans.toState) self.trans = None self.curState.Execute() ##=================================================== class Char(object): def __init__(self): self.FSM = SimpleFSM(self) self.LightOn = True ##=================================================== if __name__ == "__main__": light = Char() light.FSM.states["On"] = LightOn() light.FSM.states["Off"] = LightOff() light.FSM.transitions["toOn"] = Transition("On") light.FSM.transitions["toOff"] = Transition("Off") light.FSM.SetState("On") for i in range(20): startTime = clock() timeInterval = 1 while (startTime + timeInterval > clock()): pass if (randint(0, 2)): if (light.LightOn): light.FSM.Transition("toOff") light.LightOn = False else: light.FSM.Transition("toOn") light.LightOn = True light.FSM.Execute()
@o0O0oLOLo0O0o
@o0O0oLOLo0O0o 7 років тому
use double underscores
@dariosipari7881
@dariosipari7881 3 роки тому
also wrong indentation. remove a tab before all the def under __init__. In order to see this type of errors install a good IDE
@AzizSobirov
@AzizSobirov 9 років тому
can any body help me with this error ? light.FSM.transitions["toOn"] = Transition["On"] TypeError: 'type' object has no attribute '__getitem__'
@freddupont3597
@freddupont3597 8 років тому
+Aziz Sobirov light.FSM.transitions["toOn"] = Transition("On")
@siliconeye7447
@siliconeye7447 8 років тому
Why is he capitalizing functions
@jwadaow
@jwadaow 6 років тому
Class
@cjavilaSDSSU
@cjavilaSDSSU 9 років тому
I got this error ==> State=type("State",(object,),[]) TypeError: type() argument 3 must be dict, not list
@TPayneExperience
@TPayneExperience 9 років тому
cj avila Let's look at what the error is telling us.Argumetn 3 must be a dict, not list...So, that would mean replacing the [] with {} in your line of code. State=type("State",(object,),{})
@talwarsunny
@talwarsunny 9 років тому
Thanks Trevor ... This was an excellent presentation... I have some questions though....self.trans.Execute() self.setState(self.trans.toState) in SimpleFSM are not correct since trans is an attribute of Class SimpleFSM and has no method toState or Execute
@uekhmer2028
@uekhmer2028 6 років тому
Could you please help me? I'm having the same problem but not sure where exactly to add the self.Execute() as you said. Do you mean to delete the self.trans.Execute() line in the def Execute(self): portion of code? I did that, but then where exactly do I put the self.Execute() code? Please if you could post the full line of code that you mean it would help me out a lot, I just can't seem to get this to work even though all the code I've typed is the exact same code as shown in the video, which I find odd.
@uekhmer2028
@uekhmer2028 6 років тому
Thank you for your quick reply Heather, this helps a lot :) But I'm a little confused as your code is slightly different to that in the video and some of it seems to be left out or changed. Please would you be able to post the whole code you've used for this, if at all possible? If it doesn't fit in the comments, could you PM me? I really appreciate your help with this, I almost got it working and finally fixed this error but now the program isn't doing anything when it does start and I don't know where I've gone wrong. Thank you :)
@uekhmer2028
@uekhmer2028 6 років тому
My complete code so far is: from random import randint from time import clock ##====================================== class Transition(object): def __init__(self, toState): self.toState = toState def Execute(self): print "Transitioning..." ##====================================== class State(object): def __init__(self, FSM): self.FSM = FSM self.timer = 0 self.startTime = 0 def Enter(self): self.timer = randint(0, 5) self.startTime = int(clock()) def Execute (self): pass def Exit(self): pass class CleanDishes(State): def __init__(self, FSM): super(CleanDishes, self).__init__(FSM) def Enter(self): print "Preparing to clean dishes." super(CleanDishes, self).Enter() def Execute (self): print "Cleaning dishes" if (self.startTime + self.timer
@uekhmer2028
@uekhmer2028 6 років тому
Thank you so much! I'm really sorry to ask you this, as you've already helped me so much, but would you be able to post the code for the RobotMaid example? Again, thank you so much, this already has really helped me out, I am truly so grateful for this!
@uekhmer2028
@uekhmer2028 6 років тому
Thank you sooo much Heather! This really helps me and is so much appreciated :)
@ineedtodrive
@ineedtodrive 6 років тому
if only i knew this earlier. imagine having to programme this in linear fashion...
@TPayneExperience
@TPayneExperience 6 років тому
yep, would be a pain!
@CPlayMasH_Tutoriales
@CPlayMasH_Tutoriales 9 років тому
That code is too much for just transitioning between two states. Two little flags, maybe?
@Randelprandel
@Randelprandel 8 років тому
Fixed it. Haha !
@dvm509
@dvm509 7 років тому
Awesome tutorial but i don't think char is really necessary code can also be done without char
@TPayneExperience
@TPayneExperience 7 років тому
in python, yes. in other languages, not so much. :)
@dvm509
@dvm509 7 років тому
+Trevor Payne (TPayne) why to use in python any significant use?
@TPayneExperience
@TPayneExperience 7 років тому
It's fairly easy to learn, cross platform, free and widely used.
@sntshkmr60
@sntshkmr60 5 років тому
No sarcasm in the starting in this video?
@Randelprandel
@Randelprandel 8 років тому
I get: AttributeError: 'NoneType' object has no attribute 'Execute'
@californiaesnuestra
@californiaesnuestra 8 років тому
+Raj Kamal You need to initialize the current state for the RobotMaid, example: r.FSM.SetState("Sleep") in Main function otherwise you will get: AttributeError: 'NoneType' object has no attribute 'Execute'
@DarthKaujas
@DarthKaujas 8 років тому
just another proof of the flying spaghetti monster R'amen
@RussellTeapot
@RussellTeapot 7 років тому
ALL HAIL SPAGHETTI CODE
@382946rthu
@382946rthu 7 років тому
I think the easiest way is using case statements this is way to complicated.
@jwadaow
@jwadaow 6 років тому
Maybe suggest that to google.
@nubeslocas
@nubeslocas 9 років тому
So many classes for just an ON/OFF switch? I'm not a coder but: isn't this too much code for such a simple idea? A three lines code with a variable and a funtion with an if condition wouldn't be the same?
@TPayneExperience
@TPayneExperience 9 років тому
David Navarrot Gonzalez This example is about a concept and structure, not about the actual example. Once you under stand how to implement it, you can easily program MUCH more complex state machines with ease.
@dew_reddit
@dew_reddit 5 років тому
My mind is about to explode. Too much work.
@TPayneExperience
@TPayneExperience 5 років тому
Ooph
@AFuller2020
@AFuller2020 2 роки тому
Kinda overdid the class thing.
@BBRR442
@BBRR442 Рік тому
suxxx
@Schlumpfpirat
@Schlumpfpirat 10 місяців тому
So many things wrong here… it hurts
Let's Learn Python #20 - A* Algorithm
17:12
Trevor Payne
Переглядів 144 тис.
When Booleans Are Not Enough... State Machines?
21:50
Next Day Video
Переглядів 23 тис.
одни дома // EVA mash @TweetvilleCartoon
01:00
EVA mash
Переглядів 3 млн
And what’s your age? 🥰 @karina-kola
00:12
Andrey Grechka
Переглядів 6 млн
1 класс vs 11 класс (рисунок)
00:37
БЕРТ
Переглядів 3,5 млн
#2 Google Calendar: simple events | Beginner's course
2:26
Paperless Humans
Переглядів 11
A-Level Comp Sci: Finite State Machine
8:21
justAlevel
Переглядів 94 тис.
PGS #01 Python Finite State Machines using Enums
11:44
AtiByte
Переглядів 16 тис.
Let's Learn Python #21 - Min Max Algorithm
13:49
Trevor Payne
Переглядів 75 тис.
Big Tech AI Is A Lie
16:56
Tina Huang
Переглядів 48 тис.
Let's Learn Python - Basics #3 of 8 - Conditionals, If, Else, Elif
9:37
Trevor Payne
Переглядів 224 тис.
Python Tutorial: if __name__ == '__main__'
8:43
Corey Schafer
Переглядів 2 млн
Python Programming
43:16
Derek Banas
Переглядів 5 млн
Can you solve this Oxford admissions question?
8:18
MindYourDecisions
Переглядів 33 тис.
одни дома // EVA mash @TweetvilleCartoon
01:00
EVA mash
Переглядів 3 млн