2013-04-17 2 views
0

전 특정 크기를 기준으로 특정 선박을 배치하는 전함 게임에 종사하고 있습니다. 웬일인지 나는 배를 배치하는 나의 방법이 효과가 없다.2 차원 int 배열 채우기 int [] [] 특정 횟수

는 참고 2 개 방법과 코드가

public class Board { 

    public static final int ID_EMPTY = 0; 
public static final int ID_BATTLESHIP = 1; 
public static final int ID_AIRCRAFT_CARRIER = 2; 
public static final int ID_DESTORYER_1 = 3; 
public static final int ID_DESTORYER_2 = 4; 
public static final int ID_PT_BOAT = 5; 

private static final int ROW_COUNT = 10; 
private static final int COLUMN_COUNT = 10; 

private static final int SHIPS_PER_FLEET = 5; 

private Ship[] fleet; 
private int[][] gridCells; 

private Random randomizer = new Random(); 


public Board() { 

    this.fleet = new Ship[SHIPS_PER_FLEET]; 
    this.gridCells = new int[ROW_COUNT][COLUMN_COUNT]; 
    // Fill the grid cells with OPEN WATER -1s. 
     int i = 0; 
     while (i < ROW_COUNT) { 
      int j = 0; 
      while (j < COLUMN_COUNT) { 
       this.gridCells[i][j] = Ship.openWater; 
       j++; 
      } 

      i++; 
     } 

    } 

/* 
* add a ship to the grid. 
*/ 
    public void placeShips(Ship newShip){ 
      int row = newShip.getRow(); 
       int column = newShip.getColumn(); 
       int orientation = newShip.getOrientation(); 
       int i = 0; 

       // Add the ship to the fleet array. 
       this.fleet[newShip.getshipType()] = newShip; 

       if (orientation == Ship.orientationUp) { 
        while (i < newShip.getShipLenght()) { 
         this.gridCells[row - i][column] = newShip.getshipType(); 
         i++; 
        } 
       } 
       else if (orientation == Ship.orientationRight) { 
        while (i < newShip.getShipLenght()) { 
         this.gridCells[row][column + i] = newShip.getshipType(); 
         i++; 
        } 
       } 
       else if (orientation == Ship.orientationDown) { 
        while (i < newShip.getShipLenght()) { 
         this.gridCells[row + i][column] = newShip.getshipType(); 
         i++; 
        } 
       } 
       else { 
        // Orientation must be LEFT. Only one left =] 
        while (i < newShip.getShipLenght()) { 
         this.gridCells[row][column - i] = newShip.getshipType(); 
         i++; 
        } 
       } 

    } 
public void placeShipsRandomly(){ 


     int [] shipType = {Ship.aircraftCarrier, 
      Ship.battleship, 
      Ship.Destoryer_1, 
      Ship.Destoryer_2, 
      Ship.PtBoat}; 

     int[] shipLength = {5, 4, 3, 3, 2}; 

      int i = 0; 

       do { 
        int row; 
        int col; 
        int orientation; 

        // Randomly generate a row, column, and orientation. 

        row = randomizer.nextInt(ROW_COUNT); 
        col = randomizer.nextInt(COLUMN_COUNT); 
        orientation = randomizer.nextInt(4); 


        boolean bFitsOnBoard = false; 

        // Check to see if the ship fits on the board at the given row and column. 

        int testLength = shipLength[i] -1; 

        if (orientation == Ship.orientationUp) { 
         if (row >= testLength) { 
          bFitsOnBoard = true; 
         } 
        } 
        else if (orientation == Ship.orientationRight) { 
         if (COLUMN_COUNT - col > testLength) { 
          bFitsOnBoard = true; 
         } 
        } 
        else if (orientation == Ship.orientationDown) { 
         if (row - ROW_COUNT > testLength) { 
          bFitsOnBoard = true; 
         } 
        } 
        else if (orientation == Ship.orientationLeft) { 
         if (col >= testLength) { 
          bFitsOnBoard = true; 
         } 

        boolean bHitsOtherShips = false; 

        // Check to see if the ship hits any other ships on the board. 

        if (bFitsOnBoard == true) { 
         int j; 
         if (orientation == Ship.orientationUp) { 
          j = 0; 
          while (j < shipLength[i]) { 
           if (this.gridCells[row - j][col] != Ship.openWater) { 
            bHitsOtherShips = true; 
            break; 
           } 

           j++; 
          } 
         } 
         else if (orientation == Ship.orientationRight) { 
          j = 0; 
          while (j < shipLength[i]) { 
           if (this.gridCells[row][col + j] != Ship.openWater) { 
            bHitsOtherShips = true; 
            break; 
           } 

           j++; 
          } 
         } 
         else if (orientation == Ship.orientationDown) { 
          j = 0; 
          while (j < shipLength[i]) { 
           if (this.gridCells[row + j][col] != Ship.openWater) { 
            bHitsOtherShips = true; 
            break; 
           } 

           j++; 
          } 
         } 
         else if (orientation == Ship.orientationLeft) { 
          j = 0; 
          while (j < shipLength[i]) { 
           if (this.gridCells[row][col - j] != Ship.openWater) { 
            bHitsOtherShips = true; 
            break; 
           } 

           j++; 
          } 
         } 
        } 
        if ((bFitsOnBoard == true) && (bHitsOtherShips == false)) { 
          // Place this ship on the board. 
         Ship newShip = new Ship(shipType[i], orientation, row, col, shipLength[i]); 

         this.placeShips(newShip); 

         // Go on to the next ship. 
         i++; 
          } 
        } 
      } 
       while (i < SHIPS_PER_FLEET); 
} 
    /* 
    * returns the grid cell 
    */ 
    public int[][] getGridCell() 
    { 
    return this.gridCells; 
    } 


} 

그것은이 문제가 (그것은 단지 내가 약에있어이 개 중요한 방법이 있기 때문에 내가 학급 전체를 붙여 줄 생각).

주요 문제는 프로그램의 특정 실행시 범위를 벗어난 오류가 발생하여 10 행에 배를 배치하려고 시도하는 것이므로 int [10] [10] 배열 만 이동하기 때문에 존재하지 않습니다 0시에 시작한 이후 최대 9 시까 지.

둘째 문제는 크기에 따라 배를 배치하려고하지만 모든 배를 배치하고 크기가 3 인 모든 배를 제공하는 것입니다.

예를 들어 이것이 배열 출력이라고 말할 수 있습니다. i는 선박의 길이를 변경 한 때문에 잘못

[0] [0] [3] [3] [3] [0] [0] [0] [0] [0] 
[0] [0] [0] [0] [0] [0] [0] [0] [0] [0] 
[0] [0] [0] [0] [0] [4] [0] [0] [0] [0] 
[0] [0] [0] [0] [0] [4] [0] [0] [0] [0] 
[0] [0] [0] [0] [0] [4] [0] [0] [0] [0] 
[0] [0] [0] [0] [0] [0] [0] [0] [0] [0] 
[0] [0] [0] [0] [1] [1] [1] [0] [0] [0] 
[0] [0] [0] [0] [0] [0] [0] [0] [2] [0] 
[0] [0] [0] [0] [0] [0] [0] [0] [2] [0] 
[0] [0] [0] [0] [0] [0] [0] [0] [2] [0] 

값 int [] shipLength = {5, 4, 3, 3, 2};

따라서 장소 찾기 방법에서 어떤 사이클을 거쳐야하는지에 따라 매번 다른 크기의 배를 배치해야합니다 .3 번째 및 4 번째 배는 디스트로이어이며 크기가 같습니다.

나는 뇌가 얼어 있고 무슨 일이 일어나고 있는지 알 수 없지만 누군가 내게 손을 줄 수 있습니까?

+2

나중에 참조 할 수 있도록 여기에 코드를 붙여 넣으십시오. 링크는 시간이 지남에 따라 죽어서 미래의 독자에게는 쓸모 없게됩니다. 또한 중요한 메소드 중 하나만 붙여 넣었습니다. 문제를 디버그하는 데 도움이되는 두 번째 메소드도 볼 수 있습니까? – torquestomp

+0

문제가 발생한 곳의 전체 수업을 포함하는 것을 잊어 버렸습니다. 질문을 편집하기 위해 편집했습니다. 위의 주석에 붙여 넣은 클래스는 @torquestomp에 링크 된 클래스입니다. 또한 질문을 올바르게 편집했으며 이전 요청에 따라 코드를 질문에 입력했습니다. – JARRRRG

답변

2

당신은 내가 볼 수있는, 두 가지 간단한 오류가 :

else if (orientation == Ship.orientationLeft) { 
    if (col >= testLength) { 
     bFitsOnBoard = true; 
    } 
// ED: Where's the '}'? 

boolean bHitsOtherShips = false; 

// Check to see if the ship hits any other ships on the board. 

이 닫 여기에는 중괄호가 없습니다 밖의 경우 - 코드가 당신이하고있는 생각하고 있지 않습니다. 무작위로 회전하는 배들 == Ship.orientationLeft 만 실제로 충돌 테스트를하고 잠재적으로 배치됩니다. 당신이 배치를 위해 새로운 선박을 선언 할 때,

public Ship(int shipType, int shipLength, int row, int column, int orientation) { 

:하지만

둘째, (! 코멘트에 묻혀 외부 링크되어서는 안된다) 당신의 배() 생성자는이 서명이

Ship newShip = new Ship(shipType[i], orientation, row, col, shipLength[i]); 

orientation 및 shipLength 변수가 서로 바뀝니다. 방향 유형이 Ship.orientationLeft 인 선박 만이 인스턴스화되고 Ship.orientationLeft = 3 이후로 모든 배는 길이가 3입니다.

인덱스가 범위를 벗어나는 것은 쉽습니다. shipLength를 오리엔테이션으로 제출하기 때문에 코드의 초기 경계 확인은 아무 것도 아니므로 쉽게 범위를 벗어날 수 있습니다.

+0

나는 2 시간 일찍 이것을 해줬 으면 좋겠다. 나는 이것을 극복하기 위해 완전히 다른 것을 시도하고있었습니다. 솔직히 정말로 당신의 도움에 감사드립니다. – JARRRRG