Results 1 to 12 of 12
  1. #1
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default The last stumbling block to finishing a project: Checking if already used

    I'll toss all the code up first, the question will be WAYYYYYY down below (about 90% of the code is entirely irrelevant, but everyone always asks for me to post the full source)
    BattleShip.java

    Java Code:
    import java.util.*;
    public class BattleShip {
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    
    System.out.println("Welcome to battleship\n\n");
    char[][] ArrayPlayer= new char[10][10]; // Create an Array for the player
    Arrays MyPlayers = new Arrays(ArrayPlayer); // Set MyPlayers object to contain array ArrayPlayer, called from Arrays.java
    
     //Patrol Boat
    Boat PatrolBoat = new Boat();
    PatrolBoat.health=2;
    PatrolBoat.name="Patrol Boat";
    PatrolBoat.letter='p';
    
    //Submarine
    Boat Submarine = new Boat();
    Submarine.health=3;
    Submarine.name="Submarine";
    Submarine.letter='s';
    
    //Destroyer
    Boat Destroyer = new Boat();
    Destroyer.health=4;
    Destroyer.name="Destroyer";
    Destroyer.letter='d';
    
    //Battleship
    Boat BattleShip = new Boat();
    BattleShip.health=5;
    BattleShip.name="BattleShip";
    BattleShip.letter='b';
    
    Boat SelectedBoat; // Create a boat called Selected Boat
    Boat[] boatarray = {PatrolBoat, Submarine, Destroyer, BattleShip}; // Boat array used in select, boat here gets applied to selectedboat
    int iSelect, x=0, y=0, i=0, j=0,k=0, iOrientation; // initialize heaps of variables
    
    for (i=0; i < 4; i++){
    System.out.println("Press 1 to place your patrol boat, 2 to place your submarine, 3 to place your destroyer, or 4 to place your battleship.");//Prompt user
    iSelect =input.nextInt(); // Get value for select from array
    SelectedBoat=boatarray[iSelect-1]; // Select boat from array
    SelectedBoat.used +=1;
    while (SelectedBoat.used > 1){
        System.out.println("This boat has already been used, try again: ");
        iSelect =input.nextInt(); // Get value for select from array
        SelectedBoat=boatarray[iSelect-1]; // Select boat from array
        SelectedBoat.used +=1;
    }
        System.out.println("Press 1 for Vertical, 2 for Horizontal: "); // Prompt for horiz or vert.
    iOrientation = input.nextInt(); // Get horiz or vert
    while (iOrientation  < 1 || iOrientation  > 2){
         System.out.println("You have selected an incorrect value, try again: ");
         iOrientation=input.nextInt();
    }
    System.out.println("Choose where you would like the piece to appear on a grid (A1 is top left J10 is bottom right): ");
    String c="";//Empty string / create string / dereference string
    c = input.next(); // Allow user to guess
    SelectedBoat.location = Boatloc.BoatLoc(c); // Transform String from letter / number to 2 numbers for grid placement
    y=SelectedBoat.location[0]; // Set y to y value
    x=SelectedBoat.location[1];// Set x to X value.
    
    if (iOrientation == 1){ // If orientation is vertical
    for (j=0; j <SelectedBoat.health; j++){ // While < health, place more
    while (y + SelectedBoat.health > 9){
        System.out.println("Placing a boat here will make it go out of bounds, try again: ");
        c = input.next(); // Allow user to guess
        SelectedBoat.location = Boatloc.BoatLoc(c); // Transform String from letter / number to 2 numbers for grid placement
        y=SelectedBoat.location[0]; // Set y to y value
        x=SelectedBoat.location[1];// Set x to X value.
    }
    MyPlayers.AddBoat(y,x,SelectedBoat.letter);// Add boat letter at selected location
    while (MyPlayers.isUsed(y,x)){
        System.out.println("This spot has already been used, pick one that hasn't been used or intersect with a used spot: ");
        for (k=0; k< j; k++){
        ArrayPlayer[y][x]=' ';
        if (k==(j-1)){
            break;
        }
        y--;
        }
    }
    MyPlayers.isUsed(y, x);//Spot is used
    y++;//Increment the y variable
    
    
    }// end placement for
    }// End vert orientation if
    
    if (iOrientation == 2){//If boat orientation is horizontal, place as such
    for (j=0; j <SelectedBoat.health; j++){ // While < health, place more
    while (x + SelectedBoat.health > 9){
        System.out.println("Placing a boat here will make it go out of bounds, try again: ");
        c = input.next(); // Allow user to guess
        SelectedBoat.location = Boatloc.BoatLoc(c); // Transform String from letter / number to 2 numbers for grid placement
        y=SelectedBoat.location[0]; // Set y to y value
        x=SelectedBoat.location[1];// Set x to X value.
    }
    MyPlayers.AddBoat(y,x,SelectedBoat.letter);// Add boat letter at selected location
    while (MyPlayers.isUsed(y,x)){
        System.out.println("This spot has already been used, pick one that hasn't been used or intersect with a used spot: ");
        for (k=0; k< j; k++){
        ArrayPlayer[y][x]=' ';
        if (k==(j-1)){
            break;
        }
        x--;
        }
    }
    MyPlayers.isUsed(y, x);//Spot is used
    x++;//Increment the y variable
    }// end placement for
    }// End vert orientation if
    Arrays.DisplayMap(ArrayPlayer);// Player graph output. 
    }// End placement for
    
    
    }// End main
    }// End Class

    Boats.java
    Java Code:
    public class Boat{
     private int numBoats;
     public int health;
     public int used;
     public int orientation;
     public char letter;
     public int[] location;
     public String name;
     
     public int getnumboats(){
         return numBoats;
     }
     
     
     }
    Boatloc.java
    Java Code:
    public class Boatloc {
    public static int[] BoatLoc (String location){
     int y = Character.toLowerCase(location.charAt(0))-97;
     int z= Character.toLowerCase(location.charAt(1))-49;
     int[] x = {y, z};
    return x;
    }
    Arrays.Java
    Java Code:
    public class Arrays {
        private char[][] Arrays;
        private boolean used;
        
        public Arrays(char[][] PlayerArray) {
            Arrays = PlayerArray;
        }
        public boolean isUsed(int x, int y) {
            if(Arrays[x][y] !=' '){
                used = true;
            }
            else{
                used = false;
            }
            return used;
        }
        
        public void AddBoat(int x, int y, char boatLetter) {
            Arrays[x][y] = boatLetter;
        }
        public static void DisplayMap(char[][] Array){
            //Player Grid Output.
    int i=0, j=0;
    System.out.println("____________Player setup:____________\n"); // Top of the 'player positioning' box.
    System.out.println("         A B C D E F G H I J");  // Top of grid letters
    System.out.println("");// blank line
    for (i=0; i < Array.length; i++){ // Outer loop of the 2d array output
    if (i< 9){
    System.out.print("|  "+ (i+1) +"     "); // Left side of the box
    }
    else{
        System.out.print("|  "+ (i+1) +"    ");
    }
    for (j=0; j<10; j++){ // Inner loop of array
    System.out.print(Array[i][j]+ " "); // Array output
    }// End inner for.
    System.out.println("       |"); // Right side of playermap box
    }//End outer for
    System.out.println("______________________________________"); // Formatting 
        }
    }

    That should sum it up for code.


    Okay, my issue right now is that I'm trying to check to make sure a spot hasn't been used when I am placing a piece, if it has, I want to remove all the 'letters' placed to that point. I really need help writing the method that's going to check it. As my code stands here (At the time of posting) it returns an endless loop, so I know that I'm fucking something up ROYALLY). If anyone can help me out here I would be VERY grateful!

    Thanks a lot.

    TL;Dr; I suck at methods and can't think for the life of me of how to check if a spot in a 2D array has been used or not.
    Last edited by sarevok9; 04-21-2011 at 04:19 PM.

  2. #2
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    did you attempt the solution I gave you 2 days ago?
    Unique data check in a 2d array using objects

  3. #3
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    I did my best to do that, but... I simply have no idea how I'm going to implement that in my existing code.

  4. #4
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    That's quite astonishing because you already have a class called Boat and all you had to do was add the additional fields and methods to it, then copy + paste the coOrds class into your code.

    The only work for you to do after that is to implement the what would be new method in the Boat class

  5. #5
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    That and I try to avoid code that I honestly don't know how to use.

    Your code uses a lot of things that I've honestly never been exposed to at my level of java experience, and my main goal is to learn how to code, not to complete a project that is arbitrary in the first place.

  6. #6
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    The only thing I used was a List!

    List (Java 2 Platform SE v1.4.2)

  7. #7
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    Aye, up until now I'd never seen an array list (my class is just covering normal arrays now, I'm doing objects just for shits and giggles). Today in class the teacher was covering simple arrays and subscripts...Yay java 101.

    Also: I read the oracle doc on the 'this' keyword and it didn't really make too much sense to me. I don't really understand why it's used or what it's used for?

    Also: In your code over there you make use of some private ints

    Java Code:
        private int posX;
        private int posY;
        private int width;
    But I don't see you utilize them anywhere along the way? Am I supposed to be setting those based on the Boats.location object attribute?

    I'm just a bit confused, although I did read the arraylist example here: Java ArrayList example and thought it was wonderful.

  8. #8
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    Here's my solution again...

    This coordinates class is a simple object which contains 2 integers, x and y, which relate to the boats position on the battleship board.
    Java Code:
    public class CoOrds {
        public int x;
        public int y;
        CoOrds(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    i've added 3 fields to your Boat class:
    posX, posY together make up the starting position where the boat is placed on your battleship board; the top-left-hand corner
    width is the number of squares the Boat object takes up.
    obviously, when you create a Boat, you need to set these 3 fields with their own set methods; or like you've written the rest of your code just make them 'public' and don't need to use a set method to change them.

    Java Code:
    public class Boat {
        private int [COLOR="red"]posX[/COLOR];
        private int [COLOR="red"]posY[/COLOR];
        private int [COLOR="red"]width[/COLOR];
        ...
        public List<CoOrds> getOccupiedSquares() {
            /* the squares occupied are calculated by the X,Y start position until the X width */
            List<CoOrds> coOrds = new ArrayList<>();
            for (int i=[COLOR="Red"]posX[/COLOR]; i<[COLOR="red"]width[/COLOR]; i++) coOrds.add(new CoOrds(i,[COLOR="red"]posY[/COLOR]));
            return coOrds;
        }
    }

    This is just an addition to your boats class that adds a new method getOccupiedSquares(). getOccupiedSquares returns a List (like an array, but with an unlimited size, and without having to set the maximum size); the List contains co-ordinates of the places on your board the Boat is sitting in.

    What that means is, when you need to check if one boat is sitting on another, you call each boats getOccupiedSquares() method and if any of them have the same coOrdinates it means the Boats are over-lapping i.e. a collision.

    here's how you would use it:
    Java Code:
    public void checkCollision(Boat b1, Boat b2) {
        //get the lists of squares to check against
        java.util.List<CoOrds> b1squares = b1.getOccupiedSquares();
        java.util.List<CoOrds> b2squares = b2.getOccupiedSquares();
        //loop through boat 1's coordinates
        for (int i=0; i<b1squares.size(); i++) {
            //loop through boat 2's coordinates
            for (int j=0; j<b2squares.size(); j++) {
                /** This nested loop checks each coordinate of boat one
                 *   against each coordinate of boat 2 */
                 if (b1squares.get(i).x == b2squares.get(j).x) {
                     //x coordinates match
                     if (b1squares.get(i).y == b2squares.get(j).y) {
                         //x & y coordinates match so there is a collision
                     }
                 }
            }
        }
    }

  9. #9
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    Java Code:
    for (int i=posX; i<width; i++) coOrds.add(new CoOrds(i,posY));
    This for loop simply adds a co-ordinate for each square the boat is occupying.
    if the Boat was placed at 3,3 on the board and the boat is 4 squares long, the coordinates would come out to (x,y):
    (3,3), (4,3), (5,3), (6,3)

    the idea is that you should know where the boat is placed before you try to detect a collision. put another boat at (5,3) that is 4 squares long and you'll get these (x,y) coordinates:
    (5,3), (6,3), (7,3), (8,3)

    then its clear to see the second boat collides with the first boat in 2 squares.

  10. #10
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    Since this program is going to be using no less than 4 boats per side on 2x 10x10 arrays, isn't it a bit cumbersome checking the boats this way?

    Example:
    Boats 1, 2, 3 placed: (cords as x , y)
    Boat 1: 0,0 , 0,1
    Boat 2: 0,2 , 0,3 , 0,4
    Boat 3: 0,5 , 0,6 , 0,7, 0,8
    Assume that we are trying to put boat 4 (which is 1 wide, 5 long) starting in 1,0
    it will place on:
    Boat 4: 1,0 , 1,1 , 1,2 , 1,3 , 1,4
    This won't cause any collisions but it will still need to be compared as such
    Boat1 : Boat 4
    Boat2 : Boat 4
    Boat3 : Boat 4

    Wouldn't this just be easier setting up some kind of a bool switch, or hell, even a second 2d array for each player?

    Edit: To expand on why I find this to be a little cumbersome:

    At any point, I would have to write in something like the following loop.
    //placement loop
    for (i=0; i< 4; i++){
    if (i==0){
    Boats Boat1= SelectedBoat;
    }
    else if (i==1){
    Boats Boat2=SelectedBoat;
    }
    .... Repeat til all 4 boats have been used. I could eliminate this by using an array, but it's still going to be complex.

    // Then using your method above
    CheckCollision(SelectedBoat, Boat2);
    CheckCollision(SelectedBoat, Boat3);
    CheckCollision(SelectedBoat, Boat4);

    Or something like that.

    Wouldn't it just be a bit easier to do something like this:
    boolean[][] ArrayPlayer2 = new boolean [10][10];

    Then initialize it to all true (even though I'm pretty sure that's the default state of a bool array)
    for (i=0; i< 10; i++){
    for (j=0; j<10; j++){
    ArrayPlayer2[i][j]=true;
    }
    }

    Then when each piece is placed you just check using the same placement loop as before if there's any bools set to false:
    for (i=0; i<SelectedShip.health; i++)
    if (ArrayPlayer2[x][y]==true){
    //null, don't place yet
    }
    else if (ArrayPlayer2[x][y]== false){
    System.out.println("There is a collision at")+x + y+("In the grid, please try again: ")
    //placement algorithm within a while loop here
    }
    x++ or y++ here.

    Wouldn't this do the same thing with slightly more memory usage but significantly less complexity and code?
    Last edited by sarevok9; 04-24-2011 at 10:35 AM.

  11. #11
    sarevok9 is offline Member
    Join Date
    Apr 2011
    Posts
    37
    Rep Power
    0

    Default

    At the risk of sounding pushy, can someone tell me if the logic I outlined above would be workable over the one outlined by Ozzyman?

  12. #12
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    If you want people to read your code, please wrap it in code tags.
    [code ] <- omit space
    YOUR CODE HERE
    [/code]

Similar Threads

  1. finishing up a DB/Java exercise
    By hayden06f4i in forum New To Java
    Replies: 47
    Last Post: 12-12-2010, 10:57 PM
  2. block url
    By thedevilz in forum New To Java
    Replies: 1
    Last Post: 09-16-2010, 11:55 PM
  3. Got hit by the Comparable block again, help pls.
    By niu_niu in forum New To Java
    Replies: 7
    Last Post: 06-24-2010, 10:49 AM
  4. Programming block
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-25-2007, 12:20 PM
  5. Return to try block
    By Freddie in forum New To Java
    Replies: 2
    Last Post: 05-11-2007, 09:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •