2017-12-04 1 views
0

2D 배열을 만든 다음 X가 될 행과 열이되는 두 개의 숫자를 무작위로 생성해야합니다. 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를 임의로 배치합니다.

관련 문제