Java入门:如何在递归正方形代码中实现随机颜色生成
解决随机颜色与递归正方形绘制的集成问题
嘿,这问题其实很好搞定!你已经写好了随机颜色生成方法,只需要把它整合到递归绘制逻辑里就行,我一步步给你讲清楚:
第一步:把随机颜色方法整合到类中
首先,把你写的randomColor()改成静态方法,并放到Exercise5类里面——因为你的drawSquare和draw都是静态方法,这样不用创建类的实例就能直接调用颜色生成方法。别忘了加上必要的导入语句:
import java.awt.Color; import java.util.Random; public class Exercise5 { // 静态的随机颜色生成方法 public static Color randomColor() { Random random = new Random(); int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); return new Color(red, green, blue); } // 剩下的drawSquare、draw、main方法放这里... }
第二步:替换默认填充色为随机颜色
在drawSquare方法里,把原来设置浅灰色的代码,直接替换成调用你的randomColor()方法就行:
public static void drawSquare(double x, double y, double size) { // 替换默认的浅灰色,调用随机颜色方法 StdDraw.setPenColor(randomColor()); StdDraw.filledSquare(x, y, size/2); StdDraw.setPenColor(StdDraw.BLACK); StdDraw.square(x, y, size/2); }
这样每次绘制正方形时,都会生成一个全新的随机填充色,完美替换原来的默认浅灰色。
完整修改后的代码
把所有改动整合起来,最终的代码是这样的:
import java.awt.Color; import java.util.Random; public class Exercise5 { public static Color randomColor() { Random random = new Random(); int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); return new Color(red, green, blue); } public static void drawSquare(double x, double y, double size) { StdDraw.setPenColor(randomColor()); StdDraw.filledSquare(x, y, size/2); StdDraw.setPenColor(StdDraw.BLACK); StdDraw.square(x, y, size/2); } public static void draw(int n, double x, double y, double size) { if (n == 0) return; drawSquare(x, y, size); double ratio = 2.2; draw(n-1, x - size/2, y - size/2, size/ratio); // lower left draw(n-1, x - size/2, y + size/2, size/ratio); // upper left draw(n-1, x + size/2, y - size/2, size/ratio); // lower right draw(n-1, x + size/2, y + size/2, size/ratio); // upper right } public static void main(String[] args) { int n = 6; double x = 0.5, y = 0.5; // center of square double size = 0.5; // side length of square draw(n, x, y, size); } }
额外小提示(可选)
如果你不想每个正方形都完全随机,比如希望同一递归层级的正方形用相同颜色,可以调整颜色生成的时机:在draw方法里先生成颜色,再传给drawSquare:
public static void draw(int n, double x, double y, double size) { if (n == 0) return; Color currentLevelColor = randomColor(); // 生成当前层级的统一颜色 drawSquare(x, y, size, currentLevelColor); double ratio = 2.2; draw(n-1, x - size/2, y - size/2, size/ratio); draw(n-1, x - size/2, y + size/2, size/ratio); draw(n-1, x + size/2, y - size/2, size/ratio); draw(n-1, x + size/2, y + size/2, size/ratio); } // 修改drawSquare方法,接收颜色参数 public static void drawSquare(double x, double y, double size, Color fillColor) { StdDraw.setPenColor(fillColor); StdDraw.filledSquare(x, y, size/2); StdDraw.setPenColor(StdDraw.BLACK); StdDraw.square(x, y, size/2); }
这样同一层级的正方形会共用一个随机颜色,下一层级再生成新颜色,也是一种很有意思的视觉效果~
内容的提问来源于stack exchange,提问作者user9247053
相关产品推荐
相关产品推荐

