gpt4 book ai didi

java - Pyramid Exercise java没有完全对齐

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:16:23 26 4
gpt4 key购买 nike

Write a GraphicsProgram subclass that draws a pyramid consisting of bricks arranged in horizontal rows, so that the number of bricks in each row decreases by one as you move up the pyramid

这是我的代码:

import acm.graphics.GRect;
import acm.program.GraphicsProgram;

public class Pyramid extends GraphicsProgram {
public void run() {

int BRICK_WIDTH = 30;
int BRICK_HEIGHT = 12;
int BRICKS_IN_BASE = 20;

for (int i = 1; i <= BRICKS_IN_BASE; i++) {
for (int j = 1; j <= i; j++) {

add(new GRect(this.getCanvasWidth() / 16 + (BRICK_HEIGHT * i)
+ BRICK_WIDTH + (BRICK_WIDTH * (BRICKS_IN_BASE - j)),
BRICK_HEIGHT * i, BRICK_WIDTH, BRICK_HEIGHT));

}

}

}
}

如果 BRICK_WIDTH 为 30 且 BRICK_HEIGHT 为 12,则金字塔未完全对齐,但如果 brick_width 为 30 且 brick_height 为 15,则它会完美对齐。

这是 BRICK_WIDTH 为 30 且 BRICK_HEIGHT 为 12 时金字塔的屏幕截图 enter image description here这是 BRICK_WIDTH 为 30 且 BRICK_HEIGHT 为 15 时金字塔的屏幕截图 enter image description here

最佳答案

使用 BRICK_HEIGHT 来确定 GRect 的 x 坐标听起来不合逻辑。

你需要换行

add(new GRect(this.getCanvasWidth() / 16 + (BRICK_HEIGHT * i)

add(new GRect(this.getCanvasWidth() / 16 + (BRICK_WIDTH / 2 * i)

如果 BRICK_HEIGHT 等于 15 且 BRICK_WIDTH 为 30,则有效,因为那时 BRICK_HEIGHT * i == (BRICK_WIDHT/2 * i)

但一般来说,您希望用于绘制当前线的 x 坐标基于积木的宽度,而不是高度。

关于java - Pyramid Exercise java没有完全对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45262612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com