Introduction to coding
About this tutorial
The purpose of this tutorial is to introduce how coding works, with the C++ language here, by creating and explaining, step by step, the code of a small 2D game. In other words, the goal is to provide an overview of programming with the C++ language. If you wish to learn to code or to improve your C++ skills, you will find, at the end of this tutorial, a link to a free and in-depth C++ course.The code of the game and some coding concepts will be explained, but keep in mind that this is an introduction and not a course. After this tutorial, you should have an idea of how coding works, but if you want to really understand it, you should follow a course.
Some theory
Before getting into the creation of the game, let us have a very quick look at the C++ language.Variables
A variable is simply a memory space which has a name. It is used to store data.The following line of code defines (creates) a variable of type 'int' (A type able to hold integer numbers) and named 'var':
int var;
var = 33;
var = var + 10;
Functions
A function is a group of instructions that has been assigned a name. It can return a value, which can be seen as its result.Here is the definition (creation) of a function:
int func(int arg)
{
return arg;
}
- The first 'int' indicates that the function returns a value of type 'int' (An integer number).
- The name of the function is 'func'.
- It takes a parameter of type 'int' and referred to as 'arg'.
- The instructions of a function are located inside its braces. Here, its only instruction has the effect of returning the value of the parameter it received.
We can call the function defined above, like such:
func(46);
The main function
Here is a minimal C++ code that does... nothing.int main()
{
return 0;
}
The main function returns the error code (number) 0 to the operating system, indicating that the program ended successfully.
SFML
The C++ language does not directly provide tools to display graphics. To do so, we must use sets of tools called libraries. This tutorial uses the library SFML, which provides a multitude of functionalities, the drawing of pictures and the management of windows included.Once a library is installed, we must write a line of code to include it to the project, so it can be used within the code. The following line of code includes the graphical functionalities of SFML:
#include <SFML/Graphics.hpp>
Objects
A class is a special type of variable. A class is made up of variables (Called members) and functions (Called methods) that execute tasks such as modifying its members. A variable of a class type is called an object.If we consider that the following line of code defines (creates) an object:
Window win;
win.open();
win.title;
Window win(arg1, arg2, arg3);