2012-02-09 50 views
0

我的程序在輸入每個命令後生成一個新的遊戲板。我只想讓「P」在棋盤和障礙物保持不變的情況下進行更新,直到比賽結束。感謝您的幫助提前,這裏是我的代碼:在每個命令輸入後停止板隨機化

import java.util.Scanner; 
import java.util.Random; 

public class Adventure { 

public static void main(String[] args) { 
    // Create 2D array for game board. 
    char grid[][]= new char[10][10]; 
    Scanner move = new Scanner(System.in); 
    System.out.println("Here is the current game board:"); 
    System.out.println("-------------------------------"); 

    do{ 
     for(int i=0; i<grid.length; i++) {   
      for(int j=0; j<grid.length; j++) { 
       double Random = Math.random(); 
       if(Random <=.05) { 
        grid[i][j]='*'; 
       } 
       else if(Random > .06 && Random <= .15) { 
        grid[i][j]='X'; 
       }   
       else { 
        grid[i][j]='.'; 
       }    
       grid[0][0]='P'; 
       grid[9][9]='T'; 
       System.out.print(grid[i][j]); 
      } 
      System.out.println(""); 
     }    
     System.out.print("Enter your move (U/D/L/R)>");  
     String movePlayer = move.next(); 

     int x=0, y=0; 

     if(movePlayer.equals("R")) { 
      grid[y][x]='.'; 
      x++; 
     } 
     else if(movePlayer.equals("L")) { 
      grid[y][x]='.'; 
      x--; 
     } 
     else if(movePlayer.equals("U")) { 
      grid[y][x]='.'; 
      y++; 
     } 
     else if(movePlayer.equals("D")) { 
      grid[y][x]='.'; 
      y--; 
     } 
     else if(grid[y][x]=='*') { 
      System.out.println("You fell in a pit. Game Over."); 
     } 
     else if(grid[y][x]=='X') { 
      System.out.println("That spot is blocked. Please enter another move."); 
     } 
     else if(grid[y][x]=='T') 
      System.out.println("Congratulations! You've found the treasure!"); 
     else { 

      System.out.print(grid[y][x]); 
     } 
    }while('P' != 'T'); 
} 

}

+0

請所有的愛很酷,把它分解成更小的功能。閱讀你的代碼並找出錯誤會讓你更容易。 – 2012-02-09 18:00:24

+0

另外,''P'!='T'將始終爲真。 – 2012-02-09 18:00:55

+0

你可能想看看你的循環條件。恐怕'P'永遠不會'T'。我沒有寫字母,我只是執行它。 – Shaded 2012-02-09 18:01:37

回答

0

此舉產生do ... while()循環外板代碼:

// generate the board once at the beginning of the program. 
do 
{ 
    // update moves repeatedly until game is over 
} while (<game over perdicate>) 
+0

以上做過這幾行了當我把生成電路板的代碼放在do while循環之外並輸入命令時,電路板不打印。 – 2012-02-09 18:21:35

+0

然後把打印板內循環的代碼... – yurib 2012-02-09 18:25:35