How to enable coordinates of a point as a input

Encera :

I recently started developing a basic "Battleship" game in Java.

I've already created the match-field containing the position of each ship. Now, I'd like to allow the user to provide the program with a coordinate. If the coordinate in question is overlapping with the position of a ship, then that particular ship should be removed out of the ships queue.

I already tried out the Scanner class in the java.util package to no avail. It would be great if someone could please help me with interpreting a two-dimensional coordinate in a text-based stream. The syntax of a coordinate should be as follows: x, y. Pretty straight forward, right?

public static void main(String[] args)
{
    // Position ships.
    Scanner scanner = new Scanner(System.in).next();
    List<Point> ships = new ArrayList<>(5);
    ships.add(new Point(2, 1));
    ships.add(new Point(3, 2));
    ships.add(new Point(10, 4));
    ships.add(new Point(7, 6));
    ships.add(new Point(8, 4));
    while(true)
    {
        // Check status.
        if(ships.length > 0)
        {
            // Check if a field is containing a ship.
            for(int y = 0; y < 10; y++)
            {
                for(int x = 0; x < 40; x++)
                {
                    if (ships.contains(new Point(x, y)))
                    {
                        System.out.print('S');
                    }
                    else
                    { 
                        System.out.print('.');
                    }
                }
                System.out.println();
            }
            // TODO: Query the input of the user.
            final String input = scanner.next();
        }
        else
        {
            System.out.println("You won the game!");
            break;
        }
    }
}
Butiri Dan :
  1. Create a Scanner object to get the player input
  2. Read x and y values
  3. Check if is hit or not

Hint: Put the steps 2 and 3 in a loop

public static void main(String[] args) {
    Point[] shipPositions = new Point[5];
    shipPositions[0] = new Point(2, 1);
    shipPositions[1] = new Point(3, 2);
    shipPositions[2] = new Point(10, 4);
    shipPositions[3] = new Point(7, 6);
    shipPositions[4] = new Point(8, 4);

    //Player input
    System.out.println("Coordinates needed");
    Scanner in = new Scanner(System.in);
    int x, y;

    System.out.print("x=");
    x = in.nextInt();
    System.out.print("y=");
    y = in.nextInt();

    Point p = new Point(x, y);

    if (Arrays.asList(shipPositions).contains(p)) {
        System.out.print("Hit");
    } else {
        System.out.print("Miss");
    }
}

Example

Coordinates needed
x=2
y=1
Hit

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276935&siteId=1