1. Brief Introduction
Remember, in the object-oriented programming class, I learned finite state machines. Later, when I compiled the principle, I went on finite state machines until I got a formal language automatic machine. It seems that the core solution in an ERP system is also a state machine. However, I was most impressed by the fact that I used finite state machines to implement automatic networking and communication for wireless modules when I was working on hundreds of projects. The state machine is simple, and it is really simple, especially in actual use, but it is not easy to use it. The implementation of the state machine is very simple, but it takes some effort to design the state machine.
This chapter mainly uses two examples to illustrate the use of the state machine in the game. The following is a simple example. The second example mainly involves a lot of code, but there are not many differences. When you want to implement a state machine, it is more valuable to refer to it.
2. Ghost Finite State Machine
There are three possible states for computers to control ghosts: roam, evade, and chase. The initial state is "walk ". Three conversion behaviors: when a player takes a great shot, the trigger "I have changed to Blue" is triggered. When a ghost sees a player, the trigger "see a player" is triggered. When a ghost cannot see a player, "Players not visible" are triggered ". Status Conversion
Related program code:
Switch (currentState ){
Case kRoam:
If (imBlue = true) currentState = kEvade;
Else if (canSeePlayer = true) currentState = kChase;
Else if (canSeePlayer = false) currentState = kRoam;
Case kChase:
If (imBlue = true) currentState = kEvade;
Else if (canSeePlayer = false) currentState = kRoam;
Else if (canSeePlayer = true) currentState = kChase;
Case kEvade:
If (imBlue = true) currentState = kEvade;
Else if (canSeePlayer = true) currentState = kChase;
Else if (canSeePlayer = false) currentState = kRoam;
}
In fact, in the three cases, the Code is the same, as long as you ensure that imBlue first judgment on the line, followed by the judgment of canSeePlayer. Of course, this code is not the most efficient, but it is intuitive and easy to display.
Personal feeling: Generally, the priority State Machine mainly involves two parts. The first part is to do some things in a loop according to the state machine. The second is that some situations have occurred in the process of doing things, as a result, the status changes, affecting the previous loop process.