2012-10-17 2 views
0

미로를 만들고 있는데 재귀 메서드를 here으로 사용하고 싶습니다. 그러나 무작위로 선을 그린 후에 선을 무작위로 여는 방법에 대한 도움이 필요합니다. 바로 지금 나는 그것들의 시작과 끝을 그리며 x 좌표와 y 좌표를 그려서 선 (미로의 벽)을 만듭니 다. 나는 선의 일부를 "지우거나"열어 볼 수있는 간단한 방법을 찾지 못하는 것 같습니다.무작위로 Java에서 미로 행을 열려면

편집 : 좋아요. 좀 더 구체적으로해야합니다. 에 무작위로 장소를 선택할 수있는 방법은 각각 "open up"입니까?

편집 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을 선택하는 방법을 알아낼 필요가 있고, 각 라인 임의로 삭제 일부.

+0

재미있는 문제이지만, 문제를 중심으로 일부 소스 코드를 게시하면 도움이됩니다. –

+0

* "어떻게하면 각 줄에있는 장소를 임의로 선택하여"열 수 있습니까? ""* '무작위로 줄을 여는 것'이 유효하고 논리적 인 미로를 생성한다고 믿는 것 같습니다. 나는 OTOH가 그렇게 생각하지 않는다. 첫 번째 작업은 미로의 모양을 만드는 방법을 알아 내야합니다. –

+0

@NickRippe 몇 가지 코드를 추가했습니다. 이 코드가 실제로는 정말 간단한 코드라는 것을 알고 있지만 CS로 시작한 것입니다. – yiwei

답변

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); 
      } 
     } 
    } 
}