from direct.fsm.FSM import FSM class MyFSM(FSM): def __init__(self): FSM.__init__(self, "MyFSM") def enterState1(self): print("Entering state 1...") def exitState1(self): print("Exiting state 1...") def enterState2(self): print("Entering state 2...") def exitState2(self): print("Exiting state 2...") def transitionToState2(self): self.request("State2") def transitionToState1(self): self.request("State1") fsm = MyFSM() fsm.addState("State1", enterFunc=self.enterState1, exitFunc=self.exitState1) fsm.addState("State2", enterFunc=self.enterState2, exitFunc=self.exitState2) fsm.addTransition("State1", "State2", "transitionToState2") fsm.addTransition("State2", "State1", "transitionToState1") fsm.request("State1")
from direct.fsm.FSM import FSM class MyGame(FSM): def __init__(self): FSM.__init__(self, "MyGame") self.score = 0 def enterPlaying(self): print("Game is now playing...") def exitPlaying(self): print("Game is no longer playing...") def handleInput(self, key): if key == "space": self.score += 10 def update(self, dt): self.score -= dt game = MyGame() game.addState("Playing", enterFunc=game.enterPlaying, exitFunc=game.exitPlaying) game.request("Playing") while game.state == "Playing": key = input("Enter key: ") game.handleInput(key) game.update(0.1)In this example, we define a simple game loop that uses an FSM to manage the game's state. We define a `MyGame` class that extends `FSM` and has two states (`Playing` and `Paused`). The game loop runs continuously as long as the game's state is `Playing`. Inside the loop, we get input from the user, update the game's score, and check for other game events. The `handleInput` and `update` functions are called from inside the loop to handle events and update the game's state. When the user presses the `space` key, the game's score is increased by 10. We also have a `dt` parameter in `update` function which denotes the time elapsed between each frame of the game loop. In conclusion, `direct.fsm` module is a powerful tool for game development in Python that allows developers to easily manage game behavior as transitions between states. It is part of the Panda3D game engine package library.