Reader small image

You're reading from  SFML Game Development

Product typeBook
Published inJun 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781849696845
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
 Artur Moreira
Artur Moreira
author image
Artur Moreira

Artur Moreira is a game development enthusiast who ultimately aims to start a new game development company in his home country. He has been programming games and game-related software for over 4 years. Most of the effort in that time was put in creating an open source game-making library with lots of flexibility and portability. The library is called Nephilim and is known for supporting all major desktop and mobile operating systems, making game development fully crossplatform and fast. Alongside this big project, he keeps making his own prototypes and games for educational and commercial purposes. Aside from the programming, he also puts some focus in creative areas such as 3D modeling, digital painting, and music composing.
Read more about Artur Moreira

 Henrik Vogelius Hansson
Henrik Vogelius Hansson
author image
Henrik Vogelius Hansson

Henrik Vogelius Hansson has always been in love with both games and programming. He started his education fairly early and continued on into the indie scene with Defrost Games and their game Project Temporality. The next company that hired him was Paradox Development Studio where he got to work on titles such as Crusader Kings 2. Beside the game companies, Henrik has also been very active in the SFML community and has even provided a binding for Ruby called rbSFML.
Read more about Henrik Vogelius Hansson

Jan Haller
Jan Haller
Henrik Valter Vogelius
Henrik Valter Vogelius
View More author details
Right arrow

Chapter 10. Company Atop the Clouds – Co-op Multiplayer

After a long journey through to the book, with lots of lessons learned, we have now arrived at the last chapter. This is where we will handle a topic with growing importance in the modern times—networking. This subject shall not be overlooked as it can be very difficult to learn and implement. It is complicated enough for people to actually dedicate their careers on dealing exclusively with it. Usually network programmers are very experienced and good at it, so they can do it efficiently and provide a good multiplayer gameplay to the end users.

Obviously, even if we wanted to, we couldn't teach every single thing about network programming, good practices, and different implementations. However, we try to pass on some knowledge on how to achieve a multiplayer experience, keeping things as simple as possible. Based on the game we've built so far throughout the book, we now add two new concepts: local cooperation and actual network gameplay...

Playing multiplayer games


We've seen multiplayer games since computer games emerged—decades ago. We are used to calling friends and family to play games with us, sometimes in a co-operative mode with common goals and other times for a competitive experience. The point is that playing with someone else is usually lots of fun!

There was a time when the Internet barely existed, or simply put, people's connections were too slow to actually have a good online experience. By then, it was very usual for games to have a local multiplayer mode. This allowed a big trend for split screen and other types of local multiplayer gameplay. Local Area Network (LAN) multiplayer was also implemented as a way to make the experience more cooperative to players, and as a result, you could actually cooperate or fight with your friends over a cable or wireless network. Unfortunately, as time passed and the Internet became more powerful, the local multiplayer modes became less and less used, and actual online multiplayer...

Interacting with sockets


First of all, in order to go deeper in to network programming, we need to understand how computers communicate with each other. This is the technological base that everyone should know before trying to do anything with networking.

This topic is not simple by itself, but it can be approached more easily without the need to understand the deeper concepts, with the help of SFML's socket classes.

A socket is essentially a gateway for data. You can visualize it as a link between two applications. These applications are virtual, in the sense, they only matter in the network, but are not necessarily different application processes, because you can use sockets to connect an application to itself, as we do in this chapter. These sockets are the base of all networked programs; therefore, they are extremely important. As sockets are a rather complicated concept, SFML provides classes to manage them.

There are the following two main ways of communicating between multiple machines...

Data transport


We already know some things about how sockets behave and their inner workings, but we only talked about sending and receiving data in an abstract way. We referred to the data as arrays of bytes, which we simply send and receive, but how is it done?

Indeed, what is passed on through the network is merely a block of data, a collection of raw bytes. Therefore, it must be sent in a way that can be read again by the remote machine. Your data could be anything, text, numbers, images, sound, or pretty much anything that is digital.

For this, we pack and unpack our data into a byte array when sending/receiving it! When we use the term packet, we refer to a collection of bytes, which contain one or more primitives (integers, floats, and others). This is very efficient from the perspective that we don't have additional overhead for sending multiple primitives; they all go at once in the same byte array. However, we have a per-packet overhead, namely the packet headers that are required...

Network architectures


Regardless of socket types and protocols, games take different approaches in the architecture of the multiplayer mode.

We call the playable game application a client, network-wise, and this part of the book concerns how clients communicate with each other and who they communicate with.

There are at least two major approaches to a networked simulation.

Peer-to-peer

This architecture was and still is used in online games; however, it fits a very specific set of purposes and is used less widely than its counterpart client-server architecture.

Nevertheless, its importance should be noticed and mentioned every time networking is the topic. What defines this architecture is essentially the fact that every game client in the simulation connects to each other. You can see it in the following figure:

These inter-connections between all the clients, which somehow resemble a spider's web, mean that every client has a connection with every client. This way, they effectively communicate...

Creating the structure for multiplayer


You must be fed up with networking theory by now, and you actually want to see some code! Right, it is now time to start the concrete implementation of our game server.

In order to extend our game and add an online mode to it, we went ahead and created a new state MultiplayerGameState, which is very similar to GameState at first. In the following code snippet, you see the important parts of the class definition. As you see, the three typical state-related methods to draw, update, and handle events are again there, as well as the variables for the world, window, and texture holder. Several variables are new related to the management of different players and socket connections:

class MultiplayerGameState : public State
{
    public:
                         MultiplayerGameState(StateStack& stack,Context context, bool isHost);

        virtual void     draw();
        virtual bool     update(sf::Time dt);
        virtual bool     handleEvent(const sf...

Working with the Server


Now it is time to put our hands on the actual server! We will be dissecting the GameServer class to understand properly what is going on.

Server thread

To begin with, we decided to put the server in a separate thread. This is very useful in many ways. For once, server processing can be intensive and could hurt the frame rate on the client. On the other hand, if the server is running on a parallel thread, aside from improving its performance, it also allows it to perform blocking calls whenever necessary, and the game keeps running smoothly. Another plus in this approach is that our server does not communicate programmatically with the client, it communicates only via network; therefore, we don't even need to care about synchronization between the two. It is just like as if server is running on a different application!

As we have already introduced sf::Thread before in Chapter 5, Diverting the Game Flow – State Stack, we will skip that topic here. It is important to notice...

Taking a peek in the other end – the client


We have looked in the server extensively and have hopefully clarified all systems and learned how they come together to form a single object that services a lot of clients at once, and potentially even more aircraft! Now let's look at the other end, the client, and see how we took a jump from a single-player-only game into a fully-networked game.

Let's examine the MultiplayerGameState constructor first:

sf::IpAddress ip;
if (isHost)
{
    mGameServer.reset(new GameServer());
    ip = "127.0.0.1";
}
else
{
    ip = getAddressFromFile();
}
  
if (mSocket.connect(ip, ServerPort, sf::seconds(5.f)) ==   sf::TcpSocket::Done)
    mConnected = true;
else
    mFailedConnectionClock.restart();

mSocket.setBlocking(false);
...

We need to deduce which IP to communicate with, in order to successfully join a game. If we are the host, we just connect to the loopback address 127.0.0.1, otherwise, we need to connect to a pseudo-remote server. This means that in practice...

Latency


Programming and maintaining efficient server software is already a very hard task; however, to add even more complexity to this duty, we must deal with latency too. This topic is very broad but we will still try to give you some starting tips on how to deal with these issues.

Roughly, latency is the delay a network packet takes to reach its destination. The bigger the latency, the more we get behind in the networked simulation, and in consequence, the gameplay gets worse.

This little nightmare is one of the hardest troubles to deal with in network programming. It will make players have a different experience based on their connection and other network conditions, that is, it will make the game very smooth for some players while completely unplayable for others; it will be a mess. Unfortunately, it is not in the hands of the programmer to deal with the network's latency at all. A programmer can at best prepare the software to behave a little better in the worst case scenarios, where...

Cheating prevention


By now you probably are scratching your chin and asking yourself: "But is this secure? Is a hacky player able to exploit the game to its benefit somehow?"

If you answered "No" to yourself, you are correct. By all means we would like to explain you how to make every little thing cheat-proof. However, we don't want to give you the fish by bloating the code with lots of validations; but rather, explicitly writing about how you can learn how to fish.

The current game, as is, is not cheat-proof whatsoever. There are a lot of validations that are not performed, so it will only work predictably until a clever user starts doing packet-sniffing and sending things that are not really expected by our protocol.

Let's try to understand how cheating could be achieved in our particular case, and how would we prevent it by looking at a few examples:

  • In the client's tick, we let the client decide where its planes are going to be at. If a user with malicious intent sent this packet after modifying...

Summary


In this final chapter, you learned about basic networking concepts. We had a look at sockets, different network architectures, and protocols. We incorporated this knowledge to our game, and extended the existing design to cope with new challenges of networking. By using SFML's Network module, we implemented a mechanism to communicate with other players on the same keyboard, the local area network, or the Internet. Although we had to make compromises in some places, you should have learned a lot of techniques which you can eventually apply in another game.

Along with this chapter, also ends the book! It has been a long ride all the way and we can only thank you for reading through our pages patiently. Finally, our aircraft top-scroller has reached a state where it is not only playable, but contains many features to create an immersive experience. We began with rendering, resource and input handling, and went over to shape different states and menus with a graphical user interface....

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SFML Game Development
Published in: Jun 2013Publisher: PacktISBN-13: 9781849696845
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Artur Moreira

Artur Moreira is a game development enthusiast who ultimately aims to start a new game development company in his home country. He has been programming games and game-related software for over 4 years. Most of the effort in that time was put in creating an open source game-making library with lots of flexibility and portability. The library is called Nephilim and is known for supporting all major desktop and mobile operating systems, making game development fully crossplatform and fast. Alongside this big project, he keeps making his own prototypes and games for educational and commercial purposes. Aside from the programming, he also puts some focus in creative areas such as 3D modeling, digital painting, and music composing.
Read more about Artur Moreira

author image
Henrik Vogelius Hansson

Henrik Vogelius Hansson has always been in love with both games and programming. He started his education fairly early and continued on into the indie scene with Defrost Games and their game Project Temporality. The next company that hired him was Paradox Development Studio where he got to work on titles such as Crusader Kings 2. Beside the game companies, Henrik has also been very active in the SFML community and has even provided a binding for Ruby called rbSFML.
Read more about Henrik Vogelius Hansson