BattleShip game ship on top of ship
Hi!
i am working on a text version battleship game, but my problem is the ships that are generated by the computer are placed one on top of another.
Does anybody have any solutions on how this can be fixed? :confused:
My code:
Code:
import java.util.Random;
public class BattleShip
{
public String[][] grid;
private int[] takenX = new int[100];
private int[] takenY = new int[100];
private int length;
private int width;
public BattleShip(int l, int w)
{
grid = new String[l][w];
length = l;
width = w;
initGrid();
}
public void initGrid()
{
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[r].length; c++)
{
grid[r][c] = "O";
}
}
public void printGrid()
{
String g = "";
g += " ";
for (int i = 1; i <= (grid.length); i++)
{
g += (i + " ");
}
g += "\n\n";
for (int r = 0; r < grid.length; r++)
{
if (r >= 9)
g += ((r + 1) + " ");
else
g += ((r + 1) + " ");
for (int c = 0; c < grid[r].length; c++)
{
g += ((grid[r][c]) + " ");
}
g += "\n";
}
System.out.println(g);
}
public boolean isValidLocation(int l, int h)
{
if ((grid[l][h]).equals("O"))
return false;
else
return true;
}
public void placeShip(int l)
{
Random rand = new Random();
int x = rand.nextInt(10 - (l - 1));
int y = rand.nextInt(10 - (l - 1));
int dir = rand.nextInt(2) + 1;
if (dir == 1)
{
for (int i = 0; i < l; i++)
{
grid[x + i][y] = "#";
}
}
else
{
for (int j = 0; j < l; j++)
{
grid[x][y - 1] = "#";
}
}
}
public static void main(String[]args)
{
BattleShip battleship = new BattleShip(10,10);
battleship.placeShip(5);
battleship.printGrid();
}
}
Any suggestions would be very helpful !!!!