我正在写一个简单的tictactoe游戏,每个玩家可以是人类或AI。 因此,为了创建一个新的游戏实例,我做到了这一点,我所做的就是:
Player p1=new RLPlayer(world);
gameInstance = new GameInstance(this, p1, new HumanPlayer(this, world), world);
但是,如果我做了类似
的事情Player p1=new RLPlayer(world);
gameInstance = new GameInstance(this, p1, new HumanPlayer(this, world), world);
Player p2=new RLPlayer(world);
gameInstance = new GameInstance(this, p2, new HumanPlayer(this, world), world);
只玩了1场比赛。我已经想到这是因为对于HumanPlayer来说,它在等待移动输入时停止并且什么都不做,如果之后有代码,它只是跳过它。如何让执行等待输入?或者我的方法完全错了?我有一种感觉。
public class HumanPlayer implements Player {
private GameGUI gameGUI;
private TicTacToeWorld world;
public HumanPlayer(GameGUI gameGUI, TicTacToeWorld world){
this.gameGUI = gameGUI;
this.world = world;
}
public boolean makeMove() {
gameGUI.setMoveInputEnabled(true);
return false;
}
public boolean makeMove(int move){ //false means no move made
if(!world.isMoveLegal(move)) return false;
world.makeMove(move);
gameGUI.setMoveInputEnabled(false);
return true;
}
public void observeMove(){
}
}
仅适用于某些情况。我认为问题出在上面的那个。
public class GameInstance {
private Player[] players;
private TicTacToeWorld world;
private GameGUI gameGUI;
public GameInstance(GameGUI gameGUI, Player player1, Player player2, TicTacToeWorld world){
this.gameGUI = gameGUI;
players = new Player[]{player1,player2};
this.world = world;
runGame();
}
public void runGame(){
gameGUI.updateGUI(world.getWorldState());
while(!world.isGameOver()){
if(!makePlayerMove())return;
gameGUI.updateGUI(world.getWorldState());
}
}
public boolean makePlayerMove(){
int[] state;
state = world.getWorldState();
if(players[(state[0]-1)%2].makeMove()){
players[state[0]%2].observeMove();
return true;
}
else
return false;
}
public void makePlayerMove(int move){ //force move AI OR input human move
int[] state;
state = world.getWorldState();
if( players[(state[0]-1)%2].makeMove(move) ){ //if move was made e.g. AI. Human player would return false;
gameGUI.updateGUI(world.getWorldState());
players[state[0]%2].observeMove();
runGame();
}
}
}
答案 0 :(得分:0)
希望你刚才能想到这一点,但仅仅是为了完整性:
您的游戏必须在GUI上运行事件。具体来说,你的AI移动代码必须运行以响应人类玩家移动的点击 - 在ActionLister的actionPerformed方法的实现中。你需要考虑GUI - 按钮和事物 - 不的游戏流程。或者更确切地说,您已经在GUI事件上重建了适当的游戏流程。