2013-06-19 44 views
0

我正在寫一個簡單的tictactoe遊戲,每個玩家可以是人或AI。 所以創造遊戲的新實例,我做到了,使得我要做的就是:如何讓java等待事件?

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

研究觀察者模式... – Thihara

+0

這裏的狀態模式可能會更好。 –

+0

我googled這些模式,但我沒有得到他們如何消除需要讓程序等待。你能給一個簡短的解釋嗎? – kokocrunch

回答

0

希望你前一陣子,想通了這一點,但只是爲了完整性:

您的遊戲流掉的GUI事件。具體而言,您的AI移動代碼必須運行以響應人類玩家進行移動的點擊 - 執行ActionLister的actionPerformed方法。就遊戲流程而言,您需要考慮GUI - 按鈕和事物 - 而不是。或者說,您已經在GUI事件上重建了適當的遊戲流程。