1

I currently have a program with a grid and lines that will be drawn between dots in the grid. It uses standard draw. I wish to limit the length of the lines, so that they can only go from the adjacent points, but do not know how I would do this.

Thanks

StdDraw.setCanvasSize(400, 400);
StdDraw.setXscale(0, 10);
StdDraw.setYscale(0, 10);      

//dots
double radius = .15;
double spacing = 2.0;

for (int i = 0; i <= 4; i++) {
    for (int j = 0; j <= 4; j++) {
        StdDraw.setPenColor(StdDraw.GRAY); 
        StdDraw.filledCircle(i * spacing, j * spacing, radius );
    }
}
StdDraw.setPenColor(StdDraw.BLUE); 
StdDraw.text(0, 9.5, player1_name);
StdDraw.setPenColor(StdDraw.RED); 
StdDraw.text(5, 9.5, player2_name);
int turn = 1;
     for (int i = 0; i <= 40; i++) { 
         if (turn % 2 == 0)
           StdDraw.setPenColor(StdDraw.RED);
         else
           StdDraw.setPenColor(StdDraw.BLUE);

         while(!StdDraw.mousePressed()) { }
         double x = StdDraw.mouseX();
         double y = StdDraw.mouseY();
   System.out.println(x + " " + y);
         StdDraw.setPenRadius(.01);
         StdDraw.show(200); 
               while(!StdDraw.mousePressed()) { }
               double x2 = StdDraw.mouseX();
               double y2 = StdDraw.mouseY();
               StdDraw.show(200); 
double xround = Math.round(x); 
double yround = Math.round(y);
double x2round = Math.round(x2);
double y2round = Math.round(y2);
  int xroundb = (int) xround; 
  int yroundb = (int) yround;
  int x2roundb = (int) x2round;
  int y2roundb = (int) y2round;
StdDraw.line(xround, yround, x2round, y2round);
System.out.println("Line Drawn"); 
StdDraw.show(); 
4

1 回答 1

1

啊,我明白了。您不是在询问line正确工作的实际方法,您希望line在未选择相邻点的情况下不调用这样的逻辑。

好吧,首先我们需要知道允许哪些相邻连接。那就是我们可以有垂直吗?水平的?对角线?我会解释每一个以防万一

所以你有spacing = 2.0. 好吧,这应该足以检查邻接。

if (Math.abs(x2round - xround) > spacing) {
   // don't draw
} else if (Math.abs(y2round - yround) > spacing)) {
   // don't draw
} else if (Math.abs(y2round - yround) > 0.0) && Math.abs(x2round - xround) > 0.0) {
   // don't draw if diagonal connections are forbidden
   // if diagonal is allowed, remove this else if condition
} else {
   StdDraw.line(xround, yround, x2round, y2round);
}

所以如果你不画画,那么你必须强制执行你的游戏逻辑。也许玩家放弃了一个回合。也许玩家有另一个机会选择相邻的点。它是由你决定。由于舍入,比较双精度总是有点疯狂,因此您可能希望选择一个非常小的 epsilon 双精度值来确保捕获所有情况,而不是使用 0.0。

于 2013-01-04T20:38:51.770 回答