From 4d5638aea859f64f8421795c2c836d7ca6a7415c Mon Sep 17 00:00:00 2001 From: school Date: Thu, 4 Oct 2018 13:30:59 -0500 Subject: [PATCH] Found a bug in the placeOnBoard method --- Battleship.java | 44 ++++++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/Battleship.java b/Battleship.java index b0dc2ea..136dc48 100644 --- a/Battleship.java +++ b/Battleship.java @@ -39,42 +39,47 @@ public class Battleship{ 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]; placed = false; + System.out.println(length); while (!placed){ - + Ship cur_ship = Ship.randomShip(boundTL,boundBR,length,i%2 == 0); + cur_ship.print(); boolean intersects = false; int rot = 0; + // we need to clone since start is modified in place int[] stationary = cur_ship.getStart().clone(); while ((rot < 4) && !placed) { // ensures ship doesn't intersect with any that were previously placed for (int j = 0; j < i; j++){ intersects = cur_ship.isIntersecting(ships[j]); - if (intersects){ - cur_ship.rotate(stationary,1); - rot += 1; + if (intersects) { break; } - } - // ensures ship is still in bounds after rotation - if (!cur_ship.isInside(boundTL,boundBR)) { + if (intersects) { cur_ship.rotate(stationary,1); rot += 1; } - // nothing wrong with ship placement? place it! - else if (!intersects){ - ships[i] = cur_ship; - placed = true; + if (cur_ship.isInside(boundTL,boundBR)){ + if (!intersects){ + ships[i] = cur_ship; + placed = true; + } + else { + cur_ship.rotate(stationary,1); + rot += 1; + } } + } } } @@ -99,7 +104,14 @@ public class Battleship{ } public static void main(String[] args){ int[][] testBoard = new int[10][10]; - randomizingBoard(testBoard); - printBoard(testBoard); + Ship test = new Ship(new int[] {5,5}, new int[] {9,5}); + int[] stationary = test.getStart().clone(); + for (int i = 0; i < 4; i++){ + test.print(); + test.placeOnBoard(testBoard); + printBoard(testBoard); + test.rotate(stationary,1); + } + } }