更新:我找出问题所在并在下面写出。如果您想在此处查看完整的兼容代码,请访问GitHub:https://github.com/scohen40/cohen-mco364-fall-2018/tree/mazeGUI/src/main/java/cohen/maze
我有一个二维的单元阵列,每个单元有4个壁。我的generateMaze()类从随机点开始,并挖出一个迷宫。该部分正常工作,当我在控制台中打印出迷宫时,一切都很好。
我的下一个目标是用JPanel中的JComponent绘制迷宫。问题是我得到的只是左上角的一个粗线框。
这是绘画代码:
public class AnimatedMaze extends JComponent {
private Maze maze;
private int componentHeight;
private int componentWidth;
private int seventhHeight;
private int seventhWidth;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
componentHeight = this.getHeight();
componentWidth = this.getWidth();
seventhHeight = componentHeight/7;
seventhWidth = componentWidth/7;
maze = new Maze(7, 7);
g.setColor(Color.black);
paintMaze(g);
}
/**
* The paintMaze() method runs through the generated maze and paints the existing walls.
* @param g
*/
void paintMaze(Graphics g) {
for (int x = 0; x < maze.getHeight(); x++) {
System.out.println("|");
for (int y = 0; y < maze.getWidth(); y++) {
Cell current = maze.getMaze()[x][y];
if(current.isWestWall()) {
g.drawLine(x, y, x, y + seventhHeight);
}
if(current.isNorthWall()){
g.drawLine(x, y,x + seventhWidth, y);
}
if(current.isEastWall()) {
g.drawLine(x + seventhWidth, y, x+ seventhWidth, y + seventhHeight);
}
if(current.isSouthWall()) {
g.drawLine(x, y + seventhHeight, x + seventhWidth, y +seventhHeight);
}
}
}
}
}
答案 0 :(得分:2)
在绘画代码中,您需要将每个x和y坐标乘以'seventhHeight',否则就无法绘画以校正坐标。
答案 1 :(得分:0)
在Krzysztof Cichocki的答案的基础上,意识到坐标的工作方式不同于行和表。在将所有内容乘以SeventhHeight之后,我将x换为y,反之亦然。而且,我对任何坐标所做的任何添加现在始终都是第七高度,以使所有内容成比例。 这是绘画方法的当前代码:
void paintMaze(Graphics g) {
for (int x = 0; x < maze.getHeight(); x++) {
System.out.println("|");
for (int y = 0; y < maze.getWidth(); y++) {
Cell current = maze.getMaze()[x][y];
if(current.isWestWall()) {
g.setColor(Color.black);
g.drawLine((y+1)*seventhHeight, x*seventhHeight, (y+1)*seventhHeight, x*seventhHeight + seventhHeight);
}
if(current.isNorthWall()){
g.drawLine((y+1)*seventhHeight, x*seventhHeight,(y+1)*seventhHeight + seventhHeight, x*seventhHeight);
}
if(current.isEastWall()) {
g.drawLine((y+1)*seventhHeight + seventhHeight, x*seventhHeight, (y+1)*seventhHeight + seventhHeight, x*seventhHeight + seventhHeight);
}
if(current.isSouthWall()) {
g.drawLine((y+1)*seventhHeight, x*seventhHeight + seventhHeight, (y+1)*seventhHeight + seventhHeight, x*seventhHeight +seventhHeight);
}
}
}
}