-
Java Battleship
Hello, I'm supposed to make a Battleship game. The problem is that, upon clicking play, the game freezes. If I comment out the following section(the place ships section), the program runs fine. Maybe someone could help or even point me in the right direction? Thanks
Code:
public void placeShips()
{
int randCol;
int randRow;
int direct;
for(int ships = 0; ships < NUM_SHIPS; ships++)
{
do
{
randCol = random.nextInt(10);
randRow = random.nextInt(10);
direct = random.nextInt(4);
}while(board[randRow][randCol] != 8 || isValid(ship[ships], randCol, randRow, direct) == false);
}//end for
}//end public void placeShips
public boolean isValid(Ship ship, int col, int row, int direct)
{
int length = ship.getLength();
int direction = direct;
boolean valid = false;
int r = 0, c = 0;
int maxRow = 0, maxCol = 0, minRow = 0, minCol = 0;
switch(direction)
{
case 0:
r = row - length + 1;
minRow = r;
maxRow = r + length - 1;
break;
case 1:
r = row + length - 1;
maxRow = r;
minRow = r - length + 1;
break;
case 2:
c = col - length + 1;
minCol = c;
maxCol = c + length - 1;
break;
case 3:
c = col + length - 1;
maxCol = c;
minCol = c - length + 1;
break;
}//end switch(direction)
for(int rows = minRow; rows <= maxRow; rows++)
{
for(int cols = minCol; cols <= maxCol; cols ++)
{
if(r < 0 || c < 0 || r > 10 || c > 10 || board[rows][cols] != 8)
{
valid = false;
}//end if
else
{
setShips(ship, minRow, maxRow, minCol, maxCol);
valid = true;
}//end else
}//end for cols
}//end for rows
return valid;
}//end isValid
public void setShips(Ship sNum, int startRow, int endRow, int startCol, int endCol)
{
for(int r = startRow; r <= endRow; r++)
{
for(int c = startCol; c <= endCol; c++)
{
board[r][c] = sNum.getType();
}//end for columns
}//end for rows
sNum.setStartRow(startRow);
sNum.setEndRow(endRow);
sNum.setStartCol(startCol);
sNum.setEndCol(endCol);
}//end setShips
-
for { do-while { isValid.for { isValid.for { setShips.for { setShips.for {
thats a lot of nested loops..... no wonder it freezes! can't you structure this is such a way you get what you want from one loop, exit that loop, then take it to another.
also, this is mission-impossible to debug
-
For most of them, they're necessary. Thinks like for(rows){for(columns){}}
That's the best way to go about most of these. I can't think of another way to restructure it.
-
write it in psuedo-code for us, i'll start you off:
Code:
for (each Ship) {
do { something }
while (board[x][y] not-equals 8 OR what? isValid())
}
i'm not sure what your code is meant to do but it looks like you've set your looping conditions horribly wrong, so if you could just write for us in english-words/psuedo-code what your script is meant to do that might help.