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
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
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 : 9781785283000
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 $5 each
Feature tick icon Exclusive print discounts
$279.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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
SFML Game Development
$48.99
SFML Game Development By Example
$54.99
Procedural Content Generation for C++ Game Development
$54.99
Total $ 158.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.