Wednesday, July 10, 2024

Update Tanks (坦克大战) with network support

With Revisit 坦克大战编程, can easily build Tanks on Windows or under WSL. However, with one player the game would be a bit boring and a bit frustrate; and with two player2 on same PC, it would be a bit crowd for four hands on one keyboard. If would be more attractive if two players can play together remotely, or even play against each other, would be much fun. So, we need to bring in network support. Would need to choose a  suitable networking library, (e.g., SDL_net, which complements SDL, or another networking library like Boost.Asio for C++). Need to initialize the networking in the application, setting up one instance as the server and the other as the client.

I haven't been using either network library. So will pick SDL_net since we already have used other library from SDL. SDL_net was moved to github as: https://github.com/libsdl-org/SDL_net. Similar as other SDL libraries, I downloaded SDL2_net-devel-2.2.0-VC.zip.

Now it's time to deep dive to the code to understand the design. The main loop is App::run with state of m_app_state check/switch, eventProces, m_app_state->update, m_app_state->draw, and FPS control. m_app_state initially is pointing to an instance of Menu, then it is pointing to an instance of Game, Scores and Menu sequentially after invoke of nextState, which updates the state machine. Menu is the state to allow user to select player and quit, Scores is the state to show the score. So we most are interested of the Game state.

It would be complex to maintain two state machine on two hosts, even one is a mirror of the other. Need to clone all object on fly, with dynamic create and destroy, and need to merge input from both side, and one side needs to be the master for random number generation, state control by user. Also consider network latency, might be a bit messy to maintain the sync between server and client. The easier approach would be let the master to maintain the state machine, for client side, just relay the input to server, and mirror the render result from server.

(to be continue)

0 Comments:

Post a Comment