graphicsモジュールで遊ぶ3

2分木。

  • m分木にしたい(今は2だけ)
  • 描く方向を変えたい(今は上方向だけ)
open Graphics
    
let f x0 y0 r =
  let draw x y = draw_segments [|(x0, y0, x0+x, y0+y)|]in
    draw (-r) r;
    draw r r

let rec g x y n r=
  match (n,r) with
      (0,_) -> ()
    | (_,0) -> ()
    | _ -> 
	f x y r;
	g (-r+x) (r+y) (n - 1) (r/2);
	g (r+x) (r+y) (n - 1) (r/2)

let h n =
  let fx () = Random.int (size_x ())
  and fy () = Random.int (size_y ()) 
  and c () = Random.int 255 in
  let f () = g (fx()) (fy()) (Random.int 10) (Random.int 100)in
  let rec loop = function
      0 -> ()
    | n -> 
	set_color (rgb (c()) (c()) (c()));
	set_line_width (Random.int 10);
	f ();
	loop (n - 1)
  in
    loop n

let () =
  open_graph " 600x600";
  set_line_width 1;
  g 300 0 10 150;
  h 20;
  Unix.sleep 3;
  close_graph ()

追記

枝の長さは同じ方がいいかも

let f x0 y0 x y =
  let draw x y = draw_segments [|(x0,y0, x0+x, y0+y)|] in
    draw (-x) y;
    draw x y

let rec g x y dx dy n =
  match n with
      0 -> ()
    | _ ->
	f x y dx dy;
	g (x-dx) (y+dy) (dx/2) dy (n - 1);
	g (x+dx) (y+dy) (dx/2) dy (n - 1)