Skip to content

Instantly share code, notes, and snippets.

@phagenlocher
Last active April 12, 2018 10:04
Show Gist options
  • Select an option

  • Save phagenlocher/19767c1d799cce9f261f6fb6dc0cac49 to your computer and use it in GitHub Desktop.

Select an option

Save phagenlocher/19767c1d799cce9f261f6fb6dc0cac49 to your computer and use it in GitHub Desktop.
Xmas Tree in OCaml
(* ocamlc unix.cma xmas.ml *)
type color = RST | RED | GRN | YEL | BLU | MAG | CYN | WHT
let rec mult_list n l = if n <= 0 then [] else l @ (mult_list (n-1) l)
let tree_elems = (mult_list 5 [GRN, ">"; GRN, "<"]) @
[RED, "@"; BLU, "O"; MAG, "o"; YEL, "*"]
let snow_elems = (mult_list 15 [" "]) @ [".";",";"'";"*"]
let color_print c s =
let colorcode = function
| RST -> "0"
| RED -> "31"
| GRN -> "32"
| YEL -> "33"
| BLU -> "34"
| MAG -> "35"
| CYN -> "36"
| WHT -> "37"
in
let color_str = "\x1B[1;" ^ (colorcode c) ^ "m"
in
print_string (color_str ^ s)
let color_reset () = color_print RST "\n"
let random_elem l = List.nth l (Random.int (List.length l))
let print_snow n =
let rec snow_str n =
if n <= 0 then ""
else (random_elem snow_elems) ^ (snow_str (n-1))
in color_print WHT (snow_str n)
let print_tree h sp =
let rec random_level w =
if w <= 0 then ()
else
let co, ch = random_elem tree_elems
in
color_print co ch; random_level (w-1)
in
let rec print_levels i =
if i <= 0 then ()
else
if i = h then (
print_snow (i+sp);
color_print YEL ("*");
print_snow (i+sp);
print_newline ();
print_levels (i-1)
)
else (
print_snow (i+sp);
color_print GRN (">");
random_level (2*(h-i)-1);
color_print GRN ("<");
print_snow (i+sp);
print_newline ();
print_levels (i-1)
)
in
print_levels h;
print_snow (h-1+sp);
color_print WHT "| |";
print_snow (h-1+sp);
print_newline ();
print_snow (h-3+sp);
color_print WHT "__|_|__";
print_snow (h-3+sp)
let save_int_of_string s d =
try
int_of_string s
with
_ -> d
let get_term_size h w =
let ic = Unix.open_process_in "stty size" in
let out = Pervasives.input_line ic in
match (String.split_on_char ' ' out) with
| [nh; nw] -> save_int_of_string nh h, save_int_of_string nw w
| _ -> h, w
let _ =
Random.self_init ();
let th, tw = get_term_size 40 80 in
let w = tw-1 in
let h = (min w th) - 20 in
print_snow (w); print_newline ();
print_snow (w); print_newline ();
print_snow (w); print_newline ();
print_snow (w); print_newline ();
print_snow (w); print_newline ();
print_tree h ((w-(h*2))/2);
color_reset ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment