另一个有趣的答案,尝试 JDK16 记录。这个菱形不是在一行中循环不同的索引,而是在简单的声明中使用Math.abs:
public record Diamond(int midx, int midy, int size) implements Shape {
public int right() { return midx + size; }
public int top() { return midy + size; }
/** Check if shape is drawn at this x,y position */
public boolean intersects(int x, int y) {
return Math.abs(midx-x) + Math.abs(midy-y) <= size;
}
}
为所有Shape 类和通用draw 添加接口以打印出任何相交形状的星号:
public interface Shape {
/** Check if shape is drawn at this x,y position */
boolean intersects(int x, int y);
/** Max X position used by this shape */
int right();
/** Max Y position used by this shape */
int top();
/** Draw a series of shapes */
public static void draw(Shape ... shapes) {
// Work out largest X, Y coordinates (and print the shape list):
int ymax = Arrays.stream(shapes).peek(System.out::println)
.mapToInt(Shape::top ).max().getAsInt();
int xmax = Arrays.stream(shapes).mapToInt(Shape::right).max().getAsInt();
System.out.println();
// Visit all X,Y and see what will be printed
for (int y = ymax ; y > 0; y--) {
for (int x = 1 ; x <= xmax; x++) {
boolean hit = false;
for (int i = 0; !hit && i < shapes.length; i++) {
hit = shapes[i].intersects(x,y);
}
System.out.print(hit ? "*" : " ");
}
System.out.println();
}
System.out.println();
}
}
... 以及绘制任意数量形状的主要工具 - 很容易定义新的 ASCII 艺术Shape 类:
public static void main(String[] args) {
Shape.draw(new Diamond(10, 7, 5));
Shape.draw(new Diamond(10, 7, 3), new Diamond(17, 5, 3), new Diamond(22, 8, 1));
}
打印出来:
Diamond[midx=10, midy=7, size=5]
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
Diamond[midx=8, midy=7, size=5]
Diamond[midx=17, midy=5, size=3]
Diamond[midx=22, midy=8, size=1]
*
***
*****
******* *
********* * ***
*********** *** *
********* *****
******* *******
***** *****
*** ***
* *
另见:Draw two ASCII spruce trees of specific heights