入力として、点の座標を有効にする方法

ワックス:

私は最近、基本的な開発を始めました「戦艦」でゲームをJavaの

私はすでに、各船の位置を含むマッチフィールドを作成しました。今、私は、ユーザー座標でプログラムを提供することを可能にしたいと思います。問題の座標は、船の位置と重なっている場合は、その特定の船は外に除去する必要があるshipsキュー。

私はすでに試してみたScanner中でクラスをjava.util無駄にパッケージ。誰かが二次元は、テキストベースのストリームの座標を解釈するのヘルプ私を喜ばことができればそれは素晴らしいことです。次のように座標の構文は次のようになりますx, yかなりまっすぐ進む、右?

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;
        }
    }
}
詳細と:
  1. 作成スキャナプレーヤーの入力を取得することを目的とし
  2. xとyの値を読みます
  3. ヒットされているかどうか確認してください

ヒント:ループのステップ2と3を入れて

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");
    }
}

Coordinates needed
x=2
y=1
Hit

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=284322&siteId=1