SFML: Setup and Installation
SFML (Simple and Fast Multimedia Library) is C++'s most popular library for 2D graphics, windows, input, and audio, think of it as C++'s answer to Python's Pygame. It handles opening a window and drawing shapes so you can focus on game logic instead of low-level graphics APIs.
Installing SFML
- Ubuntu/Debian:
sudo apt install libsfml-dev - macOS (Homebrew):
brew install sfml - Windows: install via
vcpkg install sfml, or download prebuilt binaries from the SFML website and point your IDE at them.
Compiling with SFML
SFML is split into modules, a game needs at least graphics, window, and system:
g++ main.cpp -o breakout -lsfml-graphics -lsfml-window -lsfml-system
./breakout
Opening a window
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "Breakout");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear(sf::Color::Black);
window.display();
}
return 0;
}
Reading it line by line
sf::RenderWindow window(sf::VideoMode(800, 600), "Breakout")creates an 800x600 window titled "Breakout".- The outer
while (window.isOpen())is the game loop, it keeps running every frame until the window closes. - The inner
while (window.pollEvent(event))drains every pending event (key presses, window close, etc.) this frame,sf::Event::Closedfires when the user clicks the close button. window.clear(...)wipes the previous frame, andwindow.display()swaps the finished frame onto the screen, without both of these you'd see nothing, or a smeared trail of every frame ever drawn.
TIP
Forgetting window.pollEvent(event) entirely makes the window freeze and appear "Not Responding", the OS needs your program to keep handling events even if you don't care about most of them.