Advertisement
ptrelford

Koch Snowflake

Nov 26th, 2014
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.10 KB | None | 0 0
  1. #r "System.Drawing.dll"
  2. #r "System.Windows.Forms.dll"
  3.  
  4. open System
  5. open System.Drawing
  6. open System.Windows.Forms
  7.  
  8. let width, height = 512, 512
  9.  
  10. let black = 0,0,0
  11. let white = 255,255,255
  12. let red = 183,51,32
  13. let green = 45, 140, 108
  14. let blue = 68, 116, 178
  15.  
  16. let toBrush (r,g,b) =
  17.    let color = Color.FromArgb(255,r,g,b)
  18.    new SolidBrush(color)
  19.  
  20. let snowflake (graphics:Graphics) length =
  21.    let pen = ref (new Pen(toBrush white))
  22.    let angle = ref 0
  23.    let x = ref ((float width/2.0) - length/2.0)
  24.    let y = ref ((float height/2.0) - length/3.0)
  25.    let n = length
  26.    
  27.    let rec draw n depth =
  28.       if depth = 0 then
  29.          line n
  30.       else
  31.          let d = n/3.0
  32.          pen := new Pen(toBrush red)
  33.          draw (n/3.0) (depth-1)
  34.          rotate -60        
  35.          pen := new Pen(toBrush green)
  36.          draw (n/3.0) (depth-1)
  37.          rotate 120
  38.          pen := new Pen(toBrush blue)
  39.          draw (n/3.0) (depth-1)
  40.          rotate -60
  41.          pen := new Pen(toBrush red)
  42.          draw (n/3.0) (depth-1)
  43.    and line n =
  44.       let r = (float !angle * Math.PI) / 180.0
  45.       let x2 = float !x + cos(r) * n
  46.       let y2 = float !y + sin(r) * n
  47.       graphics.DrawLine(!pen, float32 !x,float32 !y, float32 x2, float32 y2)
  48.       x := x2
  49.       y := y2
  50.    and rotate a =
  51.       angle := !angle + a
  52.  
  53.    let depth = 3
  54.    pen := new Pen(toBrush red)
  55.    draw n depth
  56.    rotate 120
  57.    pen := new Pen(toBrush green)
  58.    draw n depth
  59.    pen := new Pen(toBrush blue)
  60.    rotate 120
  61.    draw n depth
  62.  
  63. let draw () =  
  64.    let image = new Bitmap(width, height)
  65.    use graphics = Graphics.FromImage(image)  
  66.    let brush = toBrush black
  67.    graphics.FillRectangle(brush, 0, 0, width, height)
  68.    for i in 10.0..20.0..360.0 do
  69.       snowflake (graphics) i
  70.    image
  71.  
  72. let show () =
  73.    let image = draw ()
  74.    let form = new Form (Text="Koch Snowflake", Width=width+16, Height=height+36)  
  75.    let picture = new PictureBox(Dock=DockStyle.Fill, Image=image)
  76.    image.Save(@"C:\app\Koch.png", Imaging.ImageFormat.Png)
  77.    do  form.Controls.Add(picture)
  78.    form.ShowDialog() |> ignore
  79.  
  80. show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement