メニュー 閉じる

072. Processingでランダムな四角を画面に充填してみる

025を四角に。色情報は以下のイメージから取得しています。

ArrayList<Square> squares;

PImage img;

void setup () {

	size (1200, 800);
	pixelDensity (2);

	squares = new ArrayList<Square> ();

	img = loadImage ("image.png");
	img.loadPixels ();

}

void draw () {

	background (0);

	int total = 100;
	int count = 0;
	int attempts = 0;

	while (count < total) {
		Square nc = new_square ();
		if (nc != null ) {
			squares.add (nc);
			count++;
		}
		attempts++;
		if (attempts > 1000) {
			noLoop ();
			println ("FINISHED");
			break;
		}

	}

	for (Square c : squares) {
		if (c.growing) {
			if (c.edges ()) {
				c.growing = false;
			} else {
				for (Square other : squares) {
					if (c != other) {
						float dx = abs (c.x - other.x);
						float dy = abs (c.y - other.y);
						if (dx - 2 < c.rx + other.rx && dy - 2 < c.ry + other.ry) {
							c.growing = false;
							break;
						}
					}
				}
			}
		}
		c.grow ();
		c.render ();
	}

}

Square new_square () {

	float x = random (width);
	float y = random (height);

	boolean valid = true;

	for (Square c : squares) {
		float dx = abs (x - c.x);
		float dy = abs (y - c.y);
		if (dx < c.rx && dy < c.ry) {
			valid = false;
			break;
		}
	}

	if (valid) {
		int index = int (x) + int (y) * img.width;
		color col = img.pixels[index];
		return new Square (x, y, col);
	} else {
		return null;
	}

}
class Square {

	float x;
	float y;
	float rx;
	float ry;
	color c;

	boolean growing = true;

	Square (float cx, float cy, color cc) {

		x = cx;
		y = cy;
		rx = 1;
		ry = 1;
		c = cc;

	}

	void grow () {

		if (growing) {
			rx += 0.5;
			ry += 0.5;
		}

	}

	boolean edges () {

		return (x + rx > width || x - rx < 0 || y + ry > height || y - ry < 0);

	}

	void render () {

		//stroke (255);
		//noFill ();
		fill (c);
		noStroke ();
		rectMode (CENTER);
		rect (x, y, rx * 2, ry * 2);

	}

}

 

Posted in processing