Diffusion-limited Aggregation(DLA)扩散限制凝聚,其效果是非常无规则的,看上去非常的cool。用php代码实现了一个快速简单的有限制扩散凝聚,并将结果输出到了图片上。
代码中的step和size不建议设置太大,否则,需要等待超长的时间。现在的值,基本上需要执行60秒左右。如果需要改进,可以考虑粒子随机直线运动的优化。
看看效果:
代码在这里:
<pre class="brush:php;"> set_time_limit(0); // 关闭代码执行时间限制
$s = 100; // 图片大小
$step = 500; // step
$area = 2;
$image = imagecreate($s, $s);
imagecolorallocate($image,255,255,255);
$color = imagecolorallocate($image,0,0,0);
$s2 = $s/2;
$grid[$s2][$s2] = 1;
imagesetpixel($image,$s2,$s2,$color);
while($i<$step){
//calculate releasing area
$n = max($max_x - $min_x, $max_y - $min_y) + $area;
$s2mn = $s2-$n;
$s2an = $s2+$n;
//release a molecule
do{
$x = rand($s2mn,$s2an);
$y = rand($s2mn,$s2an);
}while($grid[$x][$y]);
//move the molecule randomly
while(!($grid[$x-1][$y-1]+$grid[$x-1][$y]+$grid[$x-1][$y+1] +
$grid[$x][$y-1]+$grid[$x][$y+1]+$grid[$x+1][$y-1] +
$grid[$x+1][$y]+$grid[$x+1][$y+1])){
$x += rand(-1,1);
$y += rand(-1,1);
if($x<$s2mn||$x>$s2an||$y<$s2mn||$y>$s2an){
continue 2;
}
}
$grid[$x][$y] = 1;
if($max_x<$x){
$max_x = $x;
}elseif($min_x>$x){
$min_x = $x;
}
if($max_y<$y){
$max_y = $y;
}elseif($min_y>$y){
$min_y = $y;
}
imagesetpixel($image,$x,$y,$color);
++$i;
}
header("Content-type: image/png");
imagepng($image);
```
<p>
参考地址:</p>
DLA php