Explore Free C++ Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Thu, 06 Apr 2023 08:46:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free C++ Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Complete C++ Beginners Tutorial (Free) https://gamedevacademy.org/cpp-beginners-tutorial/ Thu, 06 Apr 2023 08:46:07 +0000 https://gamedevacademy.org/?p=21621 Read more]]> According to the TIOBE Index, since the 1990’s C++ has consistently ranked as one of the top 5 programming languages.

As a general-purpose, low-level programming language, C++ is widely used for everything from desktop apps to video games. It’s efficient, battle-tested, powerful, and highly in-demand throughout the tech industry. Thus, as you can imagine, it’s not a bad language to learn and add to your toolset!

Through this article, we’re going to cover the basics of C++ in a beginner-friendly way so you can master the principles and get ready to apply them to real-world applications.

Let’s jump into it!

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Introduction to C++

What is C++

C++ is a high-level programming language that was created by Bjarne Stroustrup in the early 1980s. It is an extension of the C programming language and is considered to be one of the most widely used programming languages in the world. C++ is used to develop a variety of applications, including games, desktop applications, system software, and much more.

History of C++

C++ was created as an extension of the C programming language in order to add object-oriented programming (OOP) features to the language. The first version of C++ was released in 1985, and it has gone through several updates and improvements over the years. Today, C++ is considered to be a powerful and flexible language that is widely used in many different industries and fields.

Advantages of using C++

C++ has many advantages that make it a popular choice among developers. Some of the main advantages of using C++ include:

  • It is a fast and efficient language that can handle large and complex applications.
  • C++ has a rich set of features, including object-oriented programming, which makes it easy to develop complex and feature-rich applications.
  • C++ has a large and active community of developers who contribute to its development and offer support to other users.
  • There are many resources available for learning C++, including books, tutorials, and online courses, making it easy for new users to get started.

Getting Started with C++

Getting started with C++ is easy, even if you have no prior programming experience. All you need is a basic understanding of how computers work and a willingness to learn. To get started with C++, you will need a compiler, which is a program that can compile and run your C++ code.

Setting up the Development Environment

To get started with C++ programming, you will need to set up a development environment. This typically involves installing a compiler and a code editor on your computer. There are many free compilers and code editors available, including GCC and Code::Blocks, that you can use to get started with C++ programming.

Visual demo of data structures for C++

C++ Fundamentals

Variables and Data Types

In C++, a variable is a named location in memory that is used to store a value. The value stored in a variable can be of different data types, including integers, floating-point numbers, and characters. Here’s an example of declaring and initializing an integer variable in C++:

int age = 25;

In this example, the variable “age” is declared as an integer and is initialized with the value 25. In C++, there are several basic data types, including:

  • Integers (int): used to store whole numbers
  • Floating-point numbers (float, double): used to store real numbers
  • Characters (char): used to store individual characters
  • Booleans (bool): used to store true/false values

Operators and Expressions

In C++, operators are symbols that perform operations on values and variables. For example, the “+” operator can be used to add two values:

int x = 10;
int y = 20;
int result = x + y;

In this example, the values of “x” and “y” are added together using the “+” operator and the result is stored in the variable “result”. In C++, there are several types of operators, including:

  • Arithmetic operators ( +, -, *, /, % )
  • Comparison operators ( ==, !=, >, <, >=, <= )
  • Logical operators ( &&, ||, ! )
  • Assignment operators ( =, +=, -=, *=, /=, %= )

Control Flow Statements

Control flow statements are used to control the flow of execution of a program. Here’s an example of an if-else statement in C++:

int score = 75;

if (score >= 60) {
  cout << "You passed the exam!" << endl;
} else {
  cout << "You failed the exam." << endl;
}

In this example, the if-else statement is used to determine if the value stored in “score” is greater than or equal to 60. If it is, the message “You passed the exam!” is printed. If not, the message “You failed the exam.” is printed. In C++, the main control flow statements include:

  • If-else statements
  • For loops
  • While loops
  • Switch statements

Functions

In C++, functions are blocks of code that perform a specific task. Here’s an example of a simple function in C++:

#include 
using namespace std;

int addNumbers(int x, int y) {
  return x + y;
}

int main() {
  int result = addNumbers(5, 7);
  cout << "The result is: " << result << endl;
  return 0;
}

In this example, the function “addNumbers” takes two parameters (x and y) and returns their sum. The function is then called in the “main” function, where the result is stored in the “result” variable and printed to the console. Functions can greatly simplify your code and make it easier to reuse and maintain. In C++, you can also pass parameters to functions by reference or by value, and you can also have functions that do not return a value.

Text-based dungeon crawler made with C++

Advanced C++ Features

Pointers

Pointers are a fundamental concept in C++ that allow you to manipulate memory directly. With pointers, you can access the memory address of a variable and modify the value stored there. Here’s an example of using a pointer in C++:

#include 
using namespace std;

int main() {
  int age = 25;
  int *pAge = &age;
  
  cout << "Age: " << age << endl;
  cout << "Address of age: " << pAge << endl;
  cout << "Value of age using pointer: " << *pAge << endl;
  
  *pAge = 30;
  cout << "Age after modification: " << age << endl;
  
  return 0;
}

In this example, a pointer “pAge” is declared and assigned the address of the “age” variable. The value of “age” can then be accessed and modified using the pointer. Pointers can be used to dynamically allocate memory, pass parameters to functions by reference, and implement complex data structures like linked lists and trees.

Arrays and Strings

Arrays are used to store collections of values of the same data type. Here’s an example of declaring and initializing an array in C++:

#include 
using namespace std;

int main() {
  int numbers[5] = {1, 2, 3, 4, 5};
  
  for (int i = 0; i < 5; i++) {
    cout << numbers[i] << " ";
  }
  cout << endl;
  
  return 0;
}

In this example, an array “numbers” is declared and initialized with 5 values. The values in the array can be accessed using the array index, as demonstrated in the for loop. Strings are arrays of characters that are used to store text. Here’s an example of working with strings in C++:

#include 
#include 
using namespace std;

int main() {
  string name = "John Doe";
  
  cout << "Length of name: " << name.length() << endl;
  cout << "Third character of name: " << name[2] << endl;
  
  name[0] = 'A';
  cout << "Name after modification: " << name << endl;
  
  return 0;
}

In this example, a string “name” is declared and initialized with the value “John Doe”. The length of the string can be obtained using the “length” function, and individual characters can be accessed using the array index. Strings in C++ have many built-in functions for working with text, such as “substr”, “find”, and “replace”.

Structures and Classes

Structures and classes are used to create custom data types in C++. A structure is a collection

of variables of different data types, while a class is a blueprint for creating objects. Here’s an example of using a structure in C++:

#include 
using namespace std;

struct Person {
  string name;
  int age;
};

int main() {
  Person john;
  john.name = "John Doe";
  john.age = 25;
  
  cout << "Name: " << john.name << endl;
  cout << "Age: " << john.age << endl;
  
  return 0;
}

In this example, a structure “Person” is declared with two variables “name” and “age”. An object of type “Person” can then be created and its variables can be accessed and modified. Classes are similar to structures, but they provide additional features such as encapsulation, inheritance, and polymorphism. Here’s an example of using a class in C++:

#include 
using namespace std;

class Person {
  public:
    string name;
    int age;
    
    void print() {
      cout << "Name: " << name << endl;
      cout << "Age: " << age << endl;
    }
};

int main() {
  Person john;
  john.name = "John Doe";
  john.age = 25;
  
  john.print();
  
  return 0;
}

In this example, a class “Person” is declared with two variables “name” and “age”. A member function “print” is also declared to print the values of the variables. An object of type “Person” can then be created and its member function can be called to print the values of the variables.

Templates and Exception Handling

Templates in C++ allow you to write generic code that can work with any data type. Templates are especially useful for writing functions and classes that can work with multiple data types. Here’s an example of using a template function in C++:

#include 
using namespace std;

template 
T max(T a, T b) {
  return (a > b) ? a : b;
}

int main() {
  cout << "Max of 3 and 4: " << max(3, 4) << endl;
  cout << "Max of 3.14 and 2.71: " << max(3.14, 2.71) << endl;
  cout << "Max of John and Doe: " << max("John", "Doe") << endl;
  
  return 0;
}

In this example, a template function “max” is declared to find the maximum of two values. The function can be used with different data types, such as integers, floating-point numbers, and strings, as demonstrated in the main function. Exception handling in C++ allows you to handle errors and exceptional conditions in your code. Here’s an example of using exception handling in C++:

#include 
double divide(double a, double b) {
if (b == 0) {
throw "Division by zero error";
}

return a / b;
}

int main() {
double x, y;

cout << "Enter x: "; cin >> x;

cout << "Enter y: "; cin >> y;

try {
cout << "x / y = " << divide(x, y) << endl;
} catch (const char* error) {
cout << "Error: " << error << endl;
}

return 0;
}

Roguelike game made with C++

File Handling in C++

Introduction to File Handling

File handling is an important part of any programming language, and C++ is no exception. With file handling, you can store and retrieve data from files, which can be saved on your computer or other storage devices. In this section, we’ll cover the basics of file handling in C++, including how to read from and write to files.

Opening and Closing Files

Before you can read from or write to a file, you first need to open it. You can do this using the “fstream” library, which stands for “file stream”. The following code demonstrates how to open a file named “example.txt” for writing:

#include 
#include 

int main() {
  std::ofstream file("example.txt");
  
  if (file.is_open()) {
    file << "Hello, World!" << std::endl;
    file.close();
  } else {
    std::cout << "Unable to open file" << std::endl;
  }
  
  return 0;
}

In this example, we’re using the “ofstream” class, which stands for “output file stream”. The “open” method is called to open the file, and the “is_open” method is used to check if the file was successfully opened. If the file was opened successfully, we can write to it using the “<<” operator, just like we would with “cout”. Finally, the “close” method is called to close the file.

Reading from Files

Reading from files is just as easy as writing to them. You can use the “ifstream” class, which stands for “input file stream”. The following code demonstrates how to open a file named “example.txt” for reading:

#include 
#include 
#include 

int main() {
  std::ifstream file("example.txt");
  std::string line;
  
  if (file.is_open()) {
    while (getline(file, line)) {
      std::cout << line << std::endl;
    }
    
    file.close();
  } else {
    std::cout << "Unable to open file" << std::endl;
  }
  
  return 0;
}

In this example, we’re using the “ifstream” class to open the file for reading. The “getline” function is used to read a line of text from the file and store it in a string. The “while” loop continues reading lines until there are no more lines to read. Finally, the “close” method is called to close the file.

C++ Idle clicked game screenshot

Introduction to the Standard Template Library (STL)

The Standard Template Library (STL) is a collection of C++ templates and algorithms that are used to perform common programming tasks. The STL is designed to be efficient, reusable, and flexible, making it a powerful tool for any C++ programmer. In this section, we will introduce some of the most commonly used STL components and show you how to use them in your own programs.

STL Containers

One of the main components of the STL are the containers. Containers are used to store collections of objects, and there are several different types of containers to choose from, including arrays, vectors, lists, and more. Here’s an example of how to use a vector:

#include <vector>

#include <iostream>

int main() {
  std::vector < int > myNumbers;
  myNumbers.push_back(1);
  myNumbers.push_back(2);
  myNumbers.push_back(3);
  for (int i: myNumbers) {
    std::cout << i << std::endl;
  }
  return 0;

In this example, we create a vector of integers, and then use the `push_back()` method to add three numbers to the vector. We then use a range-based for loop to iterate over the vector and print out each number.

Common C++ Libraries

In addition to the Standard Template Library (STL), there are several other libraries that are commonly used in C++. Here is a list of some of the most important ones:

      • Boost – A collection of libraries that provide a wide range of functionality, including things like algorithms, data structures, and networking. Boost is known for its well-designed and highly optimized libraries, making it a popular choice among C++ developers.
      • OpenCV – A library for computer vision and image processing. It provides tools for things like object detection, face recognition, and video analysis. OpenCV is widely used in the field of computer vision and has a large community of users and contributors.
      • SFML – A library for multimedia development, including graphics, audio, and network functions. SFML is a great choice for developing 2D games and other multimedia applications.
      • Qt – A cross-platform framework for developing GUI applications. Qt provides a variety of tools for building user interfaces, connecting to databases, and handling user interactions. It is widely used for developing desktop, mobile, and embedded applications.
      • Armadillo – A library for linear algebra and optimization. Armadillo provides fast and efficient implementation of common linear algebra operations, making it a popular choice for scientific computing and machine learning applications.

These are just a few of the many libraries available for C++. By using libraries, you can save time and effort by leveraging pre-existing code and solutions, and focus on developing your own unique features and functionality.

Conclusion

Congratulations! You’ve made it through a comprehensive beginner’s guide to C++. You now have a solid foundation in the basics of the language, as well as some of its advanced features. With this knowledge, you are well on your way to becoming a proficient C++ programmer.

The journey doesn’t stop here though – now it’s time to put everything you learned about C++ into practical application.

Below, we’ve included a great collection of resources for not only expanding your knowledge of C++ further, but learning how to create your first C++ projects.

We hope you check them out, and we’re looking forward to seeing what else you program with the C++ language!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Drawing Sprites with SFML & C++ – Game Dev Tutorial https://gamedevacademy.org/sfml-cpp-sprites-tutorial/ Mon, 19 Dec 2022 01:00:27 +0000 https://gamedevacademy.org/?p=12495 Read more]]>

You can access the full course here: Discover SFML for C++ Game Development

Want more coding topics for a school environment? The Zenva Schools platform which offers online courses, classroom management tools, reporting, pre-made course plans, and more for teachers.

Drawing Sprites

We’ve seen how to draw a basic shape but realistically, most of our games will use more than shapes. We will want to place graphics, icons, and other images into our games and we do so via Sprites. Setting up a Sprite is generally done in two steps with SFML: first, we load in a texture, then we create a sprite and pass in the texture. Once we have the sprite set up, we can set attributes such as the size and position and then display it by drawing it into the window during the run loop.

In our project, we should create a folder called assets that contains any assets needed in our game. We only have 4 so there’s no need to further divide the assets folder. Copy the “enemy.png” and “background.png” images, the “damage.ogg” audio file, and the “Arial.ttf” font files from your provided files and paste them into the assets folder. We will only work with the Enemy.png image for now. To create a texture, we first create a texture variable and then call the loadFromFile() function, passing in the path to the file as a string. It returns true if successful and false otherwise so we should perform a boolean test to see if the load was successful. In our main function, write this code after the code to create the window and before the run loop:

sf::Texture texture;
if (!texture.loadFromFile("assets/enemy.png")) {
  std::cout << "Could not load enemy texture" << std::endl;
  return 0;
}

This will create a variable of type sf::Texture and load the image into it. If the load fails, we print an error message and return. Sometimes, the load for an asset fails for some unknown reason so we should handle any errors properly. You will need to #include <iostream> at the top of main.cpp as well. Once we have the texture, we can create a sprite object called enemySprite and pass in the texture like this:

sf::Sprite enemySprite;
enemySprite.setTexture(texture);

The sprite will only be as big as the image provided and will default to be at position (0,0) or in the upper left corner. We can change the position like this:

enemySprite.setPosition(sf::Vector2f(100,100));

Which brings the sprite 100 pixels out from the left and 100 pixels out from the right and increase the size of the sprite by scaling it like this:

enemySprite.scale(sf::Vector2f(1,1.5));

This will scale the width of the sprite by 1 (no change) and scale the height to 1.5x its original height. Notice how both functions take an sf::Vector2f as inputs and each needs an x and y value. In order to draw the sprite, we change the draw code to this:

window.clear();
window.draw(enemySprite);
window.display();

We always have to clear the window before drawing anything and display the window after we draw to it.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

What’s up everyone? Welcome to our tutorial on Drawing Sprites. Here we’ll get a quick intro into what sprites are from a game context and how to create and use them in SFML.

So this is actually a two step process, the first thing we need to do is create a texture object. Once we have that we can create a sprite from it and then we can set the position and the scale. So let’s head to the code and get started. Alright, so just a quick heads up again, I took all the code from the previous section, not that we really did very much and put it in old code and I’ll continue to do this with each new section.

Alright, so what is a sprite from a game context? Well essentially, a sprite is gonna be an object in the game that has an image associated with it. So this is really the main difference between let’s say shapes and sprites in games is that a sprite has an image and a shape just has well a shape. It just has its boundaries, it has some sort of code to dictate what shape those boundaries will take on, be of circles, square, rectangle, etc.

So in our case, the background of our game and the enemy itself, those are both going to be sprites, we’re not really gonna be working with shapes very much. So like I said this is a two step process. The first thing we need to do is load in a texture and a texture needs an image to load. So that’s why I had you load in your assets folder. So your project should look like this, sfml project, you have your codes, and then you have your assets folder with the items in it. We’ll use the ttf as a font later on. Same with the damage.ogg, that’s for sound. For now we’ll at least want the enemy.png because that’s what we’re gonna be working with here. Okay, so as long as we have it in our project assets /enemy.png, then we can load it in like this.

Okay, first thing that we’ll need to do is create a texture itself so we’ll do sf, Texture, texture. Okay, now a texture just like the Render Window is part of the SFML Graphics library. Anytime you need a new module, you’ll need to load it in here. Okay, so we have a texture object, we actually don’t need to call a constructor, set it equal to a texture or anything like that. Once we create the object, we have access to it immediately and we need to call the load from file function, like this texture.load From file, oops! Not load from stream we want load from file.

Okay, and then we’re going to pass in the path to the file. So in this case this is gonna be “assets/ “enemy “.png”. Now this is actually gonna return true or false based on the success or failure. So we’re gonna say something like if text actually, we’ll say if not texture.load from file, then maybe we’ll just print out some message and return. So let’s just close that off and this should actually be in here.

Okay, so in this case, what we can do is something like Standard c out, I actually don’t think we have the iOS stream library so I’m just gonna include that now. Include your stream. Okay, good stuff. Okay, so now what we’ll do is c out something like “Could not load, “enemy texture”. Okay, and then we’re just going to end it.

All right and because we really want the game to only run if the texture is loaded, we’re actually gonna return false. Cool, so as long as this is the case oh actually you know what? This is returning will turn zero. Okay, so as long as the texture is loaded, so as long as this doesn’t return zero, then we have a texture rather an image loaded into this texture, and now we can use it with a Sprite. So to do that, we’ll do basically the same process as with the texture, we need to create the sprite object first, Sprite and we’ll call this like enemySprites or something.

Okay, and then we’re going to call upon the enemySprite . setTexture function and then we’re I’m just going to pass in the texture that we loaded. Okay, so this will associate a texture with a Sprite. So now the sprite is created It has a texture and we can draw it. We don’t know exactly what size or position well we do know what position it will be in which will be 00 by default which will be upper left corner and the size will be exactly the size of the image itself. We can modify that later on, and which we’ll do in just a minute here.

Okay, so just using the default values, if we want to draw this to the window, we simply call upon the window.draw and then pass in the Sprite. So in this case, enemySprite. Okay, cool. So we’ll get this Save, and let’s run the code, let’s see what happens. So clear it, let’s compile it, and then let’s run it and now you can see that we have this little sprite in our game.

Obviously there are some issues here it’s getting cut off so the screen is not big enough to begin with. Also, this is kind of in the top left corner, we might not want it there and might not be quite big enough. Okay, so this is all stuff that we can just maybe let’s do a 500 by 500 window. That way we have enough size to draw most of the things that we need. Then if we go to rerun it, we should probably see that’s not gonna take up the whole screen anymore. It’s just take up a part of it. So maybe we don’t want it in the top left. Maybe we want it kind of a bit centered.

So what we can do is maybe move it about 100 pixels to the right and 100 pixels down, might put it roughly in the center, okay. So what we can do is take this enemy sprite, enemySprite, okay and we can set the position of it. So, this is gonna take in an a Vector two f object like this SF Vector two f which will take in a vector two dimensional float, and this will need a width and a height or an X and Y value. So in this case, we’ll just do a 100 and 100. Okay, if we go to lets close this off, we go to rerun it.

Okay, so recompile it, again, every time you make a change, you have to recompile it, you can see that this has now moved, we can also change the height, let’s kind of make this guy a little bit taller, but we won’t necessarily change the width of it. So what we can do is lets close that up do the enemySprite . And we can scale it. Okay, weirdly enough, you can’t assign a specific width and height, you actually have to scale things.

Okay, so in this case, we’re going to again pass in a vector2f, capital V, Vector two f, okay and then we’re going to pass in the amount by which we want to scale the x and the amount by which we want to scale the y. So the x is going to remain exactly the same. So we’ll just do one, the y however, we want to change the height, maybe we’ll do like a 1.5 and see how that works out.

Okay, so we’ll go back to here. Well, I guess we don’t need to clear it. We’ll just kind of recompile and we’ll rerun it and now you can see that this guy is horribly stretched, but at least the scaling worked. Now there are plenty of other things that we can do with Sprites but this will be pretty much the extent of what we’re gonna do in this course with our Sprites.

One last thing to note before moving on to the next section is that the sprites bounding box is actually this whole rectangle. Weirdly enough, the bounding box doesn’t follow the image like this. This is gonna be the bounding box. So when when it comes to detecting mouse clicks on the sky, even if you click up here, it’s technically within the bounding box. So that’s going to register a click. Okay, we’ll get more into that a little bit later on. Just wanted to make you guys aware now. Okay, we’ll close this up.

Otherwise, that’s it. So in this section, we covered two things, loading in textures, and the second creating sprites and assessing their attributes. Definitely Feel free to play around with this. Maybe try to load in your background. See how well you can do with that. When you’re ready to move on, we’ll do pretty much the same thing but with text. So stay tuned for that. Thanks for watching and see you guys in the next one

Interested in continuing? Check out the full Discover SFML for C++ Game Development course, which is part of our C++ Programming Bundle.

For teachers, you can also try Zenva Schools which offers online learning suitable for K12 school environments and offers a wide array of topics including Python, web development, Unity, and more.

]]>
Learn String Functions in C++ https://gamedevacademy.org/cpp-string-functions-tutorial/ Fri, 10 Dec 2021 01:00:22 +0000 https://coding.degree/?p=1498 Read more]]>

You can access the full course here: The Complete Introduction to C++

Now that we know how to use functions, let’s take a look at some library functions. Strings come with a lot of functionality that can help retrieve properties or modify the string in some way. We will take a look at 6 functions:

  • size()
  • empty()
  • substr(index, length)
  • append(string)
  • insert(index, string)
  • erase(index, length)
std::string name = “Nimish”;
name.size(); // 6
name.empty(); // false
name.substr(0, 3); // “Nim”

Indexing starts at 0 instead of 1. Now for some modification functions. Let’s say we wanted to change the string “Nimesh” into “Nimish Narang” we could do this:

name = “Nimesh”;
name.insert(3, “i”); // name = “Nimiesh”
name.erase(4, 1); // name = “Nimish”
name.append(“ Narang”); // name = “Nimish Narang”

Transcript

What is up everyone? Welcome to our tutorial on string functions. Seeing us we’re quite familiar with functions and strings, I thought we’d end this with a little bit of fun. Getting to know some of the really cool things that we can do with strings. So, what are string functions?

Well, strings have many functions attached to them that either help retrieve properties or modify the string in some way, and this has because they are advanced data types, actually a bit more similar to erase, than something that we’ve seen until this point.

So, these six functions that we’re gonna look at, will be size, empty, substring, append, insert and erase, although that is just six of many possible functions. There is a link down there below that contains a reference to all of the possible string functions available.

So, let’s head over to the code, we’ll check out these six functions and then talk about what more we can do. Okay, so I figured this is really just kind of a for fun section.

If you’re really not that interested in string functions, you can skip this and end up the course, but I figured it’s always good to get to know some of the cool things that we can do with strings, because they’re such a versatile data type.

So, I’m gonna start off with a string that represents my name, and I’m just gonna play around with it a little bit. So, like I said, we’ll explore those six functions. The first of which is the, size.

So, it’s always good to know how long your string is, because strings have no predetermined length, we don’t necessarily know how long they are. So for that, we can simply call upon the string name and then dot and then the size.

So, this is the length or size property of a string, in our case, we might want to print this out. So, I’m just going to wrap this in a print statement, like so, okay. And then we’re just gonna end the line here. Okay, so this should return a six, indeed it does.

There are six characters in the string, it’s off length six, and so that’s where that comes from. The next one is to determine whether or not the string is empty. So, if the string is empty, that means it looks like this.

In our case, we know that’s not true because we have six characters here, but nevertheless, it’s always a good one to know. So, this just returns true or false based on whether or not the string is empty. In this case, we get false because it is not empty.

So, those are the two more commonly used property retrieval functions. I guess you could say that this third function is sort of retrieving a property. Although more specifically, it’s actually retrieving a part of the string, and that is our, name . substring function.

So, it looks like this, it’s a short for substring. So the purpose of this function is just to retrieve a part of a string, hence a substring, okay? If we open up the brackets, we get the arguments and exactly what they are.

The first is going to be the position that we want to start at, and then the second is going to be the length or the size of the sub-string. So, let’s say I want my first three characters, it’s just going to be name.

The start position is zero, because this is position zero, one, two, three, four and five, and my length is going to be three. So, I can, again, print that out. Why don’t we do that? Just going to take this, cut it, get rid of that extra semi-colon and then we’ll paste it in here.

And this will just return me, my first three characters, okay? So, those are the three retrieval functions I wanted to go over. Now, we’re gonna turn to three modification functions. These are going to be our append, insert and erase functions.

The append function is probably the easiest of them, and as far as strings are concerned acts very similar to the plus operator. It essentially takes one string and sticks it onto the end of the other.

So, let’s say for example, I wanted my first name to be my full name, okay? So, what I could do is I could take this name, call the append function, and then I want to stick this string, but I’m gonna give a space as well onto the end of it.

And then if I print out my name, I should get my full name printed out. So, we’re going to replace that with just my name. Now, keep in mind, this function does actually modify the original string value and that’s where it’s actually different from the plus operator.

The plus operator will return a new string, this modifies the original. So, if we run this, we should see the full name printed out here, and that’s exactly what we get. Again, it modifies the string whereas the plus operator produces a brand new string.

Okay, so we’re going to resort back to this being our name or whatever your name is, feel free to sub it in, but we’re gonna make a couple of spelling mistakes, at least I will in my own name.

So, I’m actually gonna set name equal to something else. I’m gonna replace the I with an E, just so I can show you a couple ways we can fix it. Now, there is actually a replace operation, but we’ll be doing two things instead.

We’ll be doing the insert and then the erase, rather than the replace, because I figure it’s better to get to know two functions for the price of one. So, the insert operator, although we could do the delete first, it doesn’t really matter too much.

The insert operator works something like this. We enter a position into which we want to insert the string, and then we apply a string that we want to insert. So, in this case, this is again, position zero, one, two and three.

So, I want to insert something at position three, and what I want to insert is simply going to be an I. Now, this could be a string of whatever length I want, I can insert everything here.

I can insert an empty string, although that serves no purpose to me, but I’m just going to insert an I, okay? So, now if I go to print this out, this should have an IE and indeed it does. So that’s step number one, step number two is gonna be to delete the character at this index.

So, I’m going to call name.erase. Now, erase takes a start index as its first argument, and then it takes a length as the second argument. So, in our case here, we want to erase a position, not zero, one, two, three and four. So, we want to erase whatever is starting at position four, okay?

And then we want to insert just a length of one, or rather we just want to erase a length of one. Again, we can have this be whatever length we want, if it reaches the end of the string before the length specified, then that’s just kind of where the function ends.

So, by this point, my string should have my name spelled properly because we’ve inserted the I, and we’ve erased the unwanted E. Okay, so that’s it. I just wanted to showcase these six functions that you will probably find yourself using fairly often with strings.

Like I said, there are a huge number of functions that help us to retrieve properties or modify the string in other ways, most of which I don’t find myself using very often, that’s why I brought these particular six up.

So, feel free to check out the string reference if you’d like, again, linked to that on the slides, if you do want to know more, otherwise I encourage you to try these six operations, these six functions with your own name.

Again, maybe try something like this and see if you can come up with the correct solution. So, that’s it for now, thanks for watching and see you will in the next one.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
Free Course – Explore Game Maps with C++ https://gamedevacademy.org/cpp-game-map-tutorial/ Fri, 30 Oct 2020 01:00:19 +0000 https://coding.degree/?p=445 Read more]]>

Learn C++ game coding by creating a tile-based map – a perfect step for developing roguelike games and more! You can also extend the material covered here by checking out the full course below!

Build a Roguelike Game with C++ and SFML

About

With instructor Nimish Narang, you’ll learn how to take your C++ games to the next level using SFML, a library that allows you to integrate multimedia elements into your games. Using this fantastic library – no third-party tools required – you’ll build a tile-based game map using code alone to construct and access images. Not only will these techniques allow you to expand your knowledge of C++, but you’ll also have a nifty project to evolve for numerous sorts of applications.

]]>
How to Handle User Interactions with SFML https://gamedevacademy.org/cpp-sfml-interactions-tutorial/ Fri, 07 Aug 2020 01:00:58 +0000 https://gamedevacademy.org/?p=12496 Read more]]>

You can access the full course here: Discover SFML for C++ Game Development

Handling User Interactions

There are many ways in which a user can interact with your program from pressing buttons, to opening and closing windows, and even simple events like moving a mouse. Each of these interactions triggers an event which we capture within the run loop and can either choose to handle or ignore. We could spend hours covering just events but we are only really interested in three for now: closing the window, clicking a mouse button, and pressing a keyboard key, specifically, the space bar.

To handle any event, we first need to create an sf::Event object and call the function window.pollEvent(). This gathers all of the events associated with a specific window (as you can have multiple windows open at once) and will continue to return true while there are events ongoing. For example, we are already handling the window close event with this code:

sf::Event event;
while (window.pollEvent(event)) {
  if (event.type == sf::Event::Closed) {
    window.close();
  }
}

This is only searching an event of type sf::Event::Closed, triggered when the user exits out of the current window. However, we also want to monitor mouse clicks and spacebar presses. Let’s start with mouse clicks. We can provide an else if case like this:

else if (event.type == sf::Event::MouseButtonPressed) {
  std::cout << "Mouse button pressed" << std::endl;
}

While this isn’t doing anything more than printing out “Mouse button pressed” whenever the user clicks the mouse somewhere in the window, we can see how easy it is to handle simple user events. To handle spacebar presses, we first need to detect for a KeyPressed event and then find out whether or not the key pressed was the spacebar like this:

else if (event.type == sf::Event::KeyPressed) {
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
    std::cout << "Space bar pressed" << std::endl;
  }
}

The isKeyPressed() function will return true if the key we are looking for is the one that was pressed and false otherwise. If you try pressing anything other than the spacebar, nothing will happen but the spacebar will print the message “Space bar pressed”. We can put it all together like this;

sf::Event event;
while (window.pollEvent(event)) {
  if (event.type == sf::Event::Closed) {
    window.close();
  } else if (event.type == sf::Event::MouseButtonPressed) {
    std::cout << "Mouse button pressed" << std::endl;
  } else if (event.type == sf::Event::KeyPressed) {
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
      std::cout << "Space bar pressed" << std::endl;
    }
  }
}

Note how all of this occurs within the run loop but before drawing anything. Typically, the first thing we do in a run loop is process and handle interactions as they may affect the state and thus the items that are drawn to the window.

Transcript

Hey everyone, welcome to a tutorial on handling user interactions. Here, we’re just going to explore a couple of the user interactions that we’ll be using in our game, how to detect them, and how to respond to them. So tasks are gonna be to first learn about how to monitor events, then we will respond to quit events, we’ve actually already took a quick look at that, then will respond to mouse clicks, and finally, to button presses. So let’s head to the code and get started.

All right, so like I said, we’ve actually already kind of covered one of the events and that is going to be the window.close. But we haven’t really covered events much in general. So we’re not gonna be creating anything outside of here for now. So in your while loop here, your main game loop, there will be a series of events that take place there could be multiple events happening at once.

For example, if the user is holding down a key and pressing their mouse, there could be lots of things happening okay? So what we do is that’s why we have a while loop because there could be multiple events, if we only do an if statement, that’s just gonna check one of them, which is not what we want. So by using the window.pollEvent, this is going to check to see if there are any events happening that are related to this particular window.

Technically, you can have multiple windows with SFML. Again, that’s a bit beyond the scope of this course. But for each new window, you want to pull events within that one.

Again, we just have the one window to work with. So that should be fine here. So you create an SF event object, and you pass it into the poll events that way we have access to it within the while loop. So here, we want to be checking to see what events are occurring, we only really need to check the ones that we’re interested in.

For example, if we’re just handling mouse clicks, we don’t need to do anything else. But at the very least, you should have this one that’s polling for the event closed, okay? Otherwise, you can run into issues with your game just continually running.

Okay, so events will have many possible types associated with it. In this case, this is the event.type SF event closed, and we’re just closing the window. Okay, we’ll also want to respond to mouse clicks. So when you click on the animate, we want to decrease some energy, and also will respond to key presses. So at the very end, when you want to restart the game, you press the space bar, and it will restart everything.

So let’s first work on the mouse clicks. What we’ll do is we’ll do an elifevent.type. I’ll actually you know what that should be an else if, and we need these. Okay, getting kind of confused with some Python code. Okay, so we’ll do this okay, and then we’ll say else if events.type is going to be equal to and here’s where we want to listen for a mouse button press. So we’ll pull the event SF event mouse button pressed.

Okay, we’re not gonna worry about the release or anything like that. We just want to check to see if the mouse button is pressed. Okay, so if the mouse button is pressed, we can pretty much do whatever we want. We’re not gonna check for collision detection or anything yet. We’ll cover that much later on in this course we will be covering it eventually though.

And for now what we can just do is print something else will stay Standard C out. We’ll say mouse button pressed, okay. And then we will do a new line, I guess. Okay, well, we can do we could actually just do the end L. So it should actually be standard endl okay.

So, if we’re checking to see if the mouse buttons pressed and we’re printing out, that’s good. We also you know, actually let’s go ahead and run this and demonstrate this. So we go to terminal clear will recompile it./main. Okay, you can see that I’m clicking on the screen, and we’re detecting the mouse button pressed is being printed out there every time.

Note how, if I’m clicking outside of the screen, nothing is registering. Now I’m kind of clicking all over the terminal right now. Nothing’s happening okay? That’s because we’re only detecting mouse clicks within this particular window. That is the desired behavior, at least for our game.

Okay, cool stuff, so we know how to detect mouse clicks. Again, we’ll get into the exact collision detection later to check to see if we’re clicking on an object, but we’ll also want to monitor keyboard presses. So we’ll do else if the event.type is gonna be equal to SF event key pressed.

Okay so we actually don’t launch immediately right into checking to see if the space bar key was pressed. What we should be checking see is if the events was a key press in general, okay, then we can go into that further and see if the key that was pressed was a space bar. And we may as well implement that logic here. We’re gonna need it later on anyway.

So we’ll say something like if SF keyboard is key pressed, and we’ll do SF, keyboard space. Okay, so just make sure that you can see the whole thing. So this might seem a little roundabout, we have to see if the keyboard is key pressed is called. And with this will take in a key to check to see if it’s pressed. Specifically, we’re just checking to see if the space bar is pressed. Okay, that key space equal to true, we’ll just print out something like space bar pressed. Space bar pressed, okay, and then we’ll end the line.

All right, so you can also check for other keys. For example, if you’re doing like a movement game where you press the arrow keys to move around, you’ll probably want to check for up arrow down, arrow left and right and so on and so forth. In case we’re only interested in if the space key is pressed, okay, so if this returns true, that means the space key is pressed, we can print out the statement.

Okay, so we’ll go again back to terminal. Let’s recompile, let’s rerun. Okay, and I’m pressing some other keys, nothing’s happening. Soon as I press space bar, then you can see that space bar is pressed. It’s also still detecting mouse clicks, and of course, it’s detecting close events as well.

All right, so that’s actually pretty much as complex as the user interaction handling is gonna go in our game. Like I said, you can make this really complex if you want, but we’re only really gonna be listening for these two commands, three if you include the window close. All right, so feel free to check out some of the other keys. See if you can implement like a little kind of movement thing if you want if you’re feeling adventurous. Otherwise, we’re gonna end the section here. When we come back, we’re going to be talking about how to monitor time is that’s going to be an important feature of our game. So stay tuned for that, thanks for watching. See you guys in the next one.

Interested in continuing? Check out the full Discover SFML for C++ Game Development course, which is part of our C++ Programming Bundle.

]]>
Learn to use Loops in C++ https://gamedevacademy.org/cpp-loops-tutorial/ Fri, 17 Jul 2020 01:00:49 +0000 https://gamedevacademy.org/?p=12378 Read more]]>

You can access the full course here: C++ Foundations

While Loops

Now that we can perform tests and execute code once, the next step is to be able to perform tests and execute code multiple times as long as some condition continues to be true. For this, we use loops. Loops provide a way to execute code multiple times without having to type the same code again and again.

The simplest form is the while loop and it acts very much like an if statement run multiple times. It performs a test and executes code if the test returns true but instead of executing the code once, it continuously executes the code until the test eventually returns false. This can be dangerous because if the test never returns false, the loop will run infinitely and the program will crash so we need to make sure that we build the loop in such a way that it will eventually exit.

Games at their heart, often contain a big game loop that continuously performs checks, handles player interaction, renders graphics, etc. as long as the game is still running and breaks when the user does something to end the game. We can build a very very simplified version of this by moving a player as long as they are not quite at the end position and then exiting the loop when they are. We first need current and end position variables:

int pos = 0;
int endPos = 5;

Then we need a way to check if we are at the endPos and if not, move our player forwards. An if statement will only do it once so we need a loop which loops like this:

while (pos < end_pos) {
  pos += 1;
  std::cout << pos << “\n”;
}

The difference is that the while loop loops to the top and executes the test and code continuously until eventually, in our case, the pos >= endPos. In this case, it will run 5 times. We know that this will eventually stop because our pos < endPos at the start and we’re increasing it by 1 each time.

For Loops

The next type of loop is the for loop. This acts similar to a while loop but it runs a set number of times. We build right into the loop when to start and when to stop so we know how many times it will run. This makes it great for pairing with collection types as we can just set the start point to be the beginning of the collection and the end point to be the end and visit each element in the collection. We can set up a for loop like this:

for(int i = 0; i < endPoint; i += 1) {

}

Not all for-loops have to be set up with these exact numbers; we can change the start value of i, the end condition, or the step value ( += 1 ). This one just starts with a value of 0, increases i by 1 each time, and runs until i < endPoint returns false. For example, if we wanted to print out every member in an array, we could do something like this:

int intArray[] = {5, 4, 3, 2, 1};
For (int i = 0; i < 5; i += 1) {
  std::cout << intArray[i] << “\n”;
}

This uses i as an indexing variable with the initial value run to be 0 and the final value run to be 2 and uses that to visit each element of the array. i starts at 0, then 1, then 2, then we exit the loop when i = 3. We don’t have to use i; sometimes we just want to perform a task a set number of times and that’s where for loops excel. Go ahead and run the loop within the main function to print out each element.

The final thing about loops is that every for loop can be turned into a while loop but not every while loop can be turned into a for loop because sometimes we don’t know how many times a while loop will run but we always know how many times a for loop will run.

 

Transcript

While Loops

Hello guys welcome to our tutorial on While Loops. Here we’re going to first introduce the concept of loops, and then we’ll explore the first and simplest kind. So we’re going to start by covering what are While Loops, then we’ll just write and run a very simple example. So let’s head to the code and begin.

Right, so before we write any actual code let’s talk about what While Loops are, and what they bring to the table. Well, a loop in code is just a way to execute the same statement or set of statements multiple times by racing it just once, putting it within a loop and running the loop. Okay, so this is hugely beneficial for us because we don’t want to have to rewrite the same code over and over again, if it’s doing exactly the same thing. It’s much easier to write it once, run it many times, than to write it many times and then run it once.

Okay, so a while Loop is the simplest form of it. And it actually acts very very similar to an IF statement. It will execute some code if some test returns True. The difference is that it will continue to execute the code, as long as that case is True. So if the case never returns False, then it will always execute the code over and over again infinitely until the program crashes. So that’s bad. But if we design our While Loops carefully, we can prevent this issue and control exactly how many times we want it to run.

Now what we can do is we can simulate a very very basic kind of platform runner. Typically the way these games work, is there’s an endpoint your current position, and then you have to get to the endpoint, by jumping over obstacles, defeating enemies et cetera, and the game is over or at least the level is over as soon as you reach the endpoint. So to simulate that, we might use a While Loop. We could have an Integer that represents a current position or just Pos for short. Maybe we start at zero, have an Integer that represents the end position, maybe we’ll just set this equal to five. Okay?

And what we’re trying to do is basically keep moving forwards until we reach the end. So we might use a While Loop for this will basically say something like, as long as our position is less than our end position, we’ll continuously execute some code and quit missing one of those. Okay? So in this case we might want to increase our position by one. So we’ll do in Pos plus equals one, and then maybe we want to print out our current position. So we can do Standard C out our Pos and we’ll do a new line as well. Okay, so we’ll do that and then just the new line character.

Okay, so let’s go ahead and run this. How many times do you think this will run? It should run five times. Okay? The reason it runs five times is because our end position is five. We start at zero. When we get to the first iteration, we perform the check, zero is less than five. So we execute the code, just increase it’s position by one, prints out and then loops back up to the top. We perform the test again. Yep, one is still less than five So we execute the code.

Now two still less than five. So we execute the code on and on, until eventually position is equal to five. We go back up to the top, we perform this test and it returns False. Because five is no longer less than five, at which point we exit out of the loop. So we skip over this code and that’s it. Okay,then we could execute any code down here okay, so that’s your basic While Loop.

Again there is the issue that if you don’t design this carefully, you can end up having it run forever. So you always want to make sure there is a way to exit out of your While Loops, or that eventually they will end okay? Otherwise that’s pretty much of it for the basic While Loop. Again really just think of it as an IF statement that continuously runs rather than just runs once. In the next section, we gonna be covering the For Loop So definitely play around with While Loops a bit.

Make sure you’re super comfortable with them. And we’ll learn about the next loop type in the next section. Okay? so stay tuned for that Thanks for watching and see you guys there.

For Loops

Hello, everyone. Welcome to our tutorial on For Loops. This is the next type of loop, the for loop, it’s a bit more restrictive, but that also makes it potentially easier to use than the while loop. So we’re going to start by covering what are for loops, then write and run for loops, and of course compare and contrast them to while loops. Let’s enter the code and get started.

Okay, so previously, we talked about while loops, hopefully you’re comfortable with those, because a for loop is actually gonna run fairly similarly to this. Again, it’s just another mechanism by which we can execute the same code multiple times. The difference here is that for loops are always going to run a set number of times. We choose exactly how many times we want the loop to run by; specifying a start point and end point and then some sort of a step or an iterator variable, okay? So we need these three items when designing a for loop. That makes it a bit more tedious to set up but ensures that it will run a set number of times.

So it looks a bit like this. We have for, we have the start condition, the end condition, and then the step variable. Okay, so to set up a basic loop, let’s say that runs five times, what we would do is we would create an int i equals zero, so we’re starting with i equal to zero, we’re ending when i is no longer less than five, and we’re increasing i by one each time, okay?

So this is a very basic for loop that will run five times, okay? Again, because we’re starting at zero, we’re executing the code and then we increase i by one at the end, we go back up to the top, i is equal to one now. We check to see if we’re at the end condition, if not, we execute the code, increase it by one, and so on and so forth until eventually i is no longer less than five.

Now, this makes it very good to pair with arrays because we can use i as the indexing variable within an array and then we can just set it to run for as many elements are in an array. So let’s actually demonstrate that.

We’ll just have maybe an array of integers, maybe we’ll just do the numbers five, four, three, two, one, so nothing terribly exciting. We’re just going to create an array of ints, maybe just be like intArray. Okay, and we’re just gonna set this equal to five, four, three, two and one. Okay, so really, again, nothing terribly exciting. What we’ll be doing is printing these guys out. So we’ll just do a standard cout and we’re just going to do the intArray at the index of i and then of course, a new line character.

Okay, so essentially, with each loop iteration, we’re guessing the intArray value at the index of i, so it starts at zero, then one then two then three then four and then exits. So it will start at five then four, three, two, one, and then will exit, okay? So if we save this and we run it, then we’ll basically be printing out the numbers five, four, three, two and one. And there we go, okay?

So we can use i as the indexing variable, although we don’t have to, we can just set this loop to run five times, you don’t necessarily have to use i as an indexer. But that’s very often where you’ll be using for loops, okay?

So to compare and contrast them to while loops, essentially, we’ll use for loops where we know exactly how many times we want the loop to run. We use a while loop when we’re not 100% sure how many times it will run, such as with a game. With a game loop, the game could be over in a minute, it could be over in five hours, okay? So the loop needs to run continuously throughout that. When we’re iterating through in array, there’s a finite number of elements thus we know exactly how many times we’re going to be running the loop, and that’s why we’d use a for loop, okay?

So practice around with for loops. I know it looks a bit more complex, but really, it’s no different from a while loop. It’s just a bit more strict. Now the one restriction here is that every single while loop or every single for loop can become a while loop, but not every single while loop can become a for loop, okay? So try and think about that. When we come back, we’re gonna be talking about functions. So stay tuned for that, thanks for watching and see you guys in the next one.

 

Interested in continuing? Check out the full C++ Foundations course, which is part of our One-Hour Coder Academy.

]]>
A Guide to C++ Vectors https://gamedevacademy.org/cpp-vector-tutorial/ Fri, 10 Jul 2020 01:00:22 +0000 https://gamedevacademy.org/?p=12377 Read more]]>

You can access the full course here: C++ Foundations

Vectors

Arrays aren’t great when we need a list of data that will change in size, i.e. we will add elements to it or remove elements from it. For that, we can use a vector. It is a more functional version of an array that still stores data in a list-like format but can grow or shrink. We have to first import the vector library by adding this line of code at the top:

#include <vector>

Then we can replace our roster with this:

std::vector<std::string> roster;

Not how we don’t initialize it with items initially and we set the type of values in the vector to string in the <>. We can add them with the .push_back() function like this:

roster.push_back(“Nimish”);
roster.push_back(“Sally”);
roster.push_back(“Laura”);

We can insert a value by specifying the index and the new value using the insert() function like this:

roster.insert(roster.begin() + 1, “Mike”);

This weirdly enough, needs an indexing type variable rather than just a regular int index so note the roster.begin() (start index) + 1 to insert it after the first element. We can remove an element from the back by using the pop() function like this:

roster.pop_back();

There are other functions to explore so check them out! You can access them by typing

roster.

And then a list of possible functions should pop up.

 

Transcript

What’s up guys? Welcome to our tutorial on vectors. Here we’ll take a look at a collection type that is similar to an array but a little bit more powerful. So we are going to first learn how to create vectors, then how to add elements to vectors, how to remove elements from vectors. Let’s head to the code and get started.

So let’s begin with talking about what vectors are. Well vectors really are just more powerful versions of arrays. So these are arrays that are mutable, meaning we can add elements to them and remove elements from them, but they also have a host of other functions that allow us to either manipulate them in some way or to retrieve properties of them. So really where we have static data that we know isn’t going to change very much, that’s probably where we should use an array. As soon as we know that data is going to change, it’s going to grow or shrink in size, then we probably need to turn to something like a vector.

Alright to gain access to the vector we actually have to add another include statement. So we need to include the vector library like so. Now these are part of the standard library so we’re going to need to do a standard vector like so, and then in the angular brackets beside it, we put the type of variable that we want to store in here. So let’s do basically the same thing as before with the roster, might as well keep the same examples. So we’ll do standard string here. It’s going to be a vector of strings. And then we just need to give this a name so in this case maybe roster or something.

Now we’re not going to set this up by providing initial values or anything. What we’ll do instead is create it and then we’ll just push items onto it. So when we push something onto a vector it just sticks it right onto the end. So in this case we’ll do roster and we’ll call the push back function, and then we just need to parse in an appropriate value. So in this case I’ll just maybe do my own name first. Okay and then maybe we’ll add a couple more people So let’s do Sally, and we’ll do Laura or something. Okay, just some people that we might want to add to our roster. So now it’s three members long, it starts off with my name and then the next and then the next.

Okay, so each one you add just goes to the back of the stack. Similarly we can remove elements from a vector by doing the roster in this case, or the vector name dot pop back. So the pop back function is just going to remove the last element in a vector. We can keep doing this until we have popped all the elements or until we get to the one we want.

Alternatively if I want to insert an item at a specific index, lets say I want to put someone right after myself but before Sally, what they can do is they can do roster dot insert. And with the insert function this takes first the position then the value. Now annoyingly enough I actually can’t just do the position of one, what I would have to do is something like roster dot begin plus one. And then my value, lets do Mike or something. Okay, so this is now going to insert the value of Mike in between me and Sally because it gets the beginning, or zero, plus one which would be this index and it just inserts it right here, so basically pushes this back and puts that new value Mike right there.

Now these are just a few of the many possible operations we could perform on vectors. You can open them up, see a complete list by doing the name dot and now you can see that there are a lot of different functions that we can call on these vectors. So feel free to check some of them out, otherwise we covered the basic operations of add remove and insert. Definitely give it a bit more of a play around. When we come back we will be talking about if statements and that will be our first introduction into conditional logic in our code. So stay tuned for that, thanks for watching, see you guys in the next one.

 

Interested in continuing? Check out the full C++ Foundations course, which is part of our One-Hour Coder Academy.

]]>
A Comprehensive Guide to Variables in C++ https://gamedevacademy.org/cpp-variables-tutorial/ Fri, 21 Feb 2020 01:00:40 +0000 https://gamedevacademy.org/?p=11245 Read more]]>

You can access the full course here: C++ Programming for Beginners

Basic Variables

As fun as input output is, it’s time to start learning about the language basics so we can make our programs actually do something significant. There’s no better place to start than with variables. Variables are a fundamental component of every program ever written. They provide a way to store and modify values as the program runs. Variables have a name, a type, and a value where the type dictates the kind of data that can be held (text, number, etc.). C++ is statically typed meaning once a variable is assigned a type, it cannot change (unlike dynamic languages like Python). The basic types are:

  • bool
  • int
  • float
  • double
  • char
  • nullptr
  • void
  • string

Technically strings are not basic variables; they are considered to be an array of characters or chars. In fact, the C language doesn’t even have strings. C++ is high level enough that they at least allow us to use strings. Before we dive into each variable type let’s talk about declaring vs initializing.

Declaring a variable is just assigning a name and a type. This can even be done outside of a function. Essentially, the compiler allocates some space for it (depending on the type of variable) but doesn’t store a value. Initializing a variable is assigning a value to it. We need to make sure the value we assign matches the type. We can break the process of creating variables into these 2 different parts or do it all at once. Our .h files can be used to declare variables and the .cpp files are used to initialize them (among other things).

Just a heads up; until otherwise stated, any code that you want to write to practice or follow along should go between the { } in the main function, otherwise you won’t be able to run it.

Booleans

Let’s start with Booleans or bool. These are true or false values; if the value is not true, it’s false and vice versa. Use these when you need a variable that can only take on one of two values such as:

bool isGameOver = false;

A game is either over or not; there are only two possible states (pausing a game still falls under the category of not over). We could split this up into:

bool isGameOver;
isGameOver = false;

If we wanted but it doesn’t matter here. We can also assign the result of some comparison operation like this:

bool isFalse = 5 > 10

5 is not greater than 10 so this stores false.

Numbers

There are 3 basic numerical types in C++ int, float, and double. There are actually variants on these such as unsigned int for when we just want positive numbers or ints with a specific number of bits. That’s beyond the scope of the course so let’s ignore those for now. Use integers or int when you want whole numbers:

int xPos = 5;
int yPos = -2;

Use floats or doubles when you want decimal numbers:

float percentHealth = 0.45;
double pi = 3.14159;

Doubles offer more decimal places than floats but nothing we will be doing here will require that precision so we’ll stick with just floats.

Numbers can also store the results of an arithmetic expression such as:

float percentHealth = 80 / 100;

Characters

Characters, or char, are single digit text variables between the single quote: ‘’. For example:

char c = ‘c’;

With strings available, the character type is not used too often. They potentially (but not necessarily) take up less space in memory but are more difficult to work with as you have to convert back and forth to combine them.

Nullptr

Nullptr is a value assigned to a pointer when we don’t have anything for it to point at. That likely won’t mean a lot just yet so we’ll skip this one for now and come back to it when we talk about pointers.

Void

Void is used in two cases: when we don’t want to output a specific value from a function or when we don’t want to take any parameters as input. When used with pointers, this means that it could be a pointer of any time. Again, that won’t mean a lot right now so let’s ignore this one too.

Strings

We’ve already seen some of these in our code examples! Strings represent text data such as messages or names and are initialized between double quotes: “”. Unlike characters, they can be of any length including 0. These are part of the std library so you have to use the special std:: syntax or include using namespace std. Some examples might be:

std::string name = “Nimish”
std::string emptyString = “”;

 

Transcript

What is up everyone and welcome to the fifth tutorial in our “Learn C++” course. This will be on variables, and is part one of two just because there is quite a lot to take in with regards to variables, and I don’t want to overwhelm you with everything all at once. So in part one, we’re going to focus on what are variables. Then we’ll talk about some of the basic variable types in C++, these will be in the slides, and then we’ll turn to the code and focus on assigning and reassigning variables with some examples.

So for starters, what are variables? Variables is simply a way to store and modify data within a program. Pretty much every program will need some kind of variables to help maintain its state throughout its execution. Variables can be used temporarily or can exist throughout the entire program’s execution.

Take for example a game, often they’ll ask what your name is right at the beginning, and then they’ll store it somewhere. Well, that name will exist throughout the entire time that you’re playing the game, and also in future runs as well. However, if we’re entering, let’s say a specific level, there may be a lot of variables that help set up the level that are basically destroyed, as soon as we leave the level or go into a different one.

Now, each variable uses a “type” to dictate the kind of data that can be stored. So there might be, let’s say, numerical types of variables, well there may might be text based variables or true false variables, these are all determined with the type which we have to assign. Creating a variable can be broken down into two stages; declaration and initialization. Declaration is essentially assigning a type and a name to a variable. And then initialization is storing a value in that variable.

So some of the types in C++. For starters, C++ is statically typed. So statically typed means once we assign a type to a variable, that type can never change. If we create let’s say, a numerical variable, we cannot then later store a true or false value in it. Now this is unlike languages like Python, which are considered dynamically typed, those definitely allow you to modify types of variables, but C++ is a bit more rigid that way.

So some of the basic types we might encounter will be Booleans, which are true or false values, integers, which are positive or negative whole numbers, floats and doubles, which are decimal numbers, characters, which are single byte characters, and then there are null pointers and void types.

Now, null pointers and voids are a little bit more advanced, so I doubt we’ll actually cover those too much in this course, but I just wanted to include them here just in case some of you say, “Well, there are actually other types and you didn’t include them.”

Okay, so I think we’ll focus on bools, ints, floats. We might take a look at some doubles, but we’ll kind of skip over those for the most part because they’re actually quite similar to floats, and the characters and strings, we’ll actually cover in the next tutorial.

So let’s head on over to the code and go over at some examples. Okay, so as you can see, I’ve kind of cleared out my main file and put everything in old code. And I’ll continue to do that as we go. All right, so the first stage is going to be talking about how to declare and initialize variables.

So the two stages are gonna be assigning a type and a name, okay. So that will be the declaration and then initialization will be name equals some value, okay. We can do this in two steps, or we can do it in one like this.

So let’s focus on Boolean variables, because they’re the simplest. The type is gonna be a bool, okay? The name is gonna be whatever we want. Let’s think about something game related, so maybe it’s something like “isGameOver”, okay? And then we can leave it at that. We can then assign it in a value. So isGameOver is equal to false because maybe the game is still running, okay? So Boolean is perfect for this kind of a variable, because the game is either over or it’s not over. So even if it’s paused, that doesn’t mean the game is over it’s technically still running. So it’s either true or false. There’s only one of two possible states.

Okay, so we can put this all in one go if we want suppose saying bool isGameOver is equal to false doesn’t really matter too much. So we’re actually gonna break it up. Okay, if later on, we decide that okay the game is over, we died, or maybe we just won, then we’re just going to say; isGameOver is equal to true. So this is assigning the value for the first time and then this is reassigning it later on.

We can also perform other operations, we can have a another variable such as bool isNotGameOver. I know this doesn’t really make too much sense, but just bear with me here. And we can assign it the value of isGameOver. So basically, this will say whatever value we find here true, we’re just going to copy that into here, okay.

So at this point in time they’re equal but then I could reassign it later. So I could say isGameOver is equal to, you know, false again, and then this one doesn’t change, okay? So just something to note there. We can also take Boolean values and assign them the value of some comparison operation. So for example isGameOver is going to be equal to five greater than two. Now I know this really doesn’t make much sense, given our context, but this is a perfectly valid operation, because five is greater than two, it stores the value of true, okay? So again, something to note there. Just interesting semantics.

Okay, so that’s Booleans for you, they’re very simple. Again, it’s either true or false, there’s not too much more to know there.

So next up is gonna be integers. So integers are whole numbers. Can be positive or negative. And as you can see, there are a ton of variants. So we’re not gonna worry about any of these, like int 16 and 32. There’re also like unsigned integers, if you go all the way down. We’re not gonna worry about those. We just don’t really need that level of specificity. So we can kind of ignore that.

So an int let’s say, let’s say currentHealth, okay? Maybe is equal to 100, okay. So again, we can we can split this into two parts, we could do this and say currentHealth is equal to 100. Or we can do it all in one go. Let’s do it all in one go just for the sake of variety here. We can also take our integers and we can assign them the value of some operation two but it shouldn’t be a comparison operation cause this returns true or false, and doesn’t return a number.

But we could do something like currentHealth is equal to 50 minus two, for example, and that’s also perfectly valid. We’ll talk more about operators like this later on. For now, just know that it’s totally possible to do so. Just like with Booleans, we can assign them a literal value like this, or we can assign them the value of some other variable, that’s entirely up to us what we wanna do with them.

Okay, so finally, we’ll move to floats and doubles. Floats and doubles are both decimal numbers, but doubles offer double the precision of floats. That’s how they get the name interestingly enough. So if a float is a decimal number, then a double will potentially double the amount of decimal places it can hold. Like I said, I don’t really use doubles very much, because I just don’t need that level of precision. And they would take up a bit more memory.

So as much as possible, we’ll stick to floats. If we really, really need to be precise, then we can use doubles instead. But we’ll do floats, let’s say, maybe we’ll do like percentHealth or something like that is going to be equal to 0.45. And that would be a perfectly valid thing. Just like with, I’ll show you an example of doubles, because why not?

Let’s say pi, for example, so 3.14159 probably shouldn’t add extra decimal places if I don’t need them. So that would be an example of a double or a float. Now I could totally use a float to represent this, that’s fine. You’ll note that if actually if I scroll over it, you can see that it’s storing all of these values here, but this is not going to store quite as many values in there.

All right, one final thing I should say is that we can’t assign decimal numbers to integers. But we can assign whole numbers to doubles or floats, okay. So I could totally do five, and that’s fine, okay. Just like I could do 5.9, it would be interpreted as 5.0. But if I did five, that would also be fine, okay?

We should also be aware that if we are doing operations, such as a whole number minus a decimal number, then we can’t store that inside of an integer, we would have to use a float or do some kind of conversions to make sure that we’re dealing with variables of the same type. We’ll talk more about that when we get to operators and operations, but you know, just keep that in mind as we go.

Okay, so that’s it for now. We covered Booleans ints, and floats and doubles. When we come back, we’ll talk quickly about characters and then move to strings. So thanks for watching. See you guys in the next one.

What’s up guys, welcome to the sixth tutorial in our Learn C++ course, here we’ll cover part two of variables, there’s only two types we really need to go over, and those are going to be characters and strings in C++.

So, we’ll just quickly talk about characters, these are simple text-based variables, they’re used for single digit texts only, and as basically anything of length one between the single quote marks, Okay? So it cannot be length zero, it cannot be length two, three, four et cetera, has to be of length one. There’s a great way to represent special characters such as newline or return characters, otherwise, I personally don’t really use them that much.

Next up is gonna be strings, these are text-based variables, we’ve actually seen some examples of these already. These are used for texts, names and messages throughout our code, and it’s basically anything between these double quotes. Unlike the characters, they can be of length zero, one, two, three, four, etcetera basically, up until an infinite length well – not quite because that would actually crash a program, but they could be very, very big, Okay?

So let’s head on over to the code and take a look at some examples. Right, so once again, cleared everything out. So the first thing is going to be our characters. Now these are aside from Booleans, the simplest, I guess, simplest type. But just because they take up the second least amount of memory, it’s just by default take up eight bits, characters are four Booleans are actually just the one. But again, that’s kind of beyond the scope of the course. Okay?

So first of all, we can create a character with C-H-A-R, and all the char, okay? And we can call this whatever we want, so maybe let’s call this character G, okay, single quotes, and we’ll just put the G there, and just like that, all right. So similarly, the characters can have, Oh gee I guess I can’t call this character period. I can do that by couldn’t call it this, okay. If I did a character period like that, that’s also fine. And I could also have numbers as well. So I can do a character one is equal to one like this, okay? So there’s no restriction as to what I can put in there, it just has to be of length one only.

Like I said, I really don’t find myself using characters very often because we have strings, which are so much more powerful. So why use a character instead of a string? Well, the only reason I could really think of is if we are using special characters that just don’t really have a good string representation, which doesn’t really happen very often. And if we just don’t need something that has the functionality of a string.

Strings are actually considered arrays of characters. And in languages like C which are very, very low level, even more low level than C++, there is no string type. We have to use arrays of characters, so it gets to be a bit hairy. If you’re coming from C, then probably will be very familiar with characters. If you’re just hanging out with C++ and you have strings, you really don’t need to worry about characters so much.

Okay, so next up is going to be strings. So if we didn’t have the namespace standard, we would have to declare them as standard string, okay? Otherwise we can actually just say string. We’ll give this the name. So let’s do like a player name. And let’s just put our name, so it needs to be between the double quotes here, otherwise, doesn’t really matter what it is. We can do string empty, and we can have it like this. That’s a perfectly valid string as well, we can have a really long string, I’m not going to type out a really long string, but we could totally do that.

Also, I should note, because the strings are kind of considered arrays, there are a host of functions that come with strings. So we can do let’s say, empty dots. And then you’ll see a list of all of these strings. So you can append a string onto the end of it. You can get the beginning, you can clear it out to kind of get rid of all of the characters and just make an empty string. You can copy it, you can empty it, you can erase it. You can get the length or the max size, so on and so forth. You can pop out the last character, so you get rid of that last character in the string. And there are a ton of functions.

Just to kind of demonstrate one, I’m actually gonna to do the player names. It’s a bit more interesting. The player name, and we’re gonna to get the length of that. Okay, we can get it like this. And let’s say I want to output it, what I could do is, I could just say actually C out, okay, and then just play it name dot length. Like that. Okay, good stuff. Oh, and actually I have this facing the wrong way. Okay, cool. So if I give the Save and I give it Run, you can see I get six. And that makes sense because Nimish has six characters.

Okay, so feel free to play around with those functions a little bit. Again, the best way to learn how to code is to try stuff yourself and practice. So try out some of these other functions, okay? And just note that some of them will take in arguments, so for example, if I want to append some other string onto the end of it, okay, and then I wanted to print that out, I would have to do something like this, and then say C out, player name, if I can actually spell it properly. Okay? And you should see like a bunch of characters on the end of it.

So some of these arguments, some of these functions rather take in arguments like this, and some of them don’t need arguments. So for example, if you’re just guessing the side or the length, then it doesn’t matter. Okay, so once you’re done playing around with those, we’ll come back and we’ll focus on pointers. Now pointers get a little bit more complex. So make sure you’re super comfortable with all of these types that we’ve discussed before moving on to the next section.

Alright, thanks for watching. See you guys in the next one.

Interested in continuing? Check out the full C++ Programming for Beginners course, which is part of our C++ Programming Bundle.

]]>
How to Get Started Programming in C++ https://gamedevacademy.org/how-to-program-c-plus-plus/ Fri, 14 Feb 2020 01:00:24 +0000 https://gamedevacademy.org/?p=11232 Read more]]>

You can access the full course here: C++ Programming for Beginners

Installation

To write and run C++ code, we will use the IDE Visual Studio Code (VSC). It’s a fantastic IDE with thousands of plugins to help you write code in dozens of different languages. It also looks great and is easy to use. The best part? It’s free! Also, the process of installing VSC and the necessary plugins are pretty much identical between Mac and PC so both types of users can follow the same instructions. We’ll hop on over to this website here:

https://code.visualstudio.com/download

Visual Studio Code website

It’s the official download page for visual studio code. Select your operating system and download the appropriate file. Follow the instructions in the installer. Once that’s done, go ahead and open VSC to find a welcome screen that looks something like this:

Visual Studio Code welcome screen

This screenshot is from version 1.41 so if you have a later version, things may look slightly different. VSC doesn’t come packaged with the necessary plugins automatically so we will need to install one to allow us to write C++ code and another to help us compile and run it.

C++ Plugins

The first plugin can be found by opening up the Extensions window (click on the Extensions button at the bottom of the leftmost panel) and searching for “C++” (in the search bar at the top). The one we want is an official Microsoft plugin and looks like this:

C++ Extensions for Visual Studio Code

As you can see, this package has already been installed but where is says “uninstall” above, it should say “install” for you. Go ahead and press that to install it. Don’t worry, it’s free too! You may have to restart VSC to apply the plugin.

Next, we want a way to run the code in VSC, as the plugin we just installed only lets us write C++ code. To avoid the long, roundabout way of installing the platform specific compiler and linking it to VSC, we can use the plugin “Code Runner”. Once again, it’s free to install. In the same extensions window, search for “Code Runner” in the search bar. It should look like this:

Code Runner Extension in Visual Studio Code

Just like before, press the install button and that’s it! You can now write and run C++ code!

Now that we have everything we need, we should give VSC a test run with our new plugins. VSC works best with project folders so open Finder (for Mac) or File Explorer (for PC) and create a new folder somewhere. It doesn’t really matter where for now as this is just going to be used for testing purposes so somewhere like the Desktop is fine. Once you have created a new folder (it should be empty), open it with VSC. Click on the “Explorer” button on the left panel at the top and click on the “Open Folder” button:

Visual Studio Code with Open Folder selected

Select the folder you just created. This should display the welcome screen again but you just click out of that. Now we need a file to contain our code. We very often call the entry point into a program “main” so you may as well do the same. Create a new file by selecting “File” (in the main menu at the top) and selecting “New File”. You can also create a new file by pressing cmd + N for Mac users or ctrl + N for PC users. Save the file by selecting “File” and selecting “Save As…”. You can also save the file by pressing cmd + s for Mac users or ctrl + s for PC users. Make sure it’s in the folder you just created and call it “main.cpp”. Your configuration should look something like this:

Visual Studio Code with blank main.cpp file

Now we need to write some code to run so copy and paste the following code:

#include <iostream>

int main()
{
	std::cout << “Hello World!”;
}

Don’t worry, we’ll explore the syntax in greater detail later. You will probably notice that the #include <iostream> line has a red squiggly line underneath it. That’s because we haven’t set the compiler path and is, unfortunately, something we have to do with every project. To do so, bring up the browse window by pressing cmd + shift + p (for Mac) or ctrl + shift + p (for PC). Search for “C/C++: Edit Configurations (UI)” and open the window. It should look like this:

IntelliSense Configurations window in Visual Studio Code

Although a few of the variables in the windows may be different, it should look generally the same. Under the “Compiler path” subheading, click on the dropdown button and select “/usr/bin/clang”. Give the file a save and close it. When you go back to main.cpp, the red squiggly line should be gone! Now make sure you save main.cpp. In the upper right corner of VSC, you should see a play button. Go ahead and press it to run the code. Be aware that it will run only the highlighted code if you have code highlighted or will try to run the current file you’re in so make sure you’re in main.cpp every time.

This will run the code in main.cpp (all the code is doing is getting the program to print out “Hello World!”) so you should see the terminal window open at the bottom and some output similar to this:

Hello World C++ program running

The exact text you see will differ based on where your files are saved but you should see Hello World! In there somewhere. My editor text is also much bigger than the default for your easy viewing. Congratulations! You have successfully built and run your very first C++ program!

Project and File Structure

Before we jump into learning the language, let’s talk about how C++ programs and files are structured so that we can understand what’s going on above. C++ programs are started using a main function. This is declared with the int main() {} code above and for now, we want all of our code between the {} otherwise we won’t be able to run it. Our main function is simple because we aren’t passing in any arguments and are running things with a fairly sophisticated compiler in VSC. More rudimentary C++ programs sometimes have a “makefile” which is a way of compiling all of the files at once without running them. A compiler takes code that we can read and write and turns it into machine instructions that the computer can understand and execute. We won’t worry about that here; the key takeaway is that the main function marks the start of a C++ program and when that function finishes running, the program terminates.

Now it’s bad practice to put all of our code in one file so generally we create separate files for related functionality. For example, different game components such as characters, items, rooms, etc. will all have their own separate files. However, we often need to reference other files and libraries in order to get access to the goodies inside. This is done through #include statements. The #include <iostream> above includes the input-output library so gives us access to the std::cout function. Go ahead and delete the #include <iostream> statement and you’ll notice that you immediately get an error with the std::cout code. Most functionality that isn’t declared in the current file and is not part of the basic C++ library will likely need to be imported.

One final thing to note about files in C++ programs is that we very often divide our functionality into .h and .cpp files. The .h files are header files that basically act as blueprints telling the program what variables, functions, etc. that part of the program needs to finish setting up. The .cpp files are C++ files that contain the fully set up variables, functions, etc. that the .h files say they should have. These are the files that contain the code and are actually run. For example, if we needed a bunch of variables and functions in main.cpp, we could create a main.h file, fill it with templates for the variables and functions, and then actually add the body of those variables and functions in main.cpp. Just make sure to #include the .h files in the corresponding .cpp files, otherwise you won’t get access to anything you wrote in the .h file. This may seem redundant but it’s considered best practice and will help you to organize your project. Your coworkers will greatly appreciate it!

 

Transcript

What’s up, guys? Welcome to the first tutorial in our Learn C++ course. This will be on installation and project setup. We’ve got two very easy tasks ahead of us. What we’ll do here is download and install Visual Studio Code, and then I’m gonna really quickly show you how to start a project, we’ll just become a bit more familiar with the IDE and the whole process.

So, let’s head on over to a browser first. Because of course, we need to download it. And we’re going to search for download Visual Studio Code. So I have Chrome open here, although any browser should work. We’re gonna go to this second link, code.visualstudio.com/download. This will take us right to the downloads page. Now, I’m using a Mac, so obviously it makes sense for me to download the Mac installer. But if you’re using Windows or Ubuntu, please download your respective installers. I’m gonna go ahead and click on that, and it should take you to the get started page and start the download as well.

Now, just a heads up, I am recording on a Mac, so everything I do will be from a Mac standpoint. However, once we have everything installed and the plugins in place, everything will be exactly the same between Mac and PC. I’m not a 100% hundred percent sure about Ubuntu ’cause I personally don’t really work with Ubuntu very much. So I recommend you go with either Mac or PC, but there we go.

So, now that this is downloaded, we’re gonna go ahead and open it up. I’ll really quickly show you what it looks like from a Mac standpoint, and then I’ll talk you through the process of if you’re downloading it using a PC. Okay, so you can see that this downloads the the ZIP file. I open up the ZIP file there, and it shows me this Visual Studio Code.app. If you’re using a Mac, all you need to do is drag and drop this into your applications folder and you’re good to go. That’s it. The Visual Studio Code is downloaded and you can open it up and use it.

Now, if you’re using Windows, likely this will open up the installation wizard. I think one of the first steps is just to click next, and then say read and accept the license, and then it will give you a few different screens that ask you to set up various variables, and also to set up stuff like the path, exactly where you want to save it, and so on and so forth. You can actually just use the default values for all of those. So don’t mess around with them at all, just use the default values, click next right the way through. It will give you the installation process, it will show you that installation bar, and then it should be good to go. You’ll have Visual Studio Code installed. So again, just use all the default settings for now. We’ll mess around with things a little bit in the next tutorial.

Okay, so once you have those in place. I’m just gonna go ahead and delete my Visual Studio Code app in the installer there, because I actually already have it right here. Okay, so once that’s done, we’ll go ahead and open up Visual Studio Code for the first time. This isn’t the first time for me, obviously. I wouldn’t be very good at making this course if it was. And this will show us the welcome window here. Okay, so there’s lots to take in here. You can customize the appearance, tools, languages, et cetera. You can find some tutorials here. There’s a bit of help. Gives you recent projects. You probably won’t have anything in here. But it also gives you the option to start new files and projects, et cetera.

So this right here is the file window. Any files that you have open will be displayed here in a tab-like structure. So if you have many files open, you select one at a time and it opens it up. Just a heads-up, likely you won’t have this little play button here just yet. I’ll show you how to get that in the next section. Now, we’re interested in two pieces of this whole screen here.

First it’s gonna be the file explorer up at the top. This is a way to view all of the project files that we have open. Now, we actually don’t have a project open. This is just the main IDE. So that’s why we don’t have anything exciting to see here.

The second is gonna be our extensions button. So we click on this extensions button and it gives us a way to browse for various different plugins. We’ll install two specific plugins in the next section. But for now, just know that it exists. We’ll come back to that later. I do think that this looks a little bit different in Windows, a slightly different symbol, although it does exactly the same thing.

So, before we go any further, all I want to do here is show you how to set up a new project. It’s very, very easy. All we need to do is go to our finder or file explorer, choose the location you wanna save it on. I’m probably gonna go with desktop, just ’cause that’s easy for me to access. I’m gonna create a new folder. So I’m doing Command + Shift + N. I think for you Windows users it’s probably Control + N or Control + Shift + N.

And I’m just going to call this something like C++ Practice. So we recommend you do the same. The name isn’t too, too important, because we’re just going to be using this to test out our language basics. When we go to build our actual project we’ll call this something a bit more significant.

So now that we have the folder created, we don’t need anything in it just yet, we’re gonna go back to our file explorer here, we’re gonna go to open a folder, and we’ll go ahead and find where we saved that folder. It should be on desktop, C++ Practice, down at the bottom. We’ll go ahead and open that guy up. So once again it will show us the welcome window. If we don’t want that we can just exit out. We don’t have any files in this project, which is why there’s nothing here. If we did it would show you all of the files here. It would show you any open files under open editors there. But otherwise, that is it.

So, I just wanted to show you how to download and install Visual Studio Code, how to open up a new instance of it where the couple things that we’ll need are, and finally, how to start a new project. If you do wanna start a new file, then you can go to file, new file here, although I don’t recommend you do so just yet because we haven’t added the C++ extensions that we’ll need. So that’s what we’ll do in this next section coming up, stay tuned for that. Thanks for watching, I will see you guys in the next one.

What is up everyone, welcome to the second tutorial in our learn C++ course. Here we’ll be completing a setup by adding our C++ compiler. This is an essential component for what’s called building and running the C++ code.

So we’ll need two plugins. The first will be the C++ coding tools. I think this is IntelliSense. It’s actually a direct Microsoft plugin and then we’re going to install the C++ compiler. That will be a plugin called Code Run or Code Runner I believe it’s called and will allow us to easily compile and run C++ code.

So lets head on over to Visual Studio Code now and we’re just going to start by going to our plugins or our extensions, this window here and then we go and search for first our C/C++ extension. Okay so it should be this very first one. This C/C++ IntelliSense, debugging, code browsing, etc. So as you can see I already have this installed because my only options are disable and uninstall although your options should be install if you don’t already have it. Go ahead and click on the install button.

Don’t worry it’s totally free and is necessary to build and run our code. You can see it’s got over 9,000,000 downloads at this time so it must be fairly well trusted.

Okay so this may prompt you to restart Visual Studio Code. If it does then please do so open up your project folder and we can go ahead and install the other one. Okay so I’m assuming that you have that installed and we can install the second plugin. If not then you’ll probably want to pause this video, make sure that’s good to go and then come back.

Now the second one that we’ll want to install is going to be our code runner. So we go and search for Code Runner here. Okay it should have this .run, it’s called Code Runner and it’s got over 3,000,000 downloads so quite well trusted and allows you to run all of these languages and more. We’re only really interested in C++ but I found this is by far one of the best extensions to allow us to do so. So we’re gonna go ahead and once again install that. Make sure it’s good to go and again these plugins should only take a couple of minutes to install at most. If you need to restart Visual Studio Code please go ahead and do so and then come back.

We’ll need to preform a little bit more setup. Okay so I’m assuming that’s good to go. Now what we’ll want to do is show all commands. Now I actually can’t press Command + Shift + P because that pauses my recording so we’re going to go to settings here and we’re going to go to the command palette. It’s exactly the same thing. Okay so what we’ll want to do is go to C\C++ edit configurations, so C\C++ and we go and search for edit configurations and we don’t really want the JSON we want the UI it’s just a little bit more user friendly.

Okay and this will open up this window here. So this is the IntelliSense configurations. We need this because we need to essentially specify our compiler. If we don’t specify the compiler then we’re not going to be able to actually compile and run our code. Okay so usually this actually filled in but for whatever reason it isn’t. We’re going to go ahead and add a configuration. We can just call this the configuration name Mac for me is fine although you’ll maybe want to do Window or something like that if you are using a PC.

Okay the next thing we’ll want to do is select our compiler path. Now most operating systems actually come with some sort of compiler already installed. For Mac we’re going to want to chose the clang compiler not the clang++. Make sure it is the /user/bin/clang. So you want to go ahead and make sure you have that. Windows I think they actually recommend a MinGW compiler. I don’t have this because again this inst a PC this is a Mac so the clang is the one I’ll want to go for.

Windows users again that’s going to be the MinGW. If you don’t have the MinGW compiler you can actually find this just by opening up a new window, we go and search for MinGW okay and we’re going to go to mingw.org and this will kind of allow you to search for the most recent downloads. Make sure that you get the most recent version of MinGW and get that installed so you can just kind of download and install it there.

Once that’s done you should be able to add that to your list of compilers there or rather specify your compiler path from that. Okay so from there you’ll want to make sure everything looks the same. You’ll want your workspace folders. The default here you’ll want clang x64 or MinGW if you have that option for Windows otherwise everything is looking pretty much good to go. So we can go ahead and give this a save. I’m just pressing Command + S here. Window users that Control + S or you can just go to file, save okay? We’re gonna go ahead and close that up and we should be good to go.

So if we go back to the file explorer and start opening up and creating C++ programs we should be able to actually compile and run them. We’re not going to do that just yet, we’re actually gonna save that for the next section though because we just want to get everything setup here. Okay so that’s it for now. Like I said when we come back we’ll be writing our very first C++ program to explore kind of how files and projects are structured. So thanks for watching I’ll see you guys in the next one.

What is up everyone? Welcome to the third tutorial in our Learn C++ course. Here we’re just gonna take a few minutes to talk about the C++ file structure. So it goes a bit beyond that, we’ll actually start by covering how C++ programs in general are structured. Then we’ll talk about the files specifically, how they’re structured, we’ll get into the main function and header files, we likely won’t create any header files here just ’cause we really don’t need them. But then we’ll talk about what the purpose of those is and how to include them under the include headers as well. We’ll also toss a name space in, but likely these words won’t mean a whole lot until we actually get to those topics.

So let’s head on over to Visual Studio Code again. And probably the first thing we want to do is actually start by creating a file of our own. So we’ve got all of the compilers and everything set up, we should just be able to create a new file here. We can actually go to file, create a new file. We should probably save this file right away. Make sure it’s a C++ extension. You need to go down here and select a C++, or you can actually just save it as a .cpp file. So we’re going to make sure that we’re saving it under CPP practice, in the same project folder. And I’m just gonna call this main.cpp.

Okay, so that’s C-plus-plus, because we can’t include that actual plus symbol in the file extension. Okay, so this may give you a red squiggly right off the bat saying that there’s basically nothing in this file to run. In this case it seems to be doing okay. So, we’re going to start just by creating this function called main, and actually we should specify int, main like this, and then we’re just going to put into the curly braces, it doesn’t matter whether down here or up here, it really doesn’t matter.

Okay so the reason I created this function before talking about anything else, is because main plays an integral part in the overall C++ program structure. Now, we’re not gonna be building something super, super complex, with dozens and dozens of files, we’ll probably end up with maybe about a dozen files or so. So it’s not gonna be too too crazy, and all those files are gonna be either C++ files or header files.

Now the C++ files contain the code that is actually run. So this means if we’re building this function here, this int main function, then this is going to contain the code that will actually run. The header files, on the other hand, are just a way to set up a template. So, if we had a header, and a C++ file, so main.h, that would be a header file, then essentially that would be used to say that we’re going to have a main function, but we’re not gonna fill in the body of it. So here we can fill in the body of the main function, but the header file is just used to say that our main.cpp file should have a main function. But we’re going to let the main.cpp actually implement that function, or actually provide the body of that function.

Same goes with any variables that we might declare. We might actually declare some variables in the header file, the .h file, but we’ll actually implement them. We’ll give them values in the .cpp file. Okay, so just keep that in mind as we go. The .cpp files are used to actually run code, and the header files, or the .h files, are generally just used to say what should be in the .cpp files. Okay, generally speaking for each of the .cpps we’ll have a header file to go along with it. In this case, because the main is a very special file, we won’t really need one.

Okay so, then that comes to the purpose of this main function. Now the main function itself is kind of the entry point into the program. This is going to be the very, very first thing that’s run in our program, even if we had a hundred other files, we’re going to run our main function first. This is the entry point, and so it needs to be performing all of the setup, or at least calling functions and files that will help to perform the setup. So this will be kind of the entry point into the code, that’s why I said main.cpp is generally a very special file.

So that’s for the most part what we need to know about program structure, we’ll have a main file, that will be the one that runs first, and for each of the other files, generally speaking, we have header, and then we have CPP files that kind of correspond with each other.

Okay, so next up will get into the meat of a file itself. Now we’re not really gonna differentiate too much between the header and the CPP files, just ’cause we don’t have a header file here. But generally speaking, we’ll start with some include statements. Now an include statement will be like this, #include. And is a way to include any other libraries or any other files that we might need. So if we did need a header file, we would include it up here. Same with if we needed any other libraries or anything in this file, any other functions that we needed access to that weren’t declared in this particular file, we need to include them all.

So very often you’ll see lots of these include statements. In this case we’re actually going to include just the one, that’s gonna be iostream, like this. So note, there’s no need for quotes or anything like that. Sometimes you will see some quotes if we’re including a header file, we generally wrap them in quotes like that. So generally speaking, if we’re including files we wrap them in these double quotes. If we are including libraries, like iostream is a library, that means it contains a bunch of functions and stuff, then for that we don’t actually need the quotes here, we’re fine with just the angular brackets.

Okay, we’ll talk more about the main function in just a second. One other thing I want to point out before moving forward is these double forward slashes. This represents a comment, so anything we put here will be completely ignored by the compiler. Now this is clearly nonsense, it doesn’t do anything. If I were to get rid of that then we’d have an issue here, you can see it right away there’s an issue. But the double forward slash makes it a comment. So basically, the compiler ignores all comments, they are really just there for the coders to read.

So let’s say that I was building my main function, and I realized that there is a weird bug. So it’s producing some output I don’t expect, or it’s not quite working, then I can make a comment saying “Main function is not working properly.” Maybe give a more detailed description of the issue, and then kind of put like a “TODO fix this function”, or something like that. It doesn’t even have to be an error, it could just be describing how the function works so that anyone reading your code can just look at the comments and quickly say “Okay, this function does this, I can ignore this. “Well, this function does this, “I need to pay attention to it.”

Okay, so we talked about the headers, we talked a little bit about main function, we talked about how projects and files are structured. One thing to note actually, with regards to Visual Studio Code specifically, because we’re using a special kind of a compiler we don’t need what’s called a makefile. Now some kinds of C++ compilers will need a file that’s called a makefile, which basically helps to build or compile the files. So in that you’d put all the files that need to be compiled and then that would kind of take care of that for us.

That’s not really something we have to worry about, just because we’re using Visual Studio Code and the specific plug-in. So okay, so just be aware of that if you are developing in a very basic environment, so just like a tech set as you’re in Terminal, you will likely need a makefile as well. It’s a bit beyond this course, so we’ll not worry about that for now.

Okay, so last thing I want to talk about here before we fix this issue that’s clearly something wrong, is gonna be that all of the code that we’ll write, at least for now, and over the next several tutorials, is gonna be inside of this main function. So we will put all of the code in these brackets here, and we won’t put any of that code outside of the brackets. So before or after the main function. And that’s because all of the code in C++ programs needs to be actually run within functions. We can kind of set things up and declare things outside of functions, but as soon as we want something to run then we need to put it inside of a function somehow.

Okay, so just be sure to not write any code outside of main, other than comments, comments are fine, again, because they’re not really run, they’re just kind of ignored. Okay, so finally let’s just go ahead and see what this issue is, it’s probably something to do with the compiler path. Thought we fixed that issue, but let’s see if we can figure out what’s going on there. So let’s go take a look in our command pallet, we’ll go into edit configurations and see if that is an issue.

So for whatever reason the compiler path has defaulted back to GCC, pretty sure we said that to C-lang, but that’s okay. And, so, that should be good. Okay, so once we get that done, this issue should go away. And it has indeed, because we’ve gotten rid of that red squiggly. Again, if you’re using Windows, probably you’ll do min-gW instead of the C-lang. Just make sure it is switched to a compiler that actually works, and doesn’t give you that red squiggly line.

Okay, last thing we’ll do here is just run this program. Now, it’s really not gonna do anything. Don’t worry about that, in fact, let’s actually just do this. We’ll do standard, we’ll do c-out, and actually it should be this, c-out, and we’ll just Hello World! Just the classic, I’m sure you guys have all seen Hello World! at some point in your lives. So don’t worry about exactly what this means, essentially this is just outputting this value here. We’ll talk more about that in the next section. So we just wanna go ahead and run that code.

Okay, we can see if we run this we’re not getting any output, and that’s because we haven’t saved the file. So we need to make sure that this is saving everything before we run it, the compiler is a little finicky like that. If you see this black dot inside of an X, that means you need to save the file. So we’ll go ahead and give that a rerun. And you can clearly see that Hello World! is printed there.

Okay, so that’s all we want to cover here. We talked about the file and the project structure of C++ programs. When we come back will be focusing more on this stuff which is input, output, so stay tuned for that. Thanks for watching, see you guys in the next one.

Interested in continuing? Check out the full C++ Programming for Beginners course, which is part of our C++ Programming Bundle.

]]>
C++ Programming for Beginners https://gamedevacademy.org/c-programming-for-beginners/ Tue, 28 Jun 2016 12:00:12 +0000 https://html5hive.org/?p=1491 Read more]]> Are you ready for C++? This course introduces you to function templates, namespaces, classes and more. If you are already comfortable the C syntax and basic principles of object oriented programing, then take the next step and learn C++.

C++ is still King in the game industry, number crunching at extreme speeds and compilers because C++ is built around the idea of precision resource and memory management. If you are ready for C++, this is the course for you.

Access this course on Zenva Academy

]]>