我目前有一个程序,其网格和线条将在网格中的点之间绘制。它使用标准绘图。我希望限制线条的长度,这样它们只能从相邻的点开始,但不知道我会怎么做。
由于
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 :(得分: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 double值来确保捕获所有情况。而不是使用0.0。