Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import acm.graphics.GRect;
- import acm.program.GraphicsProgram;
- import java.awt.*;
- public class MethodicalPyramid extends GraphicsProgram {
- private static final int BRICK_H = 50;
- private static final int BRICK_L = 100;
- /**
- * Returns the color to be used for bricks in the given layer.
- *
- * @param layerIndex index of the layer whose color to return. {@code 0} is the
- * bottom layer, {@code numberOfLayers - 1} is the top layer.
- * @param numberOfLayers the number of layers in the pyramid.
- * @return the color to be used for the given layer, or {@code null} if
- * {@code layerIndex} is invalid.
- */
- private Color layerColor(int layerIndex, int numberOfLayers) {
- if (layerIndex >= numberOfLayers || layerIndex < 0) {
- return null;
- } else if (layerIndex != 0) {
- int green;
- int blue = green = (220 / numberOfLayers * layerIndex);
- Color color = new Color(255, green, blue);
- return color;
- } else {
- return new Color(255, 0, 0);
- }
- }
- /**
- * Draws the given layer with bricks filled with the given color. If
- * {@code layerIndex} is invalid, no bricks at all should be drawn.
- *
- * @param layerIndex index of the layer to draw. {@code 0} is the bottom layer,
- * {@code numberOfLayers - 1} is the top layer.
- * @param numberOfLayers the number of layers in the pyramid.
- * @param layerColor color the layer's bricks should be filled with.
- */
- public void drawLayer(int layerIndex, int numberOfLayers, Color layerColor) {
- if (layerIndex >= numberOfLayers || layerIndex < 0) {
- //null;
- } else {
- int brickAmount = numberOfLayers - layerIndex;
- int x;
- int y = (BRICK_H * numberOfLayers) - (BRICK_H * layerIndex);
- for (int i = 0; brickAmount > i; i++) {
- x = 50 + (i * 100) + (layerIndex * 50);
- GRect brick = new GRect(x, y, BRICK_L, BRICK_H);
- brick.setFilled(true);
- brick.setColor(layerColor);
- add(brick);
- }
- }
- }
- public void run() {
- int n = readInt("Enter a number");
- for (int i =0; i <= n; i++){
- drawLayer(i,n,layerColor(i,n));
- }
- }
- public static void main(String[] args) {
- new MethodicalPyramid().start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement