Skip to content

Instantly share code, notes, and snippets.

@MattOates
Last active Feb 9, 2020
Embed
What would you like to do?
Dirty script to render the Mandelbrot set to the terminal
sub terminal-width(:$default=100) {
my $width = run('tput', 'cols', :out).out.slurp-rest.trim.Int;
return $width < $default ?? $default !! $width;
}
sub is-mandelbrot(Complex $z0, int $max=100) {
my Complex $z = $z0;
for ^$max -> $n {
return $n if ($z.abs() > 2e0);
$z = $z**2 + $z0;
}
return $max;
}
my @shades = [" ","","","",""];
sub MAIN(num :$mid-x=-0.4e0, num :$mid-y=0e0, num :$zoom=2e0, int :$width = terminal-width(:default<100>), int :$height=50) {
for ^$height -> $j {
my $row = "";
for ^$width -> $i {
my num $x = $mid-x - $zoom/2e0 + $zoom*$i/$width;
my num $y = $mid-y - $zoom/2e0 + $zoom*$j/$height;
my Complex $z0 = Complex.new($x, $y);
if $zoom == 2e0 {
$row ~= @shades[floor(is-mandelbrot($z0,10) / 2.5e0)];
} else {
$row ~= @shades[floor(is-mandelbrot($z0) / 25e0)];
}
}
say $row;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment