Алгоритм для игр клиент-сервер

Вы должны вызывать функцию, а не назначать объект функции. Добавление () в конце должно исправить это

currentDate: string = new Date().toDateString();
15
задан Click Ok 13 June 2013 в 13:43
поделиться

5 ответов

Это было бы что-то вроде

Клиент:

while( user does not exit )
    check for user input
    send commands to the server
    receive updates about the game from the server
    draw graphics
    play sounds
end

Сервер:

while( true )
    check for client commands
    run AI
    move all entities
    resolve collisions
    send updates about the game to the clients
end
19
ответ дан 1 December 2019 в 00:50
поделиться

Client:

connect to server
while( user does not exit && connection live)
    check for user input
    send commands to the server
    estimate outcome and update world data with 'best guess'
    draw graphics
    play sounds
    receive updates about the game from the server
    correct any errors in world data
    draw graphics
    play sounds
end

Server:

while( true )
    check for and handle new player connections
    check for client commands
    sanity check client commands
    run AI
    move all entities
    resolve collisions
    sanity check world data
    send updates about the game to the clients
    handle client disconnects
end

The sanity checks on the client commands and world data are to remove any 'impossible' situations caused either by deliberate cheating (moving too fast, through walls etc) or lag (going through a door that the client thinks is open, but the server knows is closed, etc).

In order to handle lag between the client and server the client has to make a best guess about what will happen next (using it's current world data and the client commands) - the client will then have to handle any discrepancies between what it predicted would happen and what the server later tells it actually happened. Normally this will be close enough that the player doesn't notice the difference - but if lag is significant, or the client and server are out of synch (for example due to cheating), then the client will need to make an abrupt correction when it receives data back from the server.

There are also lots of issues regarding splitting sections of these processes out into separate threads to optimise response times.

One of the best ways to start is to grab an SDK from one of the games that has an active modding community - delving into how that works will provide a good overview of how it should be done.

12
ответ дан 1 December 2019 в 00:50
поделиться

Это действительно не простая проблема. На самом базовом уровне можно сказать, что сеть предоставляет те же данные, что и часть MoveEnemies исходного цикла. Таким образом, вы можете просто заменить свой цикл на:

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

Однако вам нужно учитывать задержку, чтобы вы действительно не хотели приостанавливать свой основной цикл вызовами в сеть. Чтобы преодолеть это, нет ничего необычного в том, чтобы сетевой движок сидел во втором потоке, опрашивая данные с сервера так быстро, как мог, и помещая новые местоположения объектов в общую область памяти:

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

Тогда ваш основной цикл будет выглядит так:

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

Преимущество этого метода в том, что ваш игровой цикл будет выполняться так быстро, как только возможно, но информация с сервера будет обновляться только после завершения полной записи на сервер и с сервера. Конечно, теперь у вас есть проблемы с разделением объектов между потоками и с забавами, связанными с блокировками и т. Д.

На стороне сервера цикл почти такой же,

4
ответ дан 1 December 2019 в 00:50
поделиться

Клиентская часть в основном такая же, за исключением замены

run AI
move enemies
resolve collisions

на

upload client data to server
download server updates

И сервер просто делает:

while (game is running)
{
    get all clients data
    run AI
    resolve collisions
    udpate all clients
}
3
ответ дан 1 December 2019 в 00:50
поделиться

Вы можете использовать почти То же самое, но большая часть вашей логики будет на сервере, вы можете поместить таймеры, звуки, графику и другие компоненты пользовательского интерфейса в клиентское приложение. Любое бизнес-правило (AI, Movements) относится к серверной части.

3
ответ дан 1 December 2019 в 00:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: