我想在Java中編寫一個簡單的遊戲,使用二維數組爲用戶創建網格點。我已經完成了這一步,並且我已經到了要求用戶選擇其動作的點,但是,在此之後,我想重新打印其舊空間爲空的網格,並使用「o」他們搬到的空間。我不確定如何去重新打印網格,因爲當我第一次打印它時,我使用if語句來告訴循環在哪裏不放點。我會發佈下面的代碼,非常感謝提示!簡單的二維數組java遊戲
import java.util.Scanner;
import java.util.Random;
public class main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] gridArray = new char[10][10];
int randomRow;
int randomCol;
int randomRow2;
int randomCol2;
String moveSelect;
boolean validInput = true;
int min = 0;
int max = 9;
Random tRNG = new Random();
randomRow = tRNG.nextInt(max - min + 1) + min;
randomCol = tRNG.nextInt(max - min + 1) + min;
randomRow2 = tRNG.nextInt(max - min + 1) + min;
randomCol2 = tRNG.nextInt(max - min + 1) + min;
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (gridArray[i][j] != gridArray[randomRow][randomCol] && gridArray[i][j] != gridArray[randomRow2][randomCol2])
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
System.out.println("Enter a movement choice W A S or D");
do{
Scanner keyboard = new Scanner(System.in);
moveSelect = keyboard.nextLine();
if (moveSelect.equals("w"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow+1][randomCol];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if (moveSelect.equals("a"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow][randomCol-1];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if (moveSelect.equals("s"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow-1][randomCol];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if (moveSelect.equals("d"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow][randomCol+1];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else
{
System.out.println("Invalid Entry. Try again.");
validInput = false;
}
} while (validInput == false);
}
}
您可以指定哪些W,A,S,d分別對應? (如上,下,左,右)。此外,您需要進行驗證以確保其移動不會將其移出數組的邊界。 – 2013-03-11 01:53:16
我的錯誤,w = up,a = left,s = down,d = right。我明白你的意思,如果它超出界限並不確定如何處理它,雖然 – user2150807 2013-03-11 01:54:19
如果w是up,s是down的,你有行添加混合,你應該減去去更高的行基於你如何印刷。 – 2013-03-11 01:56:55