创建一个n*n的平铺地图用于迷宫。

3
我需要创建一个n x n的平铺地图。首先,程序询问用户想要多少个平铺,然后创建一个平铺地图。之后,用户单击一个平铺,平铺就会改变颜色。然后他点击另一个平铺,颜色也会改变。之后,程序将找到从选择的平铺到其他平铺的解决方案。
目前,我使用Graphics2D组件创建了平铺地图,但当我单击平铺时,整个图形都会改变颜色,而不仅仅是一个平铺......请告诉我问题出在哪里?有什么好的绘制平铺地图的方法吗?谢谢!迷宫应该看起来像这样:
我还需要输入墙壁和寻找解决方案的代码。 这是我创建地图的JPanel代码。
public LabyrintheInteractif (){
    addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            click=true;
            repaint();
            xClick=e.getX();
            yClick=e.getY();
        }
    });

    tiles=Integer.parseInt(JOptionPane.showInputDialog("How many tiles ?"));
    Quadrilage", JOptionPane.YES_NO_OPTION);

    setPreferredSize(new Dimension(734, 567));
    setVisible(true);
}

@Override
public void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.white);

    rect = new Rectangle2D.Double(0, 0,getWidth(), getWidth());
    g2d.fill(rect);
    g2d.setColor(Color.black);

    for (row = 0; row <tuiles; row++) {
        for (column = 0; column < tuiles; column++) {
            g2d.setStroke(new BasicStroke(3));
            g2d.draw( square=new Rectangle2D.Double(column*100 , row*100,100,100));
        }
        if(click){
            g2d.setColor(Color.green);
            g2d.fill(square);
            repaint();
    }
}

1
现在,我认为你最好的做法是将逻辑与渲染分开。解决模型的数据结构、算法和行为,一旦测试并工作正常,再考虑如何渲染模型。参见MVC。现在你已经把所有东西硬编码在一起,这使得设计、调试和理解都很困难。 - Bohemian
1个回答

2
问题在于你没有检查用户点击了哪个瓷砖。相反,你只是检查用户是否点击了任何地方。
你需要做的是找到瓷砖的宽度和高度。然后你需要在嵌套的for循环中检查用户点击了哪个瓷砖,类似于以下方式。
for (row = 0; row <tuiles; row++) {
   for (column= 0; column<tuiles; column++) {
      if(clicked){

         //check if the click x position is within the bounds of this tile
         if(column * tileWidth + tileWidth > xClick && column * tileWidth < xClick){

            //check if the click y position is within the bounds of this tile
            if(row * tileHeight + tileHeight > yClick && row * tileHeight < yClick){
               //mark this tile as being clicked on.
               clicked = false;
            }
         }
      }
   }
}

那么你需要存储布尔值,以表示特定的瓷砖是否被点击。这样,当你绘制瓷砖时,可以使用类似以下代码:

if(thisTileHasBeenClicked){

   //if the tile has been clicked on
   g2d.setColor(Color.green);
   g2d.fill(square);
}else{

   //if the tile has not been clicked on
   g2d.setColor(Color.gray);
   g2d.fill(square);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接