Browse Source

added placeOnBoard method

Battleship randomizingBoard is done and needs to be tested
experiment
school 7 years ago
parent
commit
6731305b41
  1. 71
      Battleship.java
  2. 14
      Ship.java

71
Battleship.java

@ -30,62 +30,57 @@ public class Battleship{
return this.playerBoard;
}
public static void main(String[] args){
int rand = randint(9,10);
System.out.println(rand);
}
public static void randomizingBoard(int[][] board){
boolean vert = false;
int[] boundTL = {0,0};
int[] boundBR = {board[0].length, board.length};
int length;
int[] lengths = {
2,
3,
3,
4,
5}
5};
boolean placed;
Ship[] ships = new Ship[5];
ships[0] = Ship.randomShip(boundTL,boundBR,lengths[0],true);
for (int i = 1; i < 5; i++){
length = lengths[i]
length = lengths[i];
placed = false;
while (!placed){
int[] start = new int[2];
int[] end = start.clone();
if vert{
end[Y] += length-1;
}
else {
end[X] += length-1;
}
Ship cur_ship = new Ship(start,end);
Ship cur_ship = Ship.randomShip(boundTL,boundBR,length,i%2 == 0);
boolean intersects = false;
int rot = 0;
while ((rot < 4) && !placed) {
if cur_ship.isInside(board[0].length,board.length) {
for (int j = 0; j < i + 1; j++){
placed = !isIntersecting(
int[] stationary = cur_ship.getStart().clone();
while ((rot < 4) && !placed) {
// ensures ship doesn't intect with any that were previously placed
for (int j = 0; j < i + 1; j++){
intersects = cur_ship.isIntersecting(ships[j]);
if (intersects){
cur_ship.rotate(stationary,1);
rot += 1;
break;
}
}
else {
rot = 4;
// ensures ship is still in bounds after rotation
if (!cur_ship.isInside(boundTL,boundBR)) {
cur_ship.rotate(stationary,1);
rot += 1;
}
}
// swap starting position each time
if (vert) {
vert = false;
}
else {
vert = true
// nothing wrong with ship placement? place it!
else if (!intersects){
ships[i] = cur_ship;
placed = true;
}
}
}
}
}
// we done, place those puppys on for real.
for (int i = 0; i < 5; i++){
ships[i].placeOnBoard(board);
}
}
}

14
Ship.java

@ -188,4 +188,18 @@ public class Ship{
System.out.println("Start: " + "(" + this.start[X] + ", " + this.start[Y] + ")");
System.out.println("End: " + "(" + this.end[X] + ", " + this.end[Y] + ")");
}
public void placeOnBoard(int[][] board){
if (this.vertical){
for (int c = this.start[Y];c <= this.end[Y];c++){
board[this.start[X]][c] = 4;
}
}
else {
for (int c = this.start[X];c <= this.end[X];c++){
board[c][this.start[Y]] = 4;
}
}
}
}
Loading…
Cancel
Save