Creating a SFML game

Greetings to all igrodelov and their sympathizers. In this article I want to talk about a framework such as SFML, and try to write a simple game on it (in our case it will be a clone of the legendary Pong).

v

Download and Install


You can download the framework from the official site . At the moment, two versions are available for download - 1.6 and 2.0. I used version 2.0 for Visual C ++ 2010. You can choose the option SFML for your OS and compiler.

Since the purpose of the article is not to discuss the features of connecting libraries in different IDEs, the installation guide can be read at . site . I’ll try to lead the story without being tied to any OS and compiler.

Create the foundation


From libraries, we will need only sfml-graphics, sfml-window, sfml-system (you can connect sfml-main for cross-platform main function). We begin to create the skeleton of the future game.

#include <SFML/Graphics.hpp>

int main()
{
    // Создаем главное окно приложения
    sf::RenderWindow window(sf::VideoMode(800, 600), "Pong");

    // Главный цикл приложения
    while(window.isOpen())
    {
        // Обрабатываем события в цикле
        sf::Event event;
        while(window.pollEvent(event))
        {
            // Кроме обычного способа наше окно будет закрываться по нажатию на Escape
            if(event.type == sf::Event::Closed || 
              (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
                window.close();
        }

        // Очистка
        window.clear();
        // Тут будут вызываться функции обновления и отрисовки объектов
        // Отрисовка
        window.display();
    }

    return 0;
}


So what have we done here? In the first line, the Graphics.hpp header file was connected , and then we created the main () function and a 800X600-sized window with the title “Pong”.

SFML provides convenient event management tools. We use them to create the application cycle and process window events. With the help of the loop, we implement closing the window by pressing Escape. Generally, sf :: Event provides the ability to work not only with the keyboard, but also, for example, with the mouse. In addition, you can work with some system events, and do not rewrite the code for each new platform. So, if you want to use the joystick in the game, then you do not have to rewrite half the code - it will be enough to add a couple of lines to the processing cycle.

Next, we clear the window and draw the contents of the buffer. Everything, the game frame is ready, you can compile and test the work. A black window should appear in front of you.

Racket


In Pong, there are only two kinds of objects - a racket and a ball. We will deal with the ball in the next article, and we will create the racket class now. But first, we need to add a few lines to main () .

// Создаем переменную таймера (нужен для плавной анимации)
sf::Clock clock;
float time;
// Включаем вертикальную синхронизацию (для плавной анимации)
window.setVerticalSyncEnabled(true);
/* Ставим эти строки после window.clear(). Здесь мы сохраняем прошедшее время в миллисекундах и перезапускаем таймер */
time = clock.getElapsedTime().asMilliseconds();
clock.restart();


Now let's start creating the Paddle class . I have given here only the basic methods, everything else you can see in the source (download link at the end of the article).

class Paddle {
	sf::RenderWindow* window; // Указатель на окно, нужен для отрисовки
	sf::RectangleShape rectangle; // Собственно, сама ракетка
	int y; // Координата y ракетки (x мы задаем в коде)
        int player; // Номер игрока (1 или 2)
        int score; // Переменная для хранения счета
public:
        // Конструктор
	Paddle(sf::RenderWindow* window, int player) {
                this->score = 0;
		this->y = 300;
		this->player = player;

		this->window = window;
                // Устанавливаем размер для ракетки с помощью Vector2f
		this->rectangle.setSize(sf::Vector2f(10, 100));
                // Для удобства перенесем основную точку из левого верхнего угла в центр
		this->rectangle.setOrigin(5, 50);
                // И устанавливаем ракетки в начальные позиции
		if(this->player == 1) {
			this->rectangle.setPosition(25, this->y);
		}
		else {
			this->rectangle.setPosition(775, this->y);
		}
        }
        // Метод для отрисовки ракетки
        void draw() {
		this->window->draw(this->rectangle);
	}
        /* Обработка нажатия клавиш и перемещение ракеток
        Первый игрок управляет стрелками, второй -- клавишами W и S */
        void update(float time) {
		if(this->player == 1) {
			if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
                                // Изменяем положение ракетки в зависимости от времени таймера
				this->y -= time * 0.3; 
				this->setY(this->y); // setY - сеттер для переменной Y
			}
			else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
				this->y += time * 0.3;
				this->setY(this->y);
			}
		}
		else {
			if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
				this->setY(this->y - time * 0.3);
			}
			else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
				this->setY(this->y + time * 0.3);
			}
		}
	}


A racket of 10X100 size will serve us as a racket. We set the size using the Vector2f class - this is quite an ordinary vector, in the future it will be useful to us for setting the direction of the ball.

In addition to the event system, SFML has another way to handle input devices. We use it to control the rackets from the keyboard. You can also transfer the player’s control to the mouse - for this, accordingly, sf :: Mouse (or sf :: Joystick ) will be used .

In the source code, I recommend paying attention to the setY method - he checks the coordinates of the racket and prevents it from going out of the field.

Now you can create a pair of Paddle objects and call the draw and update methods after clearing the window. If you compile the source code, you will see two racquets on opposite sides of the window, the first is controlled using the up, down arrow keys, the second is controlled by W and S.

Conclusion


For now, we will stop there, and in the next article I will tell you how to create a ball class and a points system.
Sources .