过去我使用过手动编码的整数(实际上是一个枚举)。
例如:
// "GAME" application state sub states;
private int GAMESTATE;
private static final int INTRO = 0;
private static final int PLAYING = 1;
private static final int OUTRO = 2;
然后基于 GAMESTATE 的值我可以控制游戏代码的分支。
我创建状态的首选方法是创建一个状态管理器类,它允许在需要时实例化新状态,并且可以控制哪些状态是活动的,以及允许哪些有效状态到状态移动(例如,允许intro
状态到play
状态但不intro
表示胜利state
)
(C++ 的类似示例位于此处,但基于该代码在 java 中实现相同的功能很简单:)
我刚刚找到了一组旧代码,其中包含以下内容(请原谅它大约 10 年前的格式,并且专为最小行数布局而设计):
GameStateManager.java
import java.awt.Image;
import java.awt.Graphics2D;
import java.util.*;
public class GameStateManager {
public static final String EXIT_GAME = "_ExitGame";
private Map gameStates;
private Image defaultImage;
private GameState currentState;
private InputManager inputManager;
private boolean done;
public GameStateManager(InputManager inputManager,
Image defaultImage)
{
this.inputManager = inputManager;
this.defaultImage = defaultImage;
gameStates = new HashMap();
}
public void addState(GameState state) { gameStates.put(state.getName(), state); }
public Iterator getStates() { return gameStates.values().iterator(); }
public void loadAllResources(ResourceManager resourceManager) {
Iterator i = getStates();
while (i.hasNext()) {
GameState gameState = (GameState)i.next();
gameState.loadResources(resourceManager);
}
}
public boolean isDone() { return done; }
public void setState(String name) {
// clean up old state
if (currentState != null) { currentState.stop(); }
inputManager.clearAllMaps();
if (name == EXIT_GAME) { done = true; }
else {
// set new state
currentState = (GameState)gameStates.get(name);
if (currentState != null) { currentState.start(inputManager); }
}
}
public void update(long elapsedTime) {
// if no state, pause a short time
if (currentState == null) {
try {
Thread.sleep(100);
}
catch (InterruptedException ex) { }
}
else {
String nextState = currentState.checkForStateChange();
if (nextState != null) { setState(nextState); }
else { currentState.update(elapsedTime); }
}
}
public void draw(Graphics2D g) {
if (currentState != null) { currentState.draw(g); }
// if no state, draw the default image to the screen
else { g.drawImage(defaultImage, 0, 0, null); }
}
}
GameState.java (接口)
import java.awt.Graphics2D;
public interface GameState {
public String getName();
// Returns the name of a state to change to if this state is
// ready to change to another state, or null otherwise.
public String checkForStateChange();
// Loads any resources for this state. This method is called
// in a background thread before any GameStates are set.
public void loadResources(ResourceManager resourceManager);
// Initializes this state and sets up the input manager
public void start(InputManager inputManager);
// Performs any actions needed to stop this state.
public void stop();
// Updates world, handles input.
public void update(long elapsedTime);
// Draws to the screen.
public void draw(Graphics2D g);
}
您还需要实现 anInputManager
和 a ResourceManager
,但希望这对您有所帮助:)
如果您需要更多信息,请告诉我,因为有几种方法可以做到这一点。