1. Yaron Minsky
  2. hack-and-slash

Source

hack-and-slash / state.ml

open Core.Std
open Vec.Export
open Direction.Export
open Action.Export

module Player = struct
  type t = { pos: Vec.t
           }
  with sexp, bin_io
end

type t =
  { players: Player.t Player_name.Map.t
  ; max_x: int
  ; max_y: int
  }
with sexp, bin_io

let create () =
  { players = Player_name.Map.empty
  ; max_x = 100
  ; max_y = 100
  }

let register_player t pname =
  let players' =
    Map.change t.players pname (function
      | None ->
        let player = { Player.
                       pos = vec (Random.int t.max_x) (Random.int t.max_y) }
        in
        Some player
      | Some _ as x -> x
    )
  in
  { t with players = players' }

let act t pname action =
  match Map.find t.players pname with
  | None ->
    (t,Update.of_string "Unknown player")
  | Some player ->
    match action with
    | Move d ->
      let delta = Direction.to_vec d in
      let player' = { Player. pos = Vec.add player.Player.pos delta } in
      let players' = Map.add t.players ~key:pname ~data:player' in
      ({ t with players = players' }, Update.empty)
    | Display ->
      (t, sexp_of_t t |> Sexp.to_string |> Update.of_string)