2015-11-09 118 views
-4

所以我的遊戲基本上是最後一個從袋子中挑選出令牌的玩家,但我不知道我該怎麼做。基本上我的代碼是:我如何檢查玩家1或玩家2是否贏了?

if (player1Turn = (player1Turn)?false:true){ 
    System.out.print("Player 2 - choose bag: "); 
    while (!in.hasNextInt()){ 
     System.out.println("I said a bag between 1 and 3: "); 
     in.nextLine(); 
    } 
} 
bag = in.nextInt(); 

然後它檢查他們選擇哪個包以及他們取出多少個令牌。
我不知道用什麼來檢查哪個球員贏了。

+1

你的代碼很混亂(尤其是你在* if語句的條件塊中設置值*的部分)。但總的來說,你會在一些變量或對象或某種類型的跟蹤遊戲的狀態,如果你想檢查遊戲是否結束,你會檢查這些變量或那個對象(在'if'語句中),並看到如果條件得到滿足。但是,在這個程序中跟蹤的內容並不十分清楚。 – David

+0

你能否更好地解釋一下游戲..我很困惑 –

+0

我試圖跟蹤雙方球員的移動次數,然後看看哪一個去最後看誰贏了 – Rhydz97

回答

0

我在想你的包中包含的令牌數量有限。所以,只要袋子空了,你就知道有人贏了。看看下面的代碼。

import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) { 
     System.out.println("Game started"); 

     int tokenCount = 10; 
     int bag = -1; 
     boolean player1Turn = true; 
     String player1 = "Player 1"; 
     String player2 = "Player 2"; 

     Scanner in = new Scanner(System.in); 
     try { 
      while (true) { 
       String currentPlayer = ((player1Turn) ? player1 : player2); 
       System.out.print(currentPlayer +" - choose bag: "); 

       while (true) { 
        while (!in.hasNextInt()) { 
         System.out.println("I said a bag between 1 and 3: "); 
         in.nextLine(); 
        } 
        bag = in.nextInt(); 
        if (bag >= 0 && bag <= 3) { 
         break; 
        } 
        System.out.println("I said a bag between 1 and 3: "); 
       } 

       tokenCount -= bag; 
       if (tokenCount <= 0) { 
        System.out.println(currentPlayer + " has won"); 
        break; 
       } 

       player1Turn = !player1Turn; 
      } 
     } finally { 
      if(in != null) { 
       in.close(); 
      } 
     } 
    } 
}