Algorithm for Client-Server Games

后端 未结 6 1556
谎友^
谎友^ 2021-01-30 11:59

For stand alone games, the basic game loop is (source: wikipedia)

while( user doesn\'t exit )
  check for user input
  run AI
  move enemies
  resolve collisions         


        
6条回答
  •  生来不讨喜
    2021-01-30 12:24

    It really isn't a simple problem. At a most basic level you could say that the network provides the same data that the MoveEnemies part of the original loop did. So you could simply replace your loop with:

    while( user doesn't exit )
      check for user input
      run AI
      send location to server
      get locations from server
      resolve collisions
      draw graphics
      play sounds
    end while
    

    However you need to take into account latency so you don't really want to pause your main loop with calls to the network. To overcome this it is not unusual to see the networking engine sitting on a second thread, polling for data from the server as quickly as it can and placing the new locations of objects into a shared memory space:

    while(connectedToNetwork)
        Read player location
        Post player location to server
        Read enemy locations from server
        Post enemy locations into shared memory
    

    Then your main loop would look like:

    while( user doesn't exit )
      check for user input
      run AI
      read/write shared memory
      resolve collisions
      draw graphics
      play sounds
    end while
    

    The advantage of this method is that your game loop will run as fast as it can, but the information from the server will only be updated when a full post to and from the server has been completed. Of course, you now have issues with sharing objects across threads and the fun with locks etc that comes with it.

    On the server side the loop is much the same, there is one connection per player (quite often each player is also on a separate thread so that the latency of one won't affect the others) for each connection it will run a loop like

    while (PlayerConnected)
        Wait for player to post location
        Place new location in shared memory
    

    When the client machine requests the locations of enemies the server reads all the other players locations from the shared block of memory and sends it back.

    This is a hugely simplified overview and there are many more tweaks that will improve performance (for instance it may be worth the server sending the enemy positions to the client rather than the client requesting them) and you need to decide where certain logically decisions are made (does the client decide whether he has been shot because he has the most up to date position for himself, or the server to stop cheating)

提交回复
热议问题