【问题标题】:Create tiled map n*n for maze为迷宫创建平铺地图 n*n
【发布时间】:2014-10-24 01:44:19
【问题描述】:

我需要创建一个平铺地图 nxn 列/行。首先,程序会询问用户他想要多少瓦片,然后它会创建一个瓦片地图。之后,用户单击一个图块,图块会改变颜色。然后他点击另一块瓷砖,颜色也发生了变化。之后,程序会从选定的图块到另一个图块找到解决方案。

现在,我使用 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();
    }
}

【问题讨论】:

  • 现在,我想说你最好的做法是将逻辑与渲染分开。整理出你的模型的数据结构、算法和行为,一旦测试和工作,然后才处理如何渲染模型。见MVC。现在,您已经将所有内容硬连在一起,难以设计、调试和理解。

标签: java swing graphics mouselistener maze


【解决方案1】:

这里的问题是您没有检查用户点击了哪个图块。相反,您只是检查他的用户是否点击过。

您需要做的是找到瓷砖的widthheight。 然后你需要检查用户在嵌套的 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);
}

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2012-08-15
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多