2017-12-04 21 views
0

2次元配列を作成し、Xがなる行と列になる2つの数値をランダムに生成する必要があります。私はそれらの4つを配置する必要があり、ユーザーは彼らがどこにいるかを推測するゲームのために隠される必要があります。ランダムに文字列を2次元配列に配置する

char[][]gameBoard= new char [10][10]; 

int row= (int) (Math.random()*9+1); 
int col=(int) (Math.random()*9+1); 


for (int i = 0; i < 10; i++){ 
       for (int j = 0; j <  10; j++){ 

         if(i==row&&j==col) 
          System.out.print("[X]"); 


        else 
         System.out.print("[ ]"); 

       System.out.println(); 
} 
+0

あなたの2D配列はあなたのボード状態のデータ表現で、Viewレイヤの一部である「ゲームのために隠されている必要があります。あなたはそれを個別に処理する必要があります。 – Olian04

答えて

1
const FILLED_FIELD = 'X' 
function placeX(array) { 
    const width = array.length - 1; 
    const height = array[0].length - 1; 
    const targetX = Math.round(Math.random() * width); //Pick a random number between 0, and the width of the array 
    const targetY = Math.round(Math.random() * height); //Pick a random number between 0, and the height of the array 
    if (array[targetX][targetY] === FILLED_FIELD) return placeX(array); //If the choosed place is already occupied, try again 
    array[targetX][targetY] = FILLED_FIELD; //Otherwise fill a field 
} 

技術的にはない完璧な実装ではなく、仕事を行います。 2D配列を関数に渡すだけで、Xがランダムに配置され、Xがすでに配置されている場所は無視されます。