<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Game Code SchoolGame Code School -  &#187; C++</title>
	<atom:link href="https://gamecodeschool.com/category/c-plus-plus/feed/" rel="self" type="application/rss+xml" />
	<link>https://gamecodeschool.com</link>
	<description>Game Coding for Beginners</description>
	<lastBuildDate>Wed, 29 Jan 2025 11:28:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Beginner&#8217;s Guide to Handling Errors in C++</title>
		<link>https://gamecodeschool.com/c-plus-plus/beginners-guide-to-handling-errors-in-c/</link>
		<comments>https://gamecodeschool.com/c-plus-plus/beginners-guide-to-handling-errors-in-c/#comments</comments>
		<pubDate>Thu, 25 May 2023 13:06:20 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://gamecodeschool.com/?p=16644</guid>
		<description><![CDATA[Writing error-free code is a crucial skill for any programmer. This guide will provide beginners with an overview of handling errors while writing C++ code.  We will cover different types of errors, including configuration errors, compile errors, link errors, and bugs. Each section will be accompanied by game-like examples to illustrate the concepts effectively. &#160; [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Writing error-free code is a crucial skill for any programmer. This guide will provide beginners with an overview of handling errors while writing C++ code.  We will cover different types of errors, including configuration errors, compile errors, link errors, and bugs. Each section will be accompanied by game-like examples to illustrate the concepts effectively.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="alignleft size-full wp-image-16509" src="https://gamecodeschool.com/wp-content/uploads/2015/01/patreon1.jpg" alt="patreon" width="125" height="38" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2>Configuration Errors</h2>
<p>Configuration errors occur when the development environment is not set up properly. These errors can prevent your code from compiling or running correctly. Here are some common configuration errors you may encounter:</p>
<p>For example, let&#8217;s say you&#8217;re developing a game and you receive a configuration error stating that the required graphics library is not found. This error indicates that the necessary configuration for your graphics library is missing. To resolve this, you need to ensure that the library is properly installed and its paths are correctly set in the project settings. An example article that covers this skill is <a href="https://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Setting up the Visual Studio development environment</a>.</p>
<h2>Compile Errors</h2>
<p>Compile errors occur when there are mistakes or inconsistencies in your code that prevent the compiler from translating them into machine-readable instructions. These errors are often caused by syntax errors, type mismatches, or missing declarations.</p>
<p>As an example, suppose you&#8217;re creating a game character class, and you forget to include a semicolon at the end of a class definition. This will result in a compile error, and the compiler will highlight the missing semicolon. To fix this error, simply add the semicolon at the appropriate location. These are the most common type of error and fortunately, the easiest to fix.</p>
<p>Here&#8217;s an example of a compile error in C++ code. Can you work it out for yourself?</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">#include &lt;iostream&gt; int main()
{
    int x = 10; int y = "20"; // Error: Type mismatch int sum = x + y;
    std::cout &lt;&lt; "The sum is: " &lt;&lt; sum &lt;&lt; std::endl; return 0;
}</pre><br />
In the preceding example, we have a simple program that adds two numbers and prints the result. However, there is a compile error in the code. Let&#8217;s analyze the error:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">int y = "20"; // Error: Type mismatch</pre><br />
The error occurs because we are trying to assign a string value (enclosed in double quotes) to an integer variable <pre class="crayon-plain-tag">y</pre>. This is a type mismatch because <pre class="crayon-plain-tag">y</pre> is declared as an integer, but we are assigning a string value to it.</p>
</div>
</div>
<p>When you try to compile this code in Visual Studio, you will receive an error message indicating the type mismatch:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">error: invalid conversion from 'const char*' to 'int'</pre><br />
To fix this compile error, you need to ensure that the variable <pre class="crayon-plain-tag">y</pre> is assigned an integer value instead of a string. For example:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md"><pre class="crayon-plain-tag"><span class="hljs-type">int</span> y = <span class="hljs-number">20</span>; <span class="hljs-comment">// Fixed: Assigning an integer value</span></pre></div>
</div>
<p>By correcting the type mismatch, the code will compile successfully, and you will get the desired output without any errors.</p>
<h2>Link Errors</h2>
<p>Link errors occur during the linking phase of compilation when the compiler tries to combine different object files and libraries to create the final executable. These errors are typically caused by missing function definitions or unresolved external symbols.</p>
<p>An example might help. Imagine you&#8217;re working on a game that uses a physics library. If you forget to include the necessary physics library files or provide the required function definitions, you will encounter a link error. To resolve this, ensure that you have included all the required libraries and properly link them with your project. To properly link all the files in an SFML game project, read this article: <a href="https://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a>.</p>
<p>Here&#8217;s another beginner-friendly example of a link error in C++ code:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">#include &lt;iostream&gt;

int main()
{
    sayHello(); // Error: Undefined reference to 'sayHello'
    return 0;
}

void sayHello()
{
    std::cout &lt;&lt; "Hello, World!" &lt;&lt; std::endl;
}</pre><br />
In this example, we have a program that attempts to call a function called <pre class="crayon-plain-tag">sayHello()</pre> within the <pre class="crayon-plain-tag">main()</pre> function. However, there is a link error in the code. Let&#8217;s analyze the error:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">sayHello(); // Error: Undefined reference to 'sayHello'</pre><br />
The error occurs because the compiler can&#8217;t find the definition of the <pre class="crayon-plain-tag">sayHello()</pre> function during the linking phase. In this case, the function declaration is below the <pre class="crayon-plain-tag">main()</pre> function, so the compiler doesn&#8217;t have the necessary information to link the function call properly.</p>
</div>
</div>
<p>When you try to compile this code in Visual Studio, you will receive a link error message similar to:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">error LNK2019: unresolved external symbol "void __cdecl sayHello(void)" (?sayHello@@YAXXZ) referenced in function _main</pre><br />
To fix this link error, you need to ensure that the function definition (<pre class="crayon-plain-tag">void sayHello()</pre>) is placed above the <pre class="crayon-plain-tag">main()</pre> function:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">void sayHello()
{
    std::cout &lt;&lt; "Hello, World!" &lt;&lt; std::endl;
}

int main()
{
    sayHello(); // Function call return 0;
}</pre><br />
By placing the function definition above the <pre class="crayon-plain-tag">main()</pre> function, the linker can find the definition of <pre class="crayon-plain-tag">sayHello()</pre> and successfully link the function call. This resolves the link error, and the program will execute as expected, printing &#8220;Hello, World!&#8221; to the console.</p>
</div>
</div>
<h2>Bugs</h2>
<p>Bugs are issues that arise during the execution of your program. They can cause unexpected behavior, crashes, or incorrect results. Debugging is the process of identifying and fixing bugs.</p>
<p>Suppose you&#8217;re creating a game where the player&#8217;s character keeps falling through the floor. This unexpected behavior is a bug. To identify the cause, you can use the Visual Studio debugger. Set breakpoints, step through the code, and inspect variables to find the error. In this case, you might discover that the collision detection code is incorrect, and fixing it will resolve the bug.</p>
<p>Here&#8217;s an example of a bug in C++ code:</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">#include &lt;iostream&gt; int main()
{
    int x = 5; int y = 0;
    int division_result = x / y;
    std::cout &lt;&lt; "The division result is: " &lt;&lt; division_result &lt;&lt; std::endl;
    return 0;
}</pre><br />
In this example, we have a program that calculates the division of two numbers and prints the result. However, there is a bug in the code. Let&#8217;s analyze the bug:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">int division_result = x / y;</pre><br />
The bug occurs because we are dividing the variable <pre class="crayon-plain-tag">x</pre> by <pre class="crayon-plain-tag">y</pre>, but <pre class="crayon-plain-tag">y</pre> is assigned the value of <pre class="crayon-plain-tag"></pre>. Of course, y could be equal to zero because of the way the player played the game, and therefore impossible for the compiler to know before the game is played. Hence this is a bug, not a compile or link error. This will result in a division by zero error, which is undefined behavior in C++.</p>
</div>
</div>
<p>When you run this code in Visual Studio, you will encounter a runtime error:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">Unhandled exception at 0x004115D2 in Example.exe: 0xC0000094: Integer division by zero.</pre><br />
To fix this bug, you need to ensure that the divisor (<pre class="crayon-plain-tag">y</pre>) is not equal to zero before performing the division. For example, you can add a check to prevent division by zero:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">int division_result;
if (y != 0)
{
    division_result = x / y;
}
else
{
    std::cout &lt;&lt; "Error: Division by zero is not allowed." &lt;&lt; std::endl; // Handle the error or exit the program gracefully
}</pre><br />
By checking if the divisor is zero before performing the division, you can prevent the bug and handle the error appropriately.</p>
</div>
</div>
<h2>Summary</h2>
<p>Handling errors while writing C++ code is an essential skill for developers. By understanding and addressing configuration errors, compile errors, link errors, and bugs, you can write more robust and reliable programs. Remember to pay attention to error messages, use the debugging tools available in the Visual Studio environment, and continually improve your coding skills to minimize errors and create high-quality games.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="alignleft size-full wp-image-16509" src="https://gamecodeschool.com/wp-content/uploads/2015/01/patreon1.jpg" alt="patreon" width="125" height="38" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/c-plus-plus/beginners-guide-to-handling-errors-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using C++ vectors</title>
		<link>https://gamecodeschool.com/c-plus-plus/using-c-vectors/</link>
		<comments>https://gamecodeschool.com/c-plus-plus/using-c-vectors/#comments</comments>
		<pubDate>Thu, 18 May 2023 10:37:16 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://gamecodeschool.com/?p=16638</guid>
		<description><![CDATA[Here&#8217;s a quick tutorial on using the C++ [crayon-69f5f0156514c016757504-i/] from the Standard Template Library (STL). Be sure to check my tutorial on C++ maps, also from the STL. The Standard Template Library (STL) is a collection of data containers and ways to manipulate the data we put in those containers. It is a way to store and [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a quick tutorial on using the C++ <pre class="crayon-plain-tag">vector</pre> from the Standard Template Library (STL). Be sure to check my tutorial on <a href="https://gamecodeschool.com/c-plus-plus/organizing-your-game-data-with-c-maps/">C++ maps</a>, also from the STL. The Standard Template Library (STL) is a collection of data containers and ways to manipulate the data we put in those containers. It is a way to store and manipulate different types of C++ variables and classes. We can think of the different containers as way more advanced arrays. The STL is part of C++ because its containers and the code that manipulates them contain code that we and just about every C++ programmer are all going to need at some point.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="alignleft size-full wp-image-16509" src="https://gamecodeschool.com/wp-content/uploads/2015/01/patreon1.jpg" alt="patreon" width="125" height="38" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>To begin, let&#8217;s include the necessary header file for using vectors:</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">#include &lt;vector&gt;</pre><br />
Next, let&#8217;s declare and initialize a vector. We&#8217;ll start with simple examples using <pre class="crayon-plain-tag">int</pre> and <pre class="crayon-plain-tag">string</pre> types:</p>
</div>
</div>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">std::vector&lt;int&gt; numbers; // An empty vector of integers
std::vector&lt;std::string&gt; names = {"Alice", "Bob", "Charlie"}; // A vector of strings with initial values</pre><br />
In the first line, we declare an empty vector of integers called <pre class="crayon-plain-tag">numbers</pre>. In the second line, we declare a vector of strings called <pre class="crayon-plain-tag">names</pre> and initialize it with three values: &#8220;Alice&#8221;, &#8220;Bob&#8221;, and &#8220;Charlie&#8221;.</p>
</div>
</div>
<p>Now, let&#8217;s add elements to the vector using the <pre class="crayon-plain-tag">push_back</pre> function:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">numbers.push_back(10); // Add 10 to the end of the numbers vector
names.push_back("Dave"); // Add "Dave" to the end of the names vector</pre><br />
The <pre class="crayon-plain-tag">push_back</pre> function appends elements to the end of the vector. In the first line, we add the integer value 10 to the <pre class="crayon-plain-tag">numbers</pre> vector, and in the second line, we add the string value &#8220;Dave&#8221; to the <pre class="crayon-plain-tag">names</pre> vector.</p>
</div>
</div>
<p>To access elements in the vector, we can use the subscript operator <pre class="crayon-plain-tag">[]</pre> or the <pre class="crayon-plain-tag">at()</pre> function:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">int firstNumber = numbers[0]; // Access the first element of the numbers vector
std::string secondName = names.at(1); // Access the second element of the names vector using the at() function (bounds-checked access)</pre><br />
In the first line, we retrieve the first element of the <pre class="crayon-plain-tag">numbers</pre> vector using the subscript operator. In the second line, we retrieve the second element of the <pre class="crayon-plain-tag">names</pre> vector using the <pre class="crayon-plain-tag">at()</pre> function, which performs bounds checking to ensure we&#8217;re accessing a valid element.</p>
</div>
</div>
<p>If we want to modify elements in the vector, we can directly assign new values:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">numbers[0] = 20; // Modify the first element of the numbers vector to 20
names.at(2) = "Eve"; // Modify the third element of the names vector to "Eve"</pre><br />
In the first line, we change the value of the first element in the <pre class="crayon-plain-tag">numbers</pre> vector to 20. In the second line, we update the third element in the <pre class="crayon-plain-tag">names</pre> vector to &#8220;Eve&#8221; using the <pre class="crayon-plain-tag">at()</pre> function.</p>
</div>
</div>
<p>Looping through the vector is useful for iterating over its elements. Here are two examples of looping through the vector:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">for (int i = 0; i &lt; numbers.size(); i++)
{
    int num = numbers[i]; // Process num (e.g., print, perform calculations, etc.)
}

for (const std::string&amp; name : names)
{
    // Process name (e.g., print, manipulate, etc.)
}</pre><br />
The first loop uses a traditional <pre class="crayon-plain-tag">for</pre> loop with an index variable. We iterate from 0 to <pre class="crayon-plain-tag">numbers.size() - 1</pre> and access each element using the subscript operator <pre class="crayon-plain-tag">[]</pre>. The second loop uses a range-based <pre class="crayon-plain-tag">for</pre> loop, which iterates over each element in the <pre class="crayon-plain-tag">names</pre> vector directly, assigning the value to the <pre class="crayon-plain-tag">name</pre> variable.</p>
</div>
</div>
<p>Now, let&#8217;s work with pointers to <pre class="crayon-plain-tag">GameObject</pre> instances in the vector. We&#8217;ll use smart pointers to manage memory automatically:</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">
<pre class="crayon-plain-tag">#include &lt;memory&gt;

struct GameObject {
    // Define GameObject properties and methods
};

std::vector&lt;std::shared_ptr&lt;GameObject&gt;&gt; gameObjects; // Create a new GameObject instance and add it to the vector
std::shared_ptr&lt;GameObject&gt; newObject = std::make_shared&lt;GameObject&gt;();
gameObjects.push_back(newObject); // Loop through each GameObject in the vector

for (const std::shared_ptr&lt;GameObject&gt;&amp; obj : gameObjects)
{
    // Access obj and perform game-related operations
}</pre><br />
In this example, we include the <pre class="crayon-plain-tag">&lt;memory&gt;</pre> header to use smart pointers. We define a <pre class="crayon-plain-tag">struct</pre> called <pre class="crayon-plain-tag">GameObject</pre> to represent game objects. Then, we create a vector called <pre class="crayon-plain-tag">gameObjects</pre> to store pointers to <pre class="crayon-plain-tag">GameObject</pre> instances.</p>
</div>
</div>
<p>To add a new <pre class="crayon-plain-tag">GameObject</pre> to the vector, we create a shared pointer using <pre class="crayon-plain-tag">std::make_shared&lt;GameObject&gt;()</pre> and add it to the <pre class="crayon-plain-tag">gameObjects</pre> vector using <pre class="crayon-plain-tag">push_back</pre>.</p>
<p>Finally, we iterate over the <pre class="crayon-plain-tag">gameObjects</pre> vector using a range-based <pre class="crayon-plain-tag">for</pre> loop. Each element in the vector is accessed as a <pre class="crayon-plain-tag">const std::shared_ptr&lt;GameObject&gt;&amp;</pre> reference, allowing us to access and manipulate the game objects as needed.</p>
<p>&nbsp;</p>
<p>To expand upon this idea look at the tutorial <a href="https://gamecodeschool.com/sfml/building-a-simple-game-engine-in-c-plus-plus/">Programming a simple game engine</a> in C++.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="alignleft size-full wp-image-16509" src="https://gamecodeschool.com/wp-content/uploads/2015/01/patreon1.jpg" alt="patreon" width="125" height="38" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/c-plus-plus/using-c-vectors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Coding a simple text adventure in C++</title>
		<link>https://gamecodeschool.com/c-plus-plus/coding-a-simple-text-adventure-in-c/</link>
		<comments>https://gamecodeschool.com/c-plus-plus/coding-a-simple-text-adventure-in-c/#comments</comments>
		<pubDate>Mon, 08 May 2023 12:07:44 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://gamecodeschool.com/?p=16447</guid>
		<description><![CDATA[As the last tutorial before we install a graphics library I thought a simple example that involves a game loop but no graphics would be worth while. Here&#8217;s a simple C++ tutorial for creating an adventure game where a prisoner escapes from a dungeon: Setting up the game To begin, create a new C++ project [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>As the last tutorial before we install a graphics library I thought a simple example that involves a game loop but no graphics would be worth while. Here&#8217;s a simple C++ tutorial for creating an adventure game where a prisoner escapes from a dungeon:</p>
<h2>Setting up the game</h2>
<p>To begin, create a new C++ project in your preferred development environment. Once you have created the project, create a new source file for your game. You can name it &#8220;main.cpp&#8221; or anything you like.</p>
<h3>Defining game variables</h3>
<p>Next, define the variables that will be used in the game. In this case, you will need variables to keep track of the player&#8217;s current location and the game&#8217;s state.</p><pre class="crayon-plain-tag">int location = 0;
bool gameRunning = true;</pre><p></p>
<h2>Creating the game loop</h2>
<p>As we have learned before the game loop is the heart of your game. It will continuously run until the game is over. Inside the game loop, you will have to write code to handle the player&#8217;s input and update the game state accordingly.</p><pre class="crayon-plain-tag">while(gameRunning){
     // get player input
     // update game state
}</pre><p></p>
<h2>Implementing the game logic</h2>
<p>The game logic defines how the player can interact with the game world. In this case, the player will need to navigate through different rooms in the dungeon to find a way to escape. You will need to define a list of possible actions the player can take in each room and what happens when they take that action.</p>
<p>Here&#8217;s an example code snippet to get you started:</p><pre class="crayon-plain-tag">while(gameRunning){
// display room description
// get player input
if (location == 0){ // player is in the cell
if (input == "look"){
     std::cout &lt;&lt; "You are in a small, dank cell with a rusted iron door.\n";
}
else if (input == "open door"){
     std::cout &lt;&lt; "The door is locked.\n";
}
else if (input == "use key"){
     std::cout &lt;&lt; "You don't have a key.\n";
}
else if (input == "escape"){
     std::cout &lt;&lt; "You can't escape from here without finding a way to open the door.\n";
}
else{
     std::cout &lt;&lt; "I don't understand that command.\n";
}
}
// add more room descriptions and actions here
}</pre><p></p>
<h2>Adding game objects</h2>
<p>To make the game more interesting, you can add objects that the player can interact with. For example, the player might find a key that can be used to unlock a door, or a weapon that can be used to fight enemies. You will need to define the objects and their properties, such as their name, description, and location.</p><pre class="crayon-plain-tag">struct Object{
std::string name;
std::string description;
int location;
};

Object key = {"key", "A small iron key.", 2};</pre><p>You can then modify the game logic to handle the player interacting with objects:</p><pre class="crayon-plain-tag">int location = 0;

void movePlayer(std::string direction){
  if (direction == "north" &amp;&amp; location == 0){
     location = 1;
     std::cout &lt;&lt; "You have moved to the north.\n";
}
else if (direction == "south" &amp;&amp; location == 1){
     location = 0;
     std::cout &lt;&lt; "You have moved to the south.\n";
}
else{
     std::cout &lt;&lt; "You cannot move in that direction.\n";
}
}

while(gameRunning){
     std::string input;
     std::cout &lt;&lt; "You are in a " &lt;&lt; rooms[location].description &lt;&lt; ".\n";
     std::cout &lt;&lt; "What would you like to do?\n";
     std::cin &gt;&gt; input;

if (input == "move"){
     std::string direction;
     std::cout &lt;&lt; "Which direction would you like to move?\n";
     std::cin &gt;&gt; direction;
     movePlayer(direction);
}
else if (input == "quit"){
     gameRunning = false;
     std::cout &lt;&lt; "Goodbye!\n";
}
else{
     std::cout &lt;&lt; "Invalid input.\n";
}
}</pre><p>This code defines a movePlayer function that takes a direction parameter and updates the location variable based on the player&#8217;s input. The while loop displays the room description and prompts the player for input. If the player inputs &#8220;move&#8221;, the code prompts the player for a direction and calls the movePlayer function. If the player inputs &#8220;quit&#8221;, the game ends.</p>
<p>To make the game more challenging, you can add multiple levels with increasing difficulty. Each level can have different puzzles and obstacles that the player must overcome to progress to the next level. For example, in the first level, the player might need to find a way to escape the dungeon, while in the second level, the player might have to navigate through a maze to reach the exit.</p>
<p>You can define each level as a separate function, and call them from the game loop based on the player&#8217;s progress, like this, perhaps:</p><pre class="crayon-plain-tag">void level1(){
// game logic for level 1
}

void level2(){
// game logic for level 2
}

while(gameRunning){
if (location == 0){ // player is in the cell
level1(); // call level 1 function
}
else if (location == 1){ // player is in level 2
level2(); // call level 2 function
}
// add more levels here
}</pre><p></p>
<h2>Adding game over conditions</h2>
<p>Finally, to make the game more engaging, you can add game over conditions, such as running out of health, or failing to complete a puzzle within a certain time limit. You can use these conditions to end the game and display a game over screen to the player.</p>
<p>Time for a real game now. To get started we will need to <a href="https://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">setup a Visual Studio project that uses SFML</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/c-plus-plus/coding-a-simple-text-adventure-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Organizing your Game Data with C++ Maps</title>
		<link>https://gamecodeschool.com/c-plus-plus/organizing-your-game-data-with-c-maps/</link>
		<comments>https://gamecodeschool.com/c-plus-plus/organizing-your-game-data-with-c-maps/#comments</comments>
		<pubDate>Mon, 08 May 2023 00:40:14 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">https://gamecodeschool.com/?p=16440</guid>
		<description><![CDATA[Maps are a great feature of C++ they allow us to store objects (made from classes) of any type and store them paired with any other variable. One useful combination I have used a fair bit in games programming is strings and Texture objects. The string represents the name of the graphics file and the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Maps are a great feature of C++ they allow us to store objects (made from classes) of any type and store them paired with any other variable. One useful combination I have used a fair bit in games programming is strings and Texture objects. The string represents the name of the graphics file and the Texture is an instance of a class provided by the graphics API, such as SFML.</p>
<p>To get started you would define your Texture class: A Texture class typically represents an image or texture that can be used for rendering. In the context of this tutorial, we assume that the Texture class has a constructor that takes a filename as an argument and loads the corresponding image file. You may also have other methods and properties in your Texture class depending on your specific needs.</p>
<p>Define your Texture class: A Texture class typically represents an image or texture that can be used for rendering. In the context of this tutorial, we assume that the Texture class has a constructor that takes a filename as an argument and loads the corresponding image file. You may also have other methods and properties in your Texture class depending on your specific needs.</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">class Texture {
public:
    // constructor
    Texture(std::string filename);
    // destructor
    ~Texture();
    // other methods and properties // ...
};</pre>
</div>
</div>
<p>Include the necessary headers: To use maps in C++, you need to include the <pre class="crayon-plain-tag">&lt;map&gt;</pre> header. You also need to include the <pre class="crayon-plain-tag">&lt;string&gt;</pre> header for working with strings.</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">#include &lt;map&gt;
#include &lt;string&gt;</pre>
</div>
</div>
<p>Declare the map that will store instances of the Texture class: In C++, a map is a container that stores key-value pairs. In this case, we want to store instances of the Texture class with a string key that represents each texture. To do this, we declare a map with a string key and a pointer to a Texture object as the value.</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">std::map&lt;std::string, Texture*&gt; textures;</pre>
</div>
</div>
<p>Add textures to the map: To add textures to the map, we first create instances of the Texture class using the constructor and pass in the corresponding filenames. We then add each Texture object to the map using a string key that represents the texture. In this example, we add two Texture objects to the map with the keys &#8220;texture1&#8243; and &#8220;texture2&#8243;.</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">Texture* texture1 = new Texture("texture1.png");
Texture* texture2 = new Texture("texture2.png");
textures["texture1"] = texture1;
textures["texture2"] = texture2;</pre>
</div>
</div>
<p>Access textures from the map: To access a Texture object from the map, we use the string key that was used to add the object to the map. In this example, we access the &#8220;texture1&#8243; object and store it in a pointer called &#8220;texture&#8221;.</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">Texture* texture = textures["texture1"];</pre>
</div>
</div>
<p>Delete Texture objects when you&#8217;re done with them: It&#8217;s important to properly manage memory when working with pointers to avoid memory leaks. In this case, we need to delete the Texture objects that were created with the &#8220;new&#8221; operator when we&#8217;re done with them.</p>
<div class="bg-black rounded-md mb-4">
<div class="p-4 overflow-y-auto">
<pre class="crayon-plain-tag">delete texture1;
delete texture2;</pre><br />
That&#8217;s it! With this code, you can easily store and access Texture objects using a string key. The map provides an efficient way to associate each Texture object with a unique key, and it simplifies the process of retrieving Texture objects by their key.</p>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/c-plus-plus/organizing-your-game-data-with-c-maps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Game Coding Level 1</title>
		<link>https://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/</link>
		<comments>https://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/#comments</comments>
		<pubDate>Sun, 08 Nov 2015 12:30:23 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=12358</guid>
		<description><![CDATA[This course is for you if you are completely new to programming or the C++ language. This tutorial course will explain all you need to know to code C++ games as quickly as is realistic. This course will also be relevant if you wanted an introduction to C++ that was a bit more fun and a lot more visual than [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>[widgets_on_pages id=&#8221;udemy_code_details&#8221;]</p>
<div class="fusion-one-full fusion-layout-column fusion-column-last fusion-spacing-yes" style="margin-top:0px;margin-bottom:20px;"><div class="fusion-column-wrapper"></div></div><div class="fusion-clearfix"></div>This course is for you if you are completely new to programming or the C++ language. This tutorial course will explain all you need to know to code C++ games as quickly as is realistic. This course will also be relevant if you wanted an introduction to C++ that was a bit more fun and a lot more visual than a typical C++ beginners guide.<br />
[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
There will be a whole range of game related mini-projects to accompany this course and you will be able to choose which ones you are most interested in completing. I would suggest however that you try out all the practical projects that are suggested throughout these tutorials as you will learn faster.</p>
<p>This course is also the place to start if you want to progress to learn to code for many different development platforms. For example C++ is the language of Unreal Engine and CryEngine the two most advanced game engines available. This C++ course will be especially relevant if you are an aspiring indie developer who wants to make super-fast 2d games; perhaps you want to get your game on Steam? C++ is the place to start. To accompany this C++ course there will be practical <a href="http://gamecodeschool.com/sfml-projects/">projects that use the SFML</a> C++ library which is probably the best way for someone just starting game development who wants to make 2d games for any of the desktop operating systems. These mini-projects will lead to full working game projects.</p>
<p>This C++ course will assume you know absolutely nothing about C++ or any other programming language. It will explain all jargon as we proceed through each tutorial.</p>
<p>At times in the course, we will take an optional break from theory to do an appropriate project. These projects are hands-on real coding and are much more fun than theory. All the projects will be as game related as possible, including some full working games. The tutorial list here will grow over the coming days and weeks.</p>
<h2>Explaining code through comments</h2>
<p>Sometimes I will add extra explanation or clarification within the code itself. To do this I will use C++ comments. Whenever you see a line of code with two forward slashes- like this <span style="color: #008000;">//</span> at the start, that line of code doesn&#8217;t do anything except tell you something about the code. In our C++ programs, we will use comments to remind us of what different blocks or lines of code achieve. Here is what a comment looks like.</p>
<pre class="brush: cpp; title: ; notranslate">

// I am just a comment and don't really do anything

spaceShip.shoot(alien);

// The line of code above shoots an alien
// That was a useful comment wasn't it
</pre>
<p>Enough of all the introductions let&#8217;s get on with the tutorials.</p>
<h2>The C++ game coding tutorials</h2>
<p>The tutorials are designed to get you coding games as fast as possible. They are not fully comprehensive and some topics have been trimmed to the maximum. I am sure that the best way of learning to code C++ games; is to code C++ games. So the sooner we can start doing that the better. You will find that all of the practical C++ projects on this site come with loads of refresher information and of course lots of useful C++ comments using &#8220;//&#8221;. So don&#8217;t feel you need to master a topic before moving on. You can always refer back.</p>
<h3>1 &#8211; Game Variables in C++</h3>
<p>This tutorial introduces the fundamental C++ building blocks of our game, variables. The variables tutorial explains how we keep track of the state of our game when writing in C++. Variables can be everything from the players score to an entire level of our game. Let&#8217;s get started and learn about <a href="http://gamecodeschool.com/c-plus-plus/game-variables-c-plus-plus/">game data and variables in C++</a>.</p>
<p>[widgets_on_pages id=&#8221;bcgp_cfgp_gpp&#8221;]</p>
<h3>2 &#8211; Manipulating Game Variables in C++</h3>
<p>This tutorial shows us the mathematical way in C++ that we can change our game&#8217;s data that is contained within our variables. After all, the player&#8217;s score does not remain static. <a href="http://gamecodeschool.com/c-plus-plus/manipulating-the-value-of-our-games-variables/">Changing game variables in C++</a>.</p>
<h3>3 &#8211; Checking for conditions in C++</h3>
<p>Now that we can use variables to represent all the vital data in our game we will see how we can test for important events called <strong>conditions</strong> within our game. How do we know when the player has lost their last life or achieved a new high-score? Find out about <a href="http://gamecodeschool.com/c-plus-plus/condition-checking-in-a-game/">Checking for conditions in C++</a>.</p>
<h3>4 &#8211; Branching our C++ game code</h3>
<p>Here we will use everything we learned about conditions and variables so far to make our game take a different course dependent upon an outcome. Learn about <a href="http://gamecodeschool.com/c-plus-plus/structuring-and-branching-the-code/">Branching our C++ game code</a>.</p>
<h3>5 &#8211; Looping our game code</h3>
<p>In game coding, we will regularly want to execute parts of our code multiple times while making subtle or not-so-subtle variations to our C++ code on each pass. For example, each and every frame of our game is contained in just such a loop. This is how it works: <a href="http://gamecodeschool.com/c-plus-plus/loops-in-the-game-code/">Looping our game code</a>.</p>
<h3>6 &#8211; Organizing code with functions</h3>
<p>Functions are the organizing blocks of our code. We can think of a function as a black box that does one very specific task and can be reused over and over. Learn how we <a href="http://gamecodeschool.com/c-plus-plus/organizing-game-code-with-functions/">organize our game code with C++ functions</a>.</p>
<h3>7 &#8211; Introducing OOP for C++ games</h3>
<p>OOP is probably the most vital topic in modern game coding. How do we break down our planned game and the objects (like characters, spaceships, and levels) into its most appropriate constituent parts? Find out in this <a href="http://gamecodeschool.com/c-plus-plus/introduction-to-oop-for-c_plus_plus-games/">introduction to OOP in C++ game coding</a>.</p>
<h3>8 &#8211; Game data handling with C++ arrays</h3>
<p>C++ arrays are what enable us to manage lots of objects in our game in an orderly manner. It is all well and good to have a well-designed object that can represent a zombie, an invader or a bullet; but what about when we need dozens, hundreds or even thousands of them? This brief tutorial solves the problem by <a href="http://gamecodeschool.com/c-plus-plus/handling-game-data-with-c-arrays">learning about C++ arrays</a>.<br />
[widgets_on_pages id=&#8221;udemy_advert_cpp_2&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]</p>
<h3>9 &#8211; Using C++ references to make code faster</h3>
<p>When we pass values to a function or return values from a function that is exactly what we are doing. Passing or returning a value. What happens is that a copy of the variable’s value is made, and sent into the function where it is used. Nothing happens to the actual variable itself. C++ references allow us to work around this. But why would we even want to? <a href="http://gamecodeschool.com/c-plus-plus/using-c-references-to-make-code-faster/">Using C++ references to m</a>ake code faster.</p>
<h3>10 &#8211; Controlling game memory with C++ pointers</h3>
<p>Pointers have a bad reputation. They can appear complicated or convoluted. Add to this, the way pointers can be used in C++ code has evolved in recent years. I believe the best way to understand them is to use them in their original (old-fashioned) form. You can’t understand how an internal combustion engine works if you go straight to a supercar. So what is a pointer? <a href="http://gamecodeschool.com/c-plus-plus/controlling-game-memory-with-c-pointers/">Controlling game memory with pointers</a>.</p>
<p>Be sure to complete all the related <a href="http://gamecodeschool.com/sfml-projects/">SFML game projects</a>.</p>
<h3>11 &#8211; Organizing game data with C++ Maps</h3>
<p>Maps are a convenient, organized, fast and intuitive way to organize key-value-pairs. That, is, pairs of data which go together that map to one another. Read about <a href="https://gamecodeschool.com/c-plus-plus/organizing-your-game-data-with-c-maps/">Maps in C++</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>
