首页 > 解决方案 > 如何启用点的坐标作为输入

问题描述

我最近开始用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;
        }
    }
}

标签: java

解决方案


  1. 创建一个Scanner对象以获取玩家输入
  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

推荐阅读