Brownian tree: Difference between revisions
Content added Content deleted
Line 2,317: | Line 2,317: | ||
[[File:BrownianTree.png]] |
[[File:BrownianTree.png]] |
||
=={{header|Nim}}== |
|||
Using "bitmap.nim" created for Rosetta Bitmap task. |
|||
<lang Nim>import bitmap |
|||
import random |
|||
import nimPNG |
|||
const |
|||
Size = 400 # Area size. |
|||
MaxXY = Size - 1 # Maximum possible value for x and y. |
|||
NPart = 25_000 # Number of particles. |
|||
Background = Black # Background color. |
|||
Foreground = color(50, 150, 255) # Foreground color. |
|||
randomize() |
|||
let image = newImage(Size, Size) |
|||
image.fill(Background) |
|||
image[Size div 2, Size div 2] = Foreground |
|||
for _ in 1..NPart: |
|||
block ProcessParticle: |
|||
while true: # Repeat until the particle is freezed. |
|||
# Choose position of particle. |
|||
var x, y = rand(MaxXY) |
|||
if image[x, y] == Foreground: |
|||
continue # Not free. Try again. |
|||
# Move the particle. |
|||
while true: |
|||
# Choose a motion. |
|||
let dx, dy = rand(-1..1) |
|||
inc x, dx |
|||
inc y, dy |
|||
if x notin 0..MaxXY or y notin 0..MaxXY: |
|||
break # Out of limits. Try again. |
|||
# Valid move. |
|||
if image[x, y] == Foreground: |
|||
# Not free. Freeze the particle at its previous position. |
|||
image[x - dx, y - dy] = Foreground |
|||
break ProcessParticle # Done. Process next particle. |
|||
# Save into a PNG file. |
|||
# Unfortunately, nimPNG expects a sequence of bytes, not a sequence of colors. |
|||
# So, we have to make a copy. |
|||
var data = newSeqOfCap[byte](image.pixels.len * 3) |
|||
for color in image.pixels: |
|||
data.add([color.r, color.g, color.b]) |
|||
echo savePNG24("brownian.png", data, image.w, image.h)</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |