The state transition in game design is a very important and complex part. I saw a public void keyPressed (int keyCode) with nearly 2000 lines of code in the middle when porting a few days ago, in this case, lengthy Code does not conform to OO's thinking. What is more serious is that it will disturb our program ideas. In the past two days, the State mode was used to convert the status of a j2_game. As it was just an example of an experiment, only the conversion of the Start menu and help was performed, adding other statuses under this framework is actually very simple.
Currently, there are only two States in the DEMO. The keyPressed and paint functions are different in the two states. We use the state mode to implement the keyPressed and paint functions in various States.
First, define the abstract State interface, which specifies the behavior of keyPressed and paint.
Public interface State {
Public void onKeyPressed (int keyCode, StateManage _ current );
Public void paint (Graphics g );
}
State interface keyPressed and painting methods. We implement two sub-classes: HelpMenuState and MainMenuState, which respectively indicate the status of the main menu and HELP menu, and implement the specific onKeyPressed and painting methods:
Public class MainMenuState implements State {
/** Omitting the Declaration and initial modification of variables */
Public void onKeyPressed (int keyCode, StateManage _ current ){
Switch (whichMenu ){
Case 0:
MainMenuKeyPressed (keyCode, _ current );
Break;
Case 1:
Break;
}
}
Private void mainMenuKeyPressed (int keyCode, StateManage _ current ){
Switch (keyCode ){
Case 1: // KEY_UP = 1;