I'm trying to setup a very simple multiplayer game that allows some users to join and walk around. The game is 2D and the players will have a position, the direction they are looking in (it's a top-down game) and their animation frame index (so they can be animated for all clients). This is my game loop that I have at the moment:
private void run()
{
long lastTick = 0;
long tickDelay = 33;
int tps = 0;
int ticks = 0;
long lastTickCount = 0;
List<Connection> toRemove = new List<Connection>();
while (!shouldStop)
{
lock (connections)
{
if (connections.Count != 0)
{
foreach (Connection connection in connections)
{
if (!connection.IsInitialized)
{
if (connection.Initialize())
{
BroadcastChatMessage(connection.Username + " has joined");
}
else
{
Console.WriteLine("Disconnected " + connection.IP + ": failed to authenticate");
connection.Close();
toRemove.Add(connection);
}
}
else
{
int cmd = connection.ReceiveCommand();
if (cmd == -1)
{
BroadcastChatMessage(connection.Username + " has left");
connection.Close();
toRemove.Add(connection);
}
}
}
}
if (toRemove.Count != 0)
{
foreach (Connection connection in toRemove)
{
connections.Remove(connection);
}
toRemove.Clear();
}
}
ticks++;
long now = CurrentTimeMillis;
if (now - lastTickCount >= 1000)
{
lastTickCount = now;
tps = ticks;
ticks = 0;
}
int connectionsCount = 0;
lock (connections)
{
connectionsCount = connections.Count;
}
Console.Title = "Top-Down Multiplayer Server [TPS: " + tps + ", Connected: " + connectionsCount + "]";
lastTick = CurrentTimeMillis;
Thread.Sleep(20);
while (CurrentTimeMillis - lastTick <= tickDelay) { }
}
}
I have a simple mechanism that makes the server run at 30 ticks per second with a Thread.Sleep
to free up CPU. Should I be processing data from all the clients in the same thread like this? What should the ticks per second be determined by? Am I on the right track with this loop?
P.S: In the future I would process the game after I handle connections and before I do ticks++
(after I receive client data and before I count the ticks per second).