Add terminal color manipulation.
[cellular-automata.git] / polymorphism / 001 / src / polymorphism.ml
index 1c47e0b..cb65462 100644 (file)
@@ -197,6 +197,39 @@ module Conway : RULE = struct
 end
 
 
+module Terminal : sig
+  type color = [ `green
+               | `red
+               ]
+
+  val string_with_color : string -> color -> string
+
+  val clear : unit -> unit
+
+  val reset : unit -> unit
+end = struct
+  type color = [ `green
+               | `red
+               ]
+
+  let ansi_code_clear = "\027[2J"    (* Clear screen *)
+  let ansi_code_reset = "\027[1;1H"  (* Reset cursor position *)
+
+  let string_of_color = function
+    | `green -> "\027[0;32m"
+    | `red   -> "\027[1;31m"
+
+  let string_with_color s c =
+    sprintf "%s%s\027[0m" (string_of_color c) s
+
+  let clear () =
+    print_string ansi_code_clear
+
+  let reset () =
+    print_string ansi_code_reset
+end
+
+
 module Automaton : sig
   type t
 
@@ -227,6 +260,7 @@ end = struct
       ; data = Rule.create ()
       }
     in
+    Terminal.clear ();
     { grid     = Matrix.map ~f:init (Matrix.create ~rs ~ks ())
     ; interval = Time.Span.of_float interval
     ; bar      = String.make ks '-'
@@ -236,6 +270,7 @@ end = struct
     cell.data.Cell.pheno
 
   let print t =
+    Terminal.reset ();
     print_endline t.bar;
     Matrix.print t.grid ~to_string:cell_to_string;
     print_endline t.bar
@@ -271,7 +306,7 @@ let main () =
     [ (module Conway : RULE)
     ]
   in
-  Automaton.create ~rows:(rows - 3) ~columns ~interval ~rules |> Automaton.loop
+  Automaton.loop (Automaton.create ~rows:(rows - 3) ~columns ~interval ~rules)
 
 
 let spec =
This page took 0.026506 seconds and 4 git commands to generate.