2012-12-17 102 views
1

我目前有一個網格和線條,將在網格中的點之間繪製一個程序。它使用標準繪製。我希望限制線條的長度,以便它們只能從相鄰點出發,但不知道如何做到這一點。標準繪製線的限制長度

感謝

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(); 
+0

@RohitJain我的經驗是,當代碼被破壞時,人們很少知道哪個部分是相關的。這就是爲什麼我通常會建議:「爲了更好地幫助,請發佈[SSCCE](http://sscce.org/)。」 –

回答

1

啊,我得到它。你不是問實際工作的line方法,你需要邏輯,如果沒有選擇相鄰點,line不會被調用。那麼,首先我們需要知道哪些相鄰連接是允許的。那是我們可以有Vertical嗎?水平?對角線?我會解釋每一個以防萬一

所以你有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); 
} 

所以如果你不繪製,那麼你必須執行你的遊戲邏輯。也許玩家沒有回合。也許玩家有機會選擇相鄰的點。它是由你決定。由於四捨五入,比較雙倍總是有點瘋狂,所以不是使用0.0,而是選擇一個非常小的epsilon double值來確保捕獲所有情況。