开发者社区> 问答> 正文

如何启用点的坐标作为输入

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

问题来源:Stack Overflow

展开
收起
montos 2020-03-25 21:22:07 402 0
1 条回答
写回答
取消 提交回答
    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
    

    问答来源:Stack Overflow

    2020-03-25 21:23:08
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载