Ocaml Lwt - some implementations of multiplayer game

此生再无相见时 提交于 2019-12-07 23:15:09

问题


I'm going on to writing a simple implementation of tic-tac-toe server (via telnet). The task - players connect to server and after they send START the server looks for a partner who typed START too, and game begins. A piece of code:

let handle_income () =
        let con = Lwt_unix.accept sock in 
        con >>= fun (cli, addr) ->
        let player = Lwt.return {state = Sleeping; descriptor = Lwt.return cli} in
        send_to_client player "Welcome to the server. To start game type in START and press Enter";
        player;;

let rec make_ready player = 
        player >>= fun {state; descriptor} ->
            send_to_client player "Waiting for start command";
            let answer = read_from_client player in 
                answer >>= fun str ->
                match str with
                    |"Start" -> 
                        let ready_client =  Lwt.return { state = Ready; descriptor = descriptor} in 
                        ready_client
                    | _ -> 
                        send_to_client player "Unknown command. try again";
                        make_ready player;;

I'm completely new to Ocaml (Lwt especially). So, will you be so kind as to give to me a piece of advice how to make players' START to look for another player? Should I use list with all-time iteration checking players state, high-level functions which waits for the second player typed START(I'm not sure it's possible), Lwt wakers, Lwt broadcast, creating another a' Lwt wich is Sleep until has 2 Lwt.t players or something? I don't know how to implement that the cleverest way. Thank you much.


回答1:


One possibility:

Have the connect function put each new connection in a Lwt_mvar.

Have a Lwt.async thread that loops. On each iteration take two connections from the mvar and spawn a game between them.



来源:https://stackoverflow.com/questions/32160010/ocaml-lwt-some-implementations-of-multiplayer-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!