0

我正在做一个迷宫,我想使用这里定义的递归方法。但是,我需要一些关于如何在随机绘制线条后随机打开线条的帮助。现在我正在创建线条(迷宫的墙壁),只需用它们的开始和结束 x 和 y 坐标绘制它们。我似乎无法找到一种简单的方法来“擦除”(或“打开”)部分线条。

编辑:好的,我需要稍微具体一点。我怎么能随机选择每条线上的地方“打开”?

编辑2:这是我正在尝试做的一些代码:

public static void draw() {
    // picks a random spot in the rectangle
    Random r = new Random();
    int x0 = r.nextInt(w)
    int y0 = r.nextInt(h)

    // draws the 4 lines that are perpendicular to each other and meet
    // at the selected point
    StdDraw.line(x0, 0, x0, y0);
    StdDraw.line(0, y0, x0, y0);
    StdDraw.line(x0, h, x0, y0);
    StdDraw.line(w, y0, x0, y0);
}

public static void main(String[] args) {   
    // set up the walls of the maze
    // given w = width and h = height
    StdDraw.setXscale(0, w);
    StdDraw.setYscale(0, h);

    StdDraw.line(0, 0, 0, h);
    StdDraw.line(0, h, w, h);
    StdDraw.line(w, h, w, 0);
    StdDraw.line(w, 0, 0, 0);

    draw();
}

现在我只需要弄清楚如何随机选择其中 3 行,并为每行随机擦除一部分。

4

1 回答 1

1

假设您正在使用swingpaintComponent方法,您可以将Graphic' 颜色设置为背景颜色并再次绘制线条。这是一个例子:

public class DrawTest extends JPanel{
    public static void main(String[] args)
    {

        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DrawTest());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public Dimension getPreferredSize(){
        return new Dimension(400,300);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.black);
        g.drawLine(10, 10, 100, 10);
        g.setColor(getBackground());
        g.drawLine(50, 10, 60, 10);
    }
}

编辑

我想你没有在paintComponent方法中创建迷宫(或者每次重新绘制时你都会得到一个新的迷宫)。因此,我建议创建一个类似于下面的子类并将其实例存储在ArrayList主类的字段中。ArrayList然后你可以在你喘气的时候遍历你的。

public static class MazeWall{
    public static final int OpeningWidth = 10;

    Point start;
    Point end;
    Point opening;

    public MazeWall(Point start, Point end, boolean hasOpening){
        this.start = start;
        this.end = end;

        if(hasOpening){
            int range;
            if(start.x == end.x){
                range = end.x - start.x - OpeningWidth;
                int location = (int)(Math.random() * range + start.x);
                opening = new Point(location, start.y);
            } else{
                range = end.y - start.y - OpeningWidth;
                int location = (int)(Math.random() * range + start.y);
                opening = new Point(location, start.x);
            }
        }   
    }
}
于 2012-10-17T18:31:31.553 回答