Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
SFML Game Development By Example
SFML Game Development By Example

SFML Game Development By Example: Create and develop exciting games from start to finish using SFML

eBook
AU$41.99 AU$60.99
Paperback
AU$75.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

SFML Game Development By Example

Chapter 2. Give It Some Structure – Building the Game Framework

Working on a project with poor structure is much like building a house with no foundation: it's difficult to maintain, extremely unstable, and will probably cause you to abandon it shortly. While the code we worked on in Chapter 1, It's Alive! It's Alive! – Setup and First Program, is functional and can be managed on a very small scale, expanding it without first building a solid framework would most likely result in tons of spaghetti code (not to be confused with ravioli code or lasagna code) being present. Although it sounds delicious, this pejorative term describes the pain of a new feature being exponentially more difficult to implement within the source code that is unstructured and executes in a "tangled" manner, which is something we'll be focusing on avoiding.

In this chapter we will cover:

  • Designing a window class, along with a main game class
  • Code restructuring and...

Graduating to ravioli

Let's start small. Every game needs to have a window, and as you already know from Chapter 1, It's Alive! It's Alive! – Setup and First Program, it needs to be created, destroyed, and its events need to be processed. It also needs to be able to clear the screen and update itself to show anything drawn after the screen was cleared. Additionally, keeping track of whether the window is being closed and if it's in full-screen mode, as well as having a method to toggle the latter would be quite useful. Lastly, we will, of course, need to draw to the window. Knowing all of that, the header of our window class will predictably look something like this:

class Window{
public:
    Window();
    Window(const std::string& l_title,const sf::Vector2u& l_size);
    ~Window();

    void BeginDraw(); // Clear the window.
    void EndDraw(); // Display the changes.

    void Update();

    bool IsDone();
    bool IsFullscreen();
    sf::Vector2u GetWindowSize...

Implementing the window class

Now that we have our blueprint, let's begin actually building our window class. The entry and exit points seem as good a place as any to start with:

Window::Window(){ Setup("Window", sf::Vector2u(640,480)); }

Window::Window(const std::string& l_title, const sf::Vector2u& l_size)
{
    Setup(l_title,l_size);
}

Window::~Window(){ Destroy(); }

Both implementations of the constructor and destructor simply utilize the helper methods which we'll be implementing shortly. There's also a default constructor that takes no arguments and initializes some pre-set default values, which is not necessary, but it's convenient. With that said, let's take a look at the setup method:

void Window::Setup(const std::string l_title, const sf::Vector2u& l_size)
{
    m_windowTitle = l_title;
    m_windowSize = l_size;
    m_isFullscreen = false;
    m_isDone = false;
    Create();
}

Once again, this is quite simple. As mentioned before,...

Building the game class

We've done a good job at wrapping up the basic functionality of our window class, but that's not the only chunk of code in need of refactoring. In Chapter 1, It's Alive! It's Alive! – Setup and First Program, we've discussed the main game loop and its contents, mainly processing input, updating the game world and the player, and finally, rendering everything on screen. Cramming all of that functionality into the game loop alone is generally known to produce spaghetti code, and since we want to move away from that, let's consider a better structure that would allow this kind of behavior:

#include "Game.h"

void main(int argc, void** argv[]){
    // Program entry point.
    Game game; // Creating our game object.
    while(!game.GetWindow()->IsDone()){
        // Game loop.
        game.HandleInput();
        game.Update();
        game.Render();
    }
}

The code above represents the entire content of our main.cpp file...

Hardware and execution time

Let's travel back in time to May 5, 1992. Apogee Software begins publishing the now known cult classic Wolfenstein 3D developed by id Software:

Hardware and execution time

The man with the vision, John Carmack, took massive strides forward and not only popularized, but also revolutionized the first person shooter genre on the PC. Its massive success cannot be overstated, as even now it's difficult to accurately predict how many times it has been downloaded. Having grown up at right around that time, one can't help but feel nostalgic sometimes and attempt to play this game again. Ever since its original release for the DOS operating system on the PC, it has been ported to many other operating systems and consoles. While it's still possible to play it, we've come a long way since the days of using DOS. The environment our software runs in has fundamentally changed, ergo the software from the past is no longer compatible, hence the need for emulation.

Note

An emulator...

Using the SFML clock

The sf::Clock class is very simple and lightweight, so it has only two methods: getElapsedTime() and restart(). Its sole purpose is to measure elapsed time since the last instance of the clock being restarted, or since its creation, in the most precise manner the operating system can provide. When retrieving the elapsed time using the getElapsedTime method, it returns a type sf::Time. The main reasoning behind that is an additional layer of abstraction to provide flexibility and avoid imposing any fixed data types. The sf::Time class is also lightweight and provides three useful methods for conversion of elapsed time to seconds which returns a floating point value, milliseconds, which returns a 32-bit integer value and microseconds, which returns a 64-bit integer value, as represented here:

sf::Clock clock;
...
sf::Time time = clock.getElapsedTime();

float seconds = time.asSeconds();
sf::Int32 milliseconds = time.asMilliseconds();
sf::Int64 microseconds = time.asMicroseconds...

Graduating to ravioli


Let's start small. Every game needs to have a window, and as you already know from Chapter 1, It's Alive! It's Alive! – Setup and First Program, it needs to be created, destroyed, and its events need to be processed. It also needs to be able to clear the screen and update itself to show anything drawn after the screen was cleared. Additionally, keeping track of whether the window is being closed and if it's in full-screen mode, as well as having a method to toggle the latter would be quite useful. Lastly, we will, of course, need to draw to the window. Knowing all of that, the header of our window class will predictably look something like this:

class Window{
public:
    Window();
    Window(const std::string& l_title,const sf::Vector2u& l_size);
    ~Window();

    void BeginDraw(); // Clear the window.
    void EndDraw(); // Display the changes.

    void Update();

    bool IsDone();
    bool IsFullscreen();
    sf::Vector2u GetWindowSize();

    void ToggleFullscreen...

Implementing the window class


Now that we have our blueprint, let's begin actually building our window class. The entry and exit points seem as good a place as any to start with:

Window::Window(){ Setup("Window", sf::Vector2u(640,480)); }

Window::Window(const std::string& l_title, const sf::Vector2u& l_size)
{
    Setup(l_title,l_size);
}

Window::~Window(){ Destroy(); }

Both implementations of the constructor and destructor simply utilize the helper methods which we'll be implementing shortly. There's also a default constructor that takes no arguments and initializes some pre-set default values, which is not necessary, but it's convenient. With that said, let's take a look at the setup method:

void Window::Setup(const std::string l_title, const sf::Vector2u& l_size)
{
    m_windowTitle = l_title;
    m_windowSize = l_size;
    m_isFullscreen = false;
    m_isDone = false;
    Create();
}

Once again, this is quite simple. As mentioned before, it initializes and keeps track of some...

Building the game class


We've done a good job at wrapping up the basic functionality of our window class, but that's not the only chunk of code in need of refactoring. In Chapter 1, It's Alive! It's Alive! – Setup and First Program, we've discussed the main game loop and its contents, mainly processing input, updating the game world and the player, and finally, rendering everything on screen. Cramming all of that functionality into the game loop alone is generally known to produce spaghetti code, and since we want to move away from that, let's consider a better structure that would allow this kind of behavior:

#include "Game.h"

void main(int argc, void** argv[]){
    // Program entry point.
    Game game; // Creating our game object.
    while(!game.GetWindow()->IsDone()){
        // Game loop.
        game.HandleInput();
        game.Update();
        game.Render();
    }
}

The code above represents the entire content of our main.cpp file and perfectly illustrates the use of a properly...

Left arrow icon Right arrow icon

Key benefits

  • Familiarize yourself with the SFML library and explore additional game development techniques
  • Craft, shape, and improve your games with SFML and common game design elements
  • A practical guide that will teach you how to use utilize the SFML library to build your own, fully functional applications

Description

Simple and Fast Multimedia Library (SFML) is a simple interface comprising five modules, namely, the audio, graphics, network, system, and window modules, which help to develop cross-platform media applications. By utilizing the SFML library, you are provided with the ability to craft games quickly and easily, without going through an extensive learning curve. This effectively serves as a confidence booster, as well as a way to delve into the game development process itself, before having to worry about more advanced topics such as “rendering pipelines” or “shaders.” With just an investment of moderate C++ knowledge, this book will guide you all the way through the journey of game development. The book starts by building a clone of the classical snake game where you will learn how to open a window and render a basic sprite, write well-structured code to implement the design of the game, and use the AABB bounding box collision concept. The next game is a simple platformer with enemies, obstacles and a few different stages. Here, we will be creating states that will provide custom application flow and explore the most common yet often overlooked design patterns used in game development. Last but not the least, we will create a small RPG game where we will be using common game design patterns, multiple GUI. elements, advanced graphical features, and sounds and music features. We will also be implementing networking features that will allow other players to join and play together. By the end of the book, you will be an expert in using the SFML library to its full potential.

Who is this book for?

This book is intended for game development enthusiasts with at least decent knowledge of the C++ programming language and an optional background in game design.

What you will learn

  • Create and open a window by using SFML
  • Utilize, manage, and apply all of the features and properties of the SFML library
  • Employ some basic game development techniques to make your game tick
  • Build your own code base to make your game more robust and flexible
  • Apply common game development and programming patterns to solve design problems
  • Handle your visual and auditory resources properly
  • Construct a robust system for user input and interfacing
  • Develop and provide networking capabilities to your game

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 29, 2015
Length: 522 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287343
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 29, 2015
Length: 522 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287343
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
AU$249.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts
AU$349.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 219.97
SFML Game Development
AU$67.99
SFML Game Development By Example
AU$75.99
Procedural Content Generation for C++ Game Development
AU$75.99
Total AU$ 219.97 Stars icon

Table of Contents

15 Chapters
1. It's Alive! It's Alive! – Setup and First Program Chevron down icon Chevron up icon
2. Give It Some Structure – Building the Game Framework Chevron down icon Chevron up icon
3. Get Your Hands Dirty – What You Need to Know Chevron down icon Chevron up icon
4. Grab That Joystick – Input and Event Management Chevron down icon Chevron up icon
5. Can I Pause This? – Application States Chevron down icon Chevron up icon
6. Set It in Motion! – Animating and Moving around Your World Chevron down icon Chevron up icon
7. Rediscovering Fire – Common Game Design Elements Chevron down icon Chevron up icon
8. The More You Know – Common Game Programming Patterns Chevron down icon Chevron up icon
9. A Breath of Fresh Air – Entity Component System Continued Chevron down icon Chevron up icon
10. Can I Click This? – GUI Fundamentals Chevron down icon Chevron up icon
11. Don't Touch the Red Button! – Implementing the GUI Chevron down icon Chevron up icon
12. Can You Hear Me Now? – Sound and Music Chevron down icon Chevron up icon
13. We Have Contact! – Networking Basics Chevron down icon Chevron up icon
14. Come Play with Us! – Multiplayer Subtleties Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9
(22 Ratings)
5 star 50%
4 star 18.2%
3 star 9.1%
2 star 13.6%
1 star 9.1%
Filter icon Filter
Top Reviews

Filter reviews by




CS Mar 22, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book will help you in creating simple games using SFML, provided you have basic c++ skills, which I am sure all posses. You will get good understanding of SFML library and it's various elements. The book is well written and has lot of examples to work with. Overall, one should not miss this book if looking for simple game development.
Amazon Verified review Amazon
Tom Bass Jan 08, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this book a few days ago and started reading it cover to cover. Even though I am not finished, I'd like to share my reading experience:It is well written (even though I am not a native English speaker) and clear to understand. A lot of code examples help you to get your feet wet and start using the read stuff in your games. It is not a cookbook, but gives you a helping hand on specific topics.Personally I took a lot of new knowledge from the chapters on Entity Component Design and UI implementation in SFML.Chapters 13 and 14 about network look promising (which I haven't read yet) and hopefully give me a better understanding to implement some multiplayer stuff into my upcoming games.One thing that is important to the reader: you have to have a solid understanding of C++ and should have written a few programs. Also you should know how to create a new program in Visual Studio, because the introduction is a bit too fast. Also I would like to have in the next editions of this book some cross platform approach on how to setup SFML and start coding in different operating systems. But these are wishes I have and do not reduce the great value of the book.
Amazon Verified review Amazon
Gaff Jul 28, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Contrary to what other reviewers have posted, you do not need to purchase the book on the publisher's website to access the book's materials, but you do need to use an email address to create an account with them.Regardless, this is quite possibly the most important book for budding game developers with some C++ programming experience. Everything you learned from the more technical primers or tomes of design patterns and theory is put to good use here, stripped of academic fluff and straight to the point: "here's how to put together an extensible game engine (almost) from scratch" plus useful patterns to keep with you for future projects. All you need is this book, a suitable IDE and a copy of SFML, and you'll have a solid foundation for game development by the end of it.On the technical side, though the sparing use of modern language features like smart pointers is regrettable and would simplify some examples (especially in class destructors), with only some minor and obvious tweaks, they can be brought up to modern standards.For those in doubt, this author clearly explains what an ECS is and teaches the reader how to correctly implement the pattern. Though the end result is not nearly as extensible and powerful as more popular implementations like EnTT, what's here is a rare, near-perfect demonstration of the pattern in practice.
Amazon Verified review Amazon
Mike Quint Mar 10, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Raimondas has put together a great product in "SFML Game Development by Example". This will be one of my go to resources in the future - whether it is for SFML game development or for general program architecture ideas. Here is why. The author provides the user with 3 different game projects:1 - a Snake game, which is used to teach the concepts of the game loop and gives the reader an opportunity to dabble with the basic features of SFML2 - a side scroller, in which the author walks the reader through the development of an event manager, a state manager, a resource manager, a mapping engine, and finally animation. Meanwhile, you are shown how to make your game projects data driven so that you don't have to program your own key bindings, events, maps, and animations within the code - just add the right data to a text file and add the necessary resources. Easy! A cool feature - the author walks you through the concept of layering your maps (common in games for sure but this has usages outside of game development - Photoshop anyone?)3 - a top down RPG, where the author walks you through the creation of an Entity-Component-System engine (a major undertaking for sure - last time I checked this is how games are made in todays AAA titles), a GUI manager (which has uses in anything that requires human interaction beyond text based programs), and a sound manager (which the author walks you through the process of creating a garbage collection mechanism). The RPG is finished off with an example of SFMLs networking library.This book is more then just a game development book. As I've noted, there are other programming problems solved throughout the book which made this book even more enjoyable for me to learn from. I highly recommend that if you purchase this book that you download the sample code - especially if you intend to recode the samples yourself. This book isn't perfect and there are time where I needed to rely on the sample code to figure out what I was doing wrong. The SFML forums are also helpful if you run into snag - the author frequents the forums and has been quite helpful when I've been stuck on a problem.
Amazon Verified review Amazon
Michael N. Mar 02, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Alongside my degree, this is a great book. I have an assingment to design and create a 2D graphical application. Helping me a lot with this!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.