Source

OCaml-Chip8 / src / interpreter.ml

Full commit
(*
** interpreter.ml for OCaml-Chip8 in /home/surply_p
** 
** Made by Pierre Surply
** <pierre.surply@gmail.com>
** 
** Started on  Sun Aug  5 12:31:47 2012 Pierre Surply
** Last update Sun Aug  5 17:13:51 2012 Pierre Surply
*)

open Chip8
open Opcode

let load_game str =
  let f = open_in str in
  let rec r_read n = 
    try
      let b = input_byte f in
      chip8.mem.(n + start_addr) <- b;
      r_read (n + 1)
    with End_of_file -> close_in f
  in
  r_read 0

let get_cmd op =
  let rec r_get_cmd op = function
    | -1 -> -1
    | x -> 
      if (opcodes.(x).mask land op) = opcodes.(x).id 
      then x 
      else r_get_cmd op (x-1)
  in
  r_get_cmd op (nb_opcode-1)

let interpret op = 
  let n = op land 0x000F in
  let y = (op land 0x00F0) lsr 4 in
  let x = (op land 0x0F00) lsr 8 in
  let kk = op land 0x00FF in
  let nnn = op land 0x0FFF in
  begin
    match get_cmd op with
      | 0  -> ();
      | 1  -> cls ();
      | 2  -> ret ();
      | 3  -> jmp_addr nnn;
      | 4  -> call_addr nnn;
      | 5  -> se_vx_byte x kk;
      | 6  -> sne_vx_byte x kk;
      | 7  -> se_vx_vy x y;
      | 8  -> ld_vx_byte x kk;
      | 9  -> add_vx_byte x kk;
      | 10 -> ld_vx_vy x y;
      | 11 -> or_vx_vy x y;
      | 12 -> and_vx_vy x y;
      | 13 -> xor_vx_vy x y;
      | 14 -> add_vx_vy x y;
      | 15 -> sub_vx_vy x y;
      | 16 -> shr_vx_vy x y;
      | 17 -> subn_vx_vy x y;
      | 18 -> shl_vx_vy x y;
      | 19 -> sne_vx_vy x y;
      | 20 -> ld_i_addr nnn;
      | 21 -> jp_v0_addr nnn;
      | 22 -> rnd_vx_byte x kk;
      | 23 -> drw_vx_vy_nibble x y n;
      | 24 -> skp_vx x;
      | 25 -> sknp_vx x;
      | 26 -> ld_vx_dt x;
      | 27 -> ld_vx_k x;
      | 28 -> ld_dt_vx x;
      | 29 -> ld_st_vx x;
      | 30 -> add_i_vx x;
      | 31 -> ld_f_vx x;
      | 32 -> ld_b_vx x;
      | 33 -> ld_mem_vx x;
      | 34 -> ld_vx_mem x;
      | _ -> ()
  end;
  chip8.pc <- chip8.pc + 2