<?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; SFML</title>
	<atom:link href="https://gamecodeschool.com/category/sfml/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>Building a simple game engine in C++</title>
		<link>https://gamecodeschool.com/sfml/building-a-simple-game-engine-in-c-plus-plus/</link>
		<comments>https://gamecodeschool.com/sfml/building-a-simple-game-engine-in-c-plus-plus/#comments</comments>
		<pubDate>Thu, 15 Sep 2016 09:42:02 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=14536</guid>
		<description><![CDATA[In this tutorial project, we will build a fully working and functional but simple C++ game engine. All that the game engine will do is allow the player to control one object moving left and right on a background, however, once you have completed the project you will be able to use the example game [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this tutorial project, we will build a fully working and functional but simple C++ game engine. All that the game engine will do is allow the player to control one object moving left and right on a background, however, once you have completed the project you will be able to use the example game object class, <pre class="crayon-plain-tag">Bob</pre> as a blueprint for adding as many other objects as you like. The tutorial won&#8217;t cover collision detection as that was discussed in the <a href="http://gamecodeschool.com/sfml/coding-a-simple-pong-game-with-sfml/">pong game</a> and once you have read that tutorial it would be trivial to add this feature into the update function that we will be writing. Note that this really is a &#8220;simple&#8221; engine and future tutorials will expand and evolve this code to add more features. The long-term shortcomings of the engine are discussed at the end. What you do get with this simple game engine is a level of abstraction that will allow you to build a relatively complex game, without ending up in a tangled mess of code.<br />
[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-1 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this project</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to complete 90 minutes</p>
<h4>New concepts</h4>
<ul>
<li>Building a simple reusable game engine in C++</li>
<li>Using textures with Sprites</li>
<li>Managing lengthy code with abstraction</li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a title="Making games: Where do I start?" href="http://gamecodeschool.com/blog/making-games-where-do-i-start/">Know where you want to start</a></li>
<li>Find out <a href="http://gamecodeschool.com/blog/what-is-sfml-and-should-i-use-it/">what is SFML</a>.</li>
<li><a href="http://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/">C++ game coding level 1 introduction</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/game-variables-c-plus-plus/">C++ Game variables tutorial</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/manipulating-the-value-of-our-games-variables/">Manipulating the value of game variables</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/condition-checking-in-a-game/">Condition checking in a game</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/structuring-and-branching-the-code/">Structuring and branching code</a></li>
<li><a href="http://gamecodeschool.com/android/loops-demo/">Loops in C++ game code</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/organizing-game-code-with-functions/">Organizing game code with functions</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/introduction-to-oop-for-c_plus_plus-games/">Introduction to OOP for C++ games</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Assumed previous experience</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>Basic proficiency with Windows</li>
<li><a href="http://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Setup SFML and Visual Studio development environment</a></li>
<li><a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a></li>
<li><a href="http://gamecodeschool.com/sfml/game-variables-demo-moving-circles/">SFML variables demo: Moving circles</a></li>
<li><a href="http://gamecodeschool.com/sfml/conditions-and-branching-demo-bouncing-shapes/">SFML conditions and branching demo: Bouncing shapes</a></li>
<li><a href="http://gamecodeschool.com/sfml/coding-a-simple-pong-game-with-sfml/">Building a simple Pong clone</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<h2>Creating the simple game engine project in Visual Studio</h2>
<p>To get started we need to create a new project in Visual Studio, complete with all the required properties to work with SFML. If you haven&#8217;t completed the <a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a> you will need to do that first in order for the next steps to work.</p>
<p>These next steps set up our new SFML C++  game engine project.</p>
<ol>
<li>Open Visual Studio and from the main menu choose <span style="color: #008000;">File | New Project</span>. In the left-hand menu click <span style="color: #008000;">C++</span>. Select the <span style="color: #008000;">HelloSFML</span> template and name your project <span style="color: #008000;">Simple Game Engine</span>.</li>
<li>Now click <span style="color: #008000;">OK</span>.</li>
<li>Right-click the <span style="color: #008000;">HelloSFML.cpp</span> file under the <span style="color: #008000;">Source Files</span> heading from the right-hand <span style="color: #008000;">Solution Explorer</span> window. Choose <span style="color: #008000;">Rename</span> and rename the file to <span style="color: #008000;">Main</span>. This is a more appropriate name as this will indeed be the  source file containing the main function.</li>
<li>Open <span style="color: #008000;">Main.cpp</span> by double-clicking it. Now delete all of its contents as we will be starting with an empty file.</li>
<li>Copy &amp; paste the SFML .dll files from the <span style="color: #008000;">YOUR_DRIVE:\SFML\bin</span> to <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\Simple Game Engine\Simple Game Engine</span>. Obviously, if you configured your development environment slightly differently then your folder names will vary.</li>
</ol>
<p>Now we can get coding. All the code is on the page and all the assets you need are made available from this page, but please take a look at the bonus download offer.</p>
<p>[sociallocker id=&#8221;14566&#8243;]</p>
<p style="text-align: center;">Thanks for the love! Here is the link to the <a href="http://gamecodeschool.com/wp-content/uploads/2016/09/Simple-Game-Engine-C-Bonus-Download.zip">simple-game-engine-c-bonus-download</a></p>
<div id="attachment_14519" style="width: 210px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2016/09/Simple-Game-Engine-C-Bonus-Download.zip"><img class="wp-image-14519 size-full" src="http://gamecodeschool.com/wp-content/uploads/2015/05/bonus-download.jpg" alt="Click to download the  bonus!" width="200" height="167" /></a><p class="wp-caption-text">Click to download the bonus!</p></div>
<p>&nbsp;</p>
<p>[/sociallocker]</p>
<p>Also, note that all the bonus downloads for this and every future tutorial is available on an exclusive download area for my Patreon subscribers.</p>
<p><a href="https://www.patreon.com/Gamecodeschool"><img class="aligncenter size-full wp-image-14549" src="http://gamecodeschool.com/wp-content/uploads/2016/09/patreon-medium-banner.jpg" alt="patreon-medium-banner" width="328" height="145" /></a></p>
<h2></h2>
<h2>Planning the simple game engine</h2>
<p>One of the problems that we had in the Pong game was how long and unwieldy the code was. If you consider that Pong is perhaps the simplest game it is possible to make then we need to think about improving the structure of our code. <a href="http://gamecodeschool.com/c-plus-plus/introduction-to-oop-for-c_plus_plus-games/">Object oriented programming</a> in C++ allows us to break our code up into logical and manageable chunks called classes.</p>
<p>We will make a big improvement to the manageability of the code in this project compared to the Pong game with the introduction of an <pre class="crayon-plain-tag">Engine</pre> class. The Engine class will have three<br />
private functions. They are <pre class="crayon-plain-tag">input</pre>, <pre class="crayon-plain-tag">update</pre>, and <pre class="crayon-plain-tag">draw</pre>. This should sound very familiar if you have done the Pong project. Each of these functions will hold a part of the code that was previously all in the <pre class="crayon-plain-tag">main</pre> function. Each of these functions will be in a code file of its own, <pre class="crayon-plain-tag">Input.cpp</pre>, <pre class="crayon-plain-tag">Update.cpp</pre>, and <pre class="crayon-plain-tag">Draw.cpp</pre> respectively.</p>
<p>There will also be one public function in the <pre class="crayon-plain-tag">Engine</pre> class, which can be called with an instance of <pre class="crayon-plain-tag">Engine</pre> which will be declared in <pre class="crayon-plain-tag">Main.cpp</pre>. This function is appropriately called <pre class="crayon-plain-tag">start</pre> and will be responsible for calling <pre class="crayon-plain-tag">input</pre>, <pre class="crayon-plain-tag">update</pre>, and <pre class="crayon-plain-tag">draw</pre>, once for each frame of the game:</p>
<p>In addition, because we have abstracted the game loop to the <pre class="crayon-plain-tag">Engine</pre> class, we can also move virtually all of the variables from main and make them members of <pre class="crayon-plain-tag">Engine</pre>. All we need to do to get our game engine revving is create an instance of <pre class="crayon-plain-tag">Engine</pre> and call its <pre class="crayon-plain-tag">start</pre> function from <pre class="crayon-plain-tag">main</pre>. Here is what the super-simple <pre class="crayon-plain-tag">main</pre> function will look like when we are done. Don&#8217;t code it just yet, though.</p>
<pre class="brush: cpp; title: ; notranslate">
int main()
{
	// Declare an instance of Engine
	Engine engine;
	// Start the engine
	engine.start();
	// Quit the game
	return 0;
}
</pre>
<p>If you want to go way beyond this tutorial, please take a look at these three related books.</p>
<p>[widgets_on_pages id=&#8221;bcgp_cfgp_gpp&#8221;]</p>
<p>Now we can build the classes that we discussed.</p>
<h2>Coding the Bob class</h2>
<p><pre class="crayon-plain-tag">Bob</pre> is a simple class that will represent the player&#8217;s controllable character. It can only move left and right but when you see the code you will see that it would be trivial to extend this functionality. More significant, however, is that the <pre class="crayon-plain-tag">Bob</pre> class can be easily copied and modified to become just about any type of game object you like. Simply apply the appropriate texture in the constructor, behaviour in the <pre class="crayon-plain-tag">update</pre> function then declare, update and draw them in exactly the same way that we will soon see. If you want dozens, hundreds, or more of your new game object then just declare an entire <a href="http://gamecodeschool.com/c-plus-plus/handling-game-data-with-c-arrays/">array</a> of them.</p>
<h3>Bob.h</h3>
<p>First, let&#8217;s code the header file of the <pre class="crayon-plain-tag">Bob</pre> class.</p>
<p>Right-click <span style="color: #008000;">Header Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add</span> | <span style="color: #008000;">New Item….</span> In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">Header File (.h)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Bob.h</span>. Finally, click the <span style="color: #008000;">Add</span> button. We are now ready to code the header file for the Bob class.</p>
<pre class="brush: cpp; title: ; notranslate">
#pragma once
#include &lt;SFML/Graphics.hpp&gt;

using namespace sf;

class Bob
{
	// All the private variables can only be accessed internally
private:

	// Where is Bob
	Vector2f m_Position;

	// Of course we will need a sprite
	Sprite m_Sprite;

	// And a texture
	// Bob has been working out and he is now a bit more muscular than before
	// Furthermore, he fancies himself in lumberjack attire
	Texture m_Texture;

	// Which direction(s) is the player currently moving in
	bool m_LeftPressed;
	bool m_RightPressed;

	// Bob's speed in pixels per second
	float m_Speed;

	// Public functions
public:

	// We will set Bob up in the constructor
	Bob();

	// Send a copy of the sprite to main
	Sprite getSprite();

	// Move Bob in a specific direction
	void moveLeft();

	void moveRight();

	// Stop Bob moving in a specific direction
	void stopLeft();

	void stopRight();

	// We will call this function once every frame
	void update(float elapsedTime);

};
</pre>
<p>In the previous code, we declare objects of type <pre class="crayon-plain-tag">Texture</pre> and <pre class="crayon-plain-tag">Sprite</pre>. You will see in the next code how we associate these with each other so that whenever we do anything with the <pre class="crayon-plain-tag">Sprite</pre> it will be adorned by this rather handsome Bob character. Notice also the is a <pre class="crayon-plain-tag">Vector2f</pre> called <pre class="crayon-plain-tag">m_Position</pre> which can be manipulated and will be used to set Bob&#8217;s current position on the screen.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2016/09/bob.png"><img class="aligncenter size-full wp-image-14573" src="http://gamecodeschool.com/wp-content/uploads/2016/09/bob.png" alt="bob" width="150" height="192" /></a></p>
<p>Right-click and select <span style="color: #008000;">Save Image as&#8230;</span> to download the previous image.</p>
<p>There are also two Boolean variables which will be set and unset in order to communicate with the <pre class="crayon-plain-tag">update</pre> function which way Bob should be moving, if at all. There is also an <pre class="crayon-plain-tag">int</pre> called <pre class="crayon-plain-tag">m_Speed</pre> which will be assigned a value which determines how fast Bob will move.</p>
<p>The <pre class="crayon-plain-tag">public</pre> section of the class has a <pre class="crayon-plain-tag">getSprite</pre> function to return a copy of the <pre class="crayon-plain-tag">Sprite</pre> object to the <pre class="crayon-plain-tag">draw</pre> function where it is required in order to draw Bob to the screen. There are four setter functions <pre class="crayon-plain-tag">moveLeft</pre>, <pre class="crayon-plain-tag">moveRight</pre>, <pre class="crayon-plain-tag">stopLeft</pre>, and <pre class="crayon-plain-tag">stopRight</pre>. These functions will be called from the <pre class="crayon-plain-tag">input</pre> function and are used to set the values of the two Booleans that control the movement.</p>
<p>The final function in the <pre class="crayon-plain-tag">Bob.h</pre> file is the <pre class="crayon-plain-tag">update</pre> function. You can see it takes a <pre class="crayon-plain-tag">float</pre> variable. This function will be called each and every frame from the update function of the <pre class="crayon-plain-tag">Engine</pre> class and will update Bob&#8217;s position by the right amount in the appropriate direction each frame.</p>
<h3>Bob.cpp</h3>
<p>Now we can code the definitions for all the functions we have just seen.</p>
<p>Right-click<span style="color: #008000;"> Source Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add | New Item…</span>. In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">C++ File (.cpp)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Bob.cpp</span>. Finally, click the <span style="color: #008000;">Add</span> button. We are now ready to code the .cpp file for the Bob class.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;bob.h&quot;

Bob::Bob()
{
	// How fast does Bob move?
	m_Speed = 400;

	// Associate a texture with the sprite
	m_Texture.loadFromFile(&quot;bob.png&quot;);
	m_Sprite.setTexture(m_Texture);		

	// Set the Bob's starting position
	m_Position.x = 500;
	m_Position.y = 800;

}

// Make the private spite available to the draw() function
Sprite Bob::getSprite()
{
	return m_Sprite;
}

void Bob::moveLeft()
{
	m_LeftPressed = true;
}

void Bob::moveRight()
{
	m_RightPressed = true;
}

void Bob::stopLeft()
{
	m_LeftPressed = false;
}

void Bob::stopRight()
{
	m_RightPressed = false;
}

// Move Bob based on the input this frame,
// the time elapsed, and the speed
void Bob::update(float elapsedTime)
{
	if (m_RightPressed)
	{
		m_Position.x += m_Speed * elapsedTime;
	}

	if (m_LeftPressed)
	{
		m_Position.x -= m_Speed * elapsedTime;
	}

	// Now move the sprite to its new position
	m_Sprite.setPosition(m_Position);	

}
</pre>
<p>In the constructor function, <pre class="crayon-plain-tag">Bob</pre>, above we set <pre class="crayon-plain-tag">m_Speed</pre> to <pre class="crayon-plain-tag">400</pre> which means Bob would cross a 1920 pixel screen width in around 5 seconds. We load the <pre class="crayon-plain-tag">bob.png</pre> image into the <pre class="crayon-plain-tag">Texture</pre> object and we associate it with the <pre class="crayon-plain-tag">Sprite</pre> object. We also set the starting horizontal and vertical positions for Bob by initializing <pre class="crayon-plain-tag">m_Position.x</pre> and <pre class="crayon-plain-tag">m_Position.y</pre>. It is worth noting that depending on the resolution of your monitor you might want to adjust these values.</p>
<p>The <pre class="crayon-plain-tag">getSprite</pre> function as expected returns a copy of <pre class="crayon-plain-tag">m_Sprite</pre>. The four movement related functions play with our two Booleans. The <pre class="crayon-plain-tag">...Pressed</pre> functions set the appropriate Boolean to <pre class="crayon-plain-tag">true</pre> and the <pre class="crayon-plain-tag">stop...</pre> functions set the same to <pre class="crayon-plain-tag">false</pre>. We can now see how all these ties together in the <pre class="crayon-plain-tag">update</pre> function.</p>
<p>The <pre class="crayon-plain-tag">update</pre> function starts with two <pre class="crayon-plain-tag">if</pre> statements. The first checking whether <pre class="crayon-plain-tag">m_RightPressed</pre> is <pre class="crayon-plain-tag">true</pre> and the second detecting whether <pre class="crayon-plain-tag">m_LeftPressed</pre> is <pre class="crayon-plain-tag">true</pre>. Inside each of the <pre class="crayon-plain-tag">if</pre> blocks <pre class="crayon-plain-tag">m_Speed</pre> multiplied by <pre class="crayon-plain-tag">elapsedTime</pre> is added or subtracted from <pre class="crayon-plain-tag">m_Position.x</pre>. The <pre class="crayon-plain-tag">elapsedTime</pre> variable is calculated and passed in by the <pre class="crayon-plain-tag">start</pre> function of the <pre class="crayon-plain-tag">Engine</pre> class. We will code that next.</p>
<p>As a final step for this class add <pre class="crayon-plain-tag">bob.png</pre> to the <pre class="crayon-plain-tag">Simple Game Engine/Simple Game Engine folder</pre>.</p>
<h2>Coding the Engine class</h2>
<p>The Engine class is what controls everything else. Once it is started in the main function which runs when the app runs it will hold control right up until the player quits the game. Let&#8217;s code it now, it is quite straightforward.</p>
<h3>Engine.h</h3>
<p>Right-click <span style="color: #008000;">Header Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add</span> | <span style="color: #008000;">New Item…</span>. In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">Header File (.h)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Engine.h</span>. Finally, click the <span style="color: #008000;">Add</span> button. We are now ready to code the header file for the Engine class. Add the following code.</p>
<pre class="brush: cpp; title: ; notranslate">
#pragma once
#include &lt;SFML/Graphics.hpp&gt;
#include &quot;Bob.h&quot;;

using namespace sf;

class Engine
{
private:

	// A regular RenderWindow
	RenderWindow m_Window;	

	// Declare a sprite and a Texture for the background
	Sprite m_BackgroundSprite;
	Texture m_BackgroundTexture;

	// An instance of Bob
	Bob m_Bob;

	// Private functions for internal use only
	void input();
	void update(float dtAsSeconds);
	void draw();

public:
	// The Engine constructor
	Engine();

	// start will call all the private functions
	void start();

};
</pre>
<p>Let&#8217;s talk about the variables first. There is an SFML <pre class="crayon-plain-tag">RenderWIndow</pre> which is what we use to display everything. There is a <pre class="crayon-plain-tag">Sprite</pre> and a <pre class="crayon-plain-tag">Texture</pre> which will be used to draw a pretty background image. We declare an instance of the <pre class="crayon-plain-tag">Bob</pre> class that we just finished coding a moment ago. There is also the three <pre class="crayon-plain-tag">private</pre> functions, <pre class="crayon-plain-tag">input</pre>, <pre class="crayon-plain-tag">update</pre>, and <pre class="crayon-plain-tag">draw</pre>. They are <pre class="crayon-plain-tag">private</pre> because we don&#8217;t need or want to call them from outside of the <pre class="crayon-plain-tag">Engine</pre> class.</p>
<p>Next, the code declares two <pre class="crayon-plain-tag">public</pre> functions. The constructor called <pre class="crayon-plain-tag">Engine</pre> will set the instance of the class up ready go and the <pre class="crayon-plain-tag">start</pre> function is the function that will continuously call the <pre class="crayon-plain-tag">input</pre>, <pre class="crayon-plain-tag">update</pre> and <pre class="crayon-plain-tag">draw</pre> functions, in that order, every frame.</p>
<h3>Engine.cpp</h3>
<p>In the <pre class="crayon-plain-tag">Engine.cpp</pre> file, we will put the constructor (<pre class="crayon-plain-tag">Engine</pre>) and the public <pre class="crayon-plain-tag">start</pre> function. All the rest of the functions will go in their own <pre class="crayon-plain-tag">.cpp</pre> file, with a name that makes it clear what function goes where. This will not be a problem for the compiler as long as we add the appropriate include directive (<pre class="crayon-plain-tag">#include "Engine.h"</pre>) at the top of all the files that contain function definitions from the <pre class="crayon-plain-tag">Engine</pre> class.</p>
<p>Let&#8217;s get started by coding <pre class="crayon-plain-tag">Engine</pre> and <pre class="crayon-plain-tag">start</pre> in <pre class="crayon-plain-tag">Engine.cpp</pre>. Right-click <span style="color: #008000;">Source Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add</span> | <span style="color: #008000;">New Item…</span>. In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">C++ File (.cpp)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Engine.cpp</span>. Finally, click the <span style="color: #008000;">Add</span> button. We are now ready to code the .cpp file for the Engine class.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Engine.h&quot;

Engine::Engine()
{
	// Get the screen resolution and create an SFML window and View
	Vector2f resolution;
	resolution.x = VideoMode::getDesktopMode().width;
	resolution.y = VideoMode::getDesktopMode().height;

	m_Window.create(VideoMode(resolution.x, resolution.y),
		&quot;Simple Game Engine&quot;,
		Style::Fullscreen);

	// Load the background into the texture
	// Be sure to scale this image to your screen size
	m_BackgroundTexture.loadFromFile(&quot;background.jpg&quot;);

	// Associate the sprite with the texture
	m_BackgroundSprite.setTexture(m_BackgroundTexture);

}

void Engine::start()
{
	// Timing
	Clock clock;

	while (m_Window.isOpen())
	{
		// Restart the clock and save the elapsed time into dt
		Time dt = clock.restart();

		// Make a fraction from the delta time
		float dtAsSeconds = dt.asSeconds();

		input();
		update(dtAsSeconds);
		draw();
	}
}
</pre>
<p>The constructor function gets the screen resolution and then opens a fullscreen window with <pre class="crayon-plain-tag">m_Window.create</pre>. Finally, in the constructor, we load the image into the <pre class="crayon-plain-tag">Texture</pre> and associate it with the <pre class="crayon-plain-tag">Sprite</pre>.</p>
<p>You need to add an image for the background. Here is a great place to get lots of images with varying sizes.</p>
<p><a href="http://www.spyderonlines.com/wallpapers/game-background-images.html">http://www.spyderonlines.com/wallpapers/game-background-images.html</a></p>
<p>Use an image editor like GIMP or Photoshop to scale the background to the same resolution as your screen. Rename the image as <pre class="crayon-plain-tag">background.jpg</pre>. Add the <pre class="crayon-plain-tag">backgroung.jpg</pre> image to the <pre class="crayon-plain-tag">Simple Game Engine/Simple Game Engine</pre> folder.</p>
<p>The other function in the code above is the <pre class="crayon-plain-tag">start</pre> function. This function contains just a continuous <pre class="crayon-plain-tag">while</pre> loop that will only break when the window (<pre class="crayon-plain-tag">m_Window</pre>) is closed. We will give the player the ability to do this in the <pre class="crayon-plain-tag">input</pre> function soon.</p>
<p>The <pre class="crayon-plain-tag">start</pre> function then calculates how long the previous frame took, stores the answer as a <pre class="crayon-plain-tag">float</pre> called <pre class="crayon-plain-tag">dtAsSeconds</pre> then calls <pre class="crayon-plain-tag">input</pre>, <pre class="crayon-plain-tag">update</pre> and <pre class="crayon-plain-tag">draw</pre>. Notice that <pre class="crayon-plain-tag">dtAsSeconds</pre> get passed to <pre class="crayon-plain-tag">update</pre> that will require the value because it will be calling the <pre class="crayon-plain-tag">update</pre> function of the <pre class="crayon-plain-tag">Bob</pre> instance.</p>
<p>I hope you agree that is extremely simple. It is arguably easier than have to handle the sprawl of code that we did in the Pong game.</p>
<h2>Coding the three stages of the game loop</h2>
<p>[widgets_on_pages id=&#8221;udemy_advert_cpp_2&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
The next three functions will be coded in their own individual files but don&#8217;t forget that they are part of the <pre class="crayon-plain-tag">Engine</pre> class and were declared in the <pre class="crayon-plain-tag">Engine.h</pre> file. At the top of each file, we will add the directive <pre class="crayon-plain-tag">#include "Engine.h"</pre> so that Visual Studio knows what we are doing.</p>
<h3>Handling player input</h3>
<p>The first of these functions we will code is <pre class="crayon-plain-tag">input</pre>.</p>
<p>Right-click <span style="color: #008000;">Source Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add</span> | <span style="color: #008000;">New Item…</span>. In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">C++ File (.cpp)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Input.cpp</span>. Finally, click the <span style="color: #008000;">Add</span> button. Here is the code for Input.cpp.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Engine.h&quot;

void Engine::input()
{
	// Handle the player quitting
	if (Keyboard::isKeyPressed(Keyboard::Escape))
	{
		m_Window.close();
	}

	// Handle the player moving
	if (Keyboard::isKeyPressed(Keyboard::A))
	{
		m_Bob.moveLeft();
	}
	else
	{
		m_Bob.stopLeft();
	}

	if (Keyboard::isKeyPressed(Keyboard::D))
	{
		m_Bob.moveRight();
	}
	else
	{
		m_Bob.stopRight();
	}						

}
</pre>
<p>In the <pre class="crayon-plain-tag">input</pre> function, we use the SFML <pre class="crayon-plain-tag">Keyboard::isKeyPressed</pre> constants to verify which keyboard keys are currently pressed. If the Escape key is pressed <pre class="crayon-plain-tag">m_Window</pre> is closed. This has the effect of breaking out of the <pre class="crayon-plain-tag">while</pre> loop in the <pre class="crayon-plain-tag">start</pre> function. This causes execution to go back to the <pre class="crayon-plain-tag">main</pre> function and the game will close.</p>
<p>If the A or D keys are pressed we call the appropriate <pre class="crayon-plain-tag">move...</pre> function on our <pre class="crayon-plain-tag">Bob</pre> instance. Notice that when the A or D keys are not pressed the two <pre class="crayon-plain-tag">else</pre> clauses call the corresponding <pre class="crayon-plain-tag">stop...</pre> functions. This is the final piece of the puzzle that enables the player to move Bob left and right.</p>
<h3>Updating the game objects</h3>
<p>Next, we come to the super-simple <pre class="crayon-plain-tag">update</pre> function. Any new objects you create should have their own <pre class="crayon-plain-tag">update</pre> functions called from here. You should also add collision detection to the end of this function.</p>
<p>Right-click <span style="color: #008000;">Source Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add</span> | <span style="color: #008000;">New Item…</span>. In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">C++ File (.cpp)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Update.cpp</span>. Finally, click the <span style="color: #008000;">Add</span> button. Here is the code for Update.cpp.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Engine.h&quot;

using namespace sf;

void Engine::update(float dtAsSeconds)
{
	m_Bob.update(dtAsSeconds);
}
</pre>
<p>As we only have one game object we call <pre class="crayon-plain-tag">m_Bob.update</pre> and pass in <pre class="crayon-plain-tag">dtAsSeconds</pre> and then we are finished with this function.</p>
<h3>Drawing the scene</h3>
<p>This is the final function of the <pre class="crayon-plain-tag">Engine</pre> class.</p>
<p>Right-click <span style="color: #008000;">Source Files</span> in the <span style="color: #008000;">Solution Explorer</span> and select <span style="color: #008000;">Add</span> | <span style="color: #008000;">New Item…</span>. In the <span style="color: #008000;">Add New Item</span> window, highlight (by left-clicking) <span style="color: #008000;">C++ File (.cpp)</span> and then in the <span style="color: #008000;">Name</span> field, type <span style="color: #008000;">Draw.cpp</span>. Finally, click the <span style="color: #008000;">Add</span> button. Here is the code for Draw.cpp.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Engine.h&quot;

void Engine::draw()
{
	// Rub out the last frame
	m_Window.clear(Color::White);

	// Draw the background
	m_Window.draw(m_BackgroundSprite);
	m_Window.draw(m_Bob.getSprite());

	// Show everything we have just drawn
	m_Window.display();
}
</pre>
<p>In the <pre class="crayon-plain-tag">draw</pre> function, there is nothing that we didn&#8217;t see in the Pong game. First, we clear the screen with the <pre class="crayon-plain-tag">clear</pre> function. Next, we draw the background followed by Bob. The things to note here are that we must draw the background first so Bob is drawn on top and that when we draw Bob we call the <pre class="crayon-plain-tag">getSprite</pre> function which gets a copy of the <pre class="crayon-plain-tag">Sprite</pre> in the <pre class="crayon-plain-tag">Bob</pre> class.</p>
<h2>Getting the engine started with Main</h2>
<p>This is the shortest <pre class="crayon-plain-tag">main</pre> function out of all the C++ tutorials on this site.</p>
<p>Add the code we have already glimpsed at to <pre class="crayon-plain-tag">Main.cpp</pre>. Here it is again in its entirety.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Engine.h&quot;

int main()
{
	// Declare an instance of Engine
	Engine engine;

	// Start the engine
	engine.start();

	// Quit in the usual way when the engine is stopped
	return 0;
}
</pre>
<p>First, we declare an instance of <pre class="crayon-plain-tag">Engine</pre>, call the <pre class="crayon-plain-tag">start</pre> function and execution will move to the <pre class="crayon-plain-tag">Engine</pre> class until the player quits by pressing the Escape key.</p>
<p>You can now run the game and move Bob left and right with the A and D keyboard keys.</p>
<div id="attachment_14557" style="width: 489px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2016/09/simple-c-plus-plus-game-engine-move-left-and-right.jpg"><img class="size-full wp-image-14557" src="http://gamecodeschool.com/wp-content/uploads/2016/09/simple-c-plus-plus-game-engine-move-left-and-right.jpg" alt="Use the A and S keys to move" width="479" height="88" /></a><p class="wp-caption-text">Use the A and D keys to move</p></div>
<h2>Conclusion, flaws &amp; what next?</h2>
<p>When you added the background and the player we had to adjust the code to suit your specific resolution. This is obviously not suitable for a game you want to release on Steam. It is quite easy to fix this flaw using the SFML <pre class="crayon-plain-tag">View</pre> class. I didn&#8217;t add this feature because at some point I had to stop adding features. The <pre class="crayon-plain-tag">View</pre> class uses OpenGL to make independent drawing layers and can be used to make some really cool effects like split-screen gameplay, mini maps, and levels that can rotate and zoom. I will publish a whole working game that uses these features soon.</p>
<p>Another obvious flaw that you probably spotted was that the game engine doesn&#8217;t handle for different game states like paused, home screen and playing. You can quickly cater for this by creating some Booleans to represent each state. Perhaps <pre class="crayon-plain-tag">isPlaying</pre>, <pre class="crayon-plain-tag">isPaused</pre> etc. This isn&#8217;t the best way of doing it but as I said before I had to draw the line at the features to include in what should be a simple tutorial. We will see a neater and more efficient way to handle states in a forthcoming full-game project, most likely a platformer.</p>
<p>In addition, any game you are going to release to the world will have more features like sound, music, artificial intelligence, saving of high scores and more besides. Most of these features can be bolted onto this engine. It is true, unfortunately, that eventually you will end up with code sprawl again but the purpose of the tutorial is meant to be instructional as well as practical and when we dive into something more complicated this engine should serve as good preparation and starting point.</p>
<p>I hope you had some fun with this simple C++ game engine. Please ask questions and leave comments if you would like to.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/sfml/building-a-simple-game-engine-in-c-plus-plus/feed/</wfw:commentRss>
		<slash:comments>51</slash:comments>
		</item>
		<item>
		<title>Coding a simple Pong game with SFML</title>
		<link>https://gamecodeschool.com/sfml/coding-a-simple-pong-game-with-sfml/</link>
		<comments>https://gamecodeschool.com/sfml/coding-a-simple-pong-game-with-sfml/#comments</comments>
		<pubDate>Thu, 10 Dec 2015 18:51:27 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=12780</guid>
		<description><![CDATA[In this first playable game project we will build a very simple Pong clone. If you don&#8217;t know what Pong is then you are much younger than me and you should take a look at its appearance and history before continuing. We will use everything we learnt about C++ Functions and OOP to create a [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this first playable game project we will build a very simple Pong clone. If you don&#8217;t know what Pong is then you are much younger than me and you should take a look at its appearance and history before continuing. We will use everything we learnt about C++ Functions and OOP to create a class for each of the objects of the game (a bat and a ball) as well as functions within these classes to make our bat and ball behave as we expect.[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-2 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this project</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to complete 30 minutes</p>
<h4>New concepts</h4>
<ul>
<li>Separating the class definition from the declaration</li>
<li>Getter and setter functions</li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a title="Making games: Where do I start?" href="http://gamecodeschool.com/blog/making-games-where-do-i-start/">Know where you want to start</a></li>
<li>Find out <a href="http://gamecodeschool.com/blog/what-is-sfml-and-should-i-use-it/">what is SFML</a>.</li>
<li><a href="http://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/">C++ game coding level 1 introduction</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/game-variables-c-plus-plus/">C++ Game variables tutorial</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/manipulating-the-value-of-our-games-variables/">Manipulating the value of game variables</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/condition-checking-in-a-game/">Condition checking in a game</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/structuring-and-branching-the-code/">Structuring and branching code</a></li>
<li><a href="http://gamecodeschool.com/android/loops-demo/">Loops in C++ game code</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/organizing-game-code-with-functions/">Organizing game code with functions</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/introduction-to-oop-for-c_plus_plus-games/">Introduction to OOP for C++ games</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Assumed previous experience</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>Basic proficiency with Windows</li>
<li><a href="http://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Setup SFML and Visual Studio development environment</a></li>
<li><a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a></li>
<li><a href="http://gamecodeschool.com/sfml/game-variables-demo-moving-circles/">SFML variables demo: Moving circles</a></li>
<li><a href="http://gamecodeschool.com/sfml/conditions-and-branching-demo-bouncing-shapes/">SFML conditions and branching demo: Bouncing shapes</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>To get started we need to create a new project, complete with all the required properties to work with SFML. If you haven&#8217;t completed the <a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a> you will need to do that first. In that project, we created a Visual Studio project <strong>template,</strong> so that starting a new SFML project is now a two-minute job instead of a half an hour long chore.</p>
<p>The next steps set up our new SFML C++ project.</p>
<ol>
<li>Open Visual Studio and from the main menu choose <span style="color: #008000;">File | New Project</span>. In the left-hand menu click <span style="color: #008000;">C++</span>. Select the <span style="color: #008000;">HelloSFML</span> template and name your project <span style="color: #008000;">Pong</span>.</li>
<li>Now click <span style="color: #008000;">OK</span>.</li>
<li>Right-click the <span style="color: #008000;">HelloSFML.cpp</span> file under the <span style="color: #008000;">Source Files</span> heading from the right-hand <span style="color: #008000;">Solution Explorer</span> window. Choose <span style="color: #008000;">Rename</span> and rename the file to <span style="color: #008000;">Main</span>. This is a more appropriate name as this will indeed be our &#8220;main&#8221; source file.</li>
<li>Open <span style="color: #008000;">Main.cpp</span> by double-clicking it. Now delete all of its contents as we will be starting fresh and discussing all of the code as well.</li>
<li>Copy &amp; paste the SFML .dll files in the <span style="color: #008000;">YOUR_DRIVE:\SFML\bin</span> to <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\Pong\Pong</span>.</li>
</ol>
<p>Now we can get coding.</p>
<p>[widgets_on_pages id=&#8221;bcgp_cfgp_gpp&#8221;]</p>
<h2>Building the Bat class</h2>
<p>In the tutorial on <a href="http://gamecodeschool.com/c-plus-plus/introduction-to-oop-for-c_plus_plus-games/">coding a C++ class</a>, we mentioned that we should separate the declaration from the definition. As we create the <pre class="crayon-plain-tag">Bat</pre> class we will see exactly how to do this. Perhaps unsurprisingly the <pre class="crayon-plain-tag">Bat</pre> class will represent the player&#8217;s bat.</p>
<p>Right-click on <span style="color: #008000;">Header Files</span> in the <span style="color: #008000;">Solution Explorer</span> window. And select <span style="color: #008000;">ADD | New Item</span>. This step is shown in the next image.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/12/create-new-header-file.png"><img class=" size-full wp-image-12915 aligncenter" src="http://gamecodeschool.com/wp-content/uploads/2015/12/create-new-header-file.png" alt="create-new-header-file" width="906" height="501" /></a></p>
<p>&nbsp;</p>
<p>Now select <span style="color: #008000;">C++ Header File (.h)</span> (1) and enter <span style="color: #008000;">bat.h</span> in the <span style="color: #008000;">Name:</span> field (2) as shown next.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/12/create-new-header-file-part-2.png"><img class=" size-full wp-image-12916 aligncenter" src="http://gamecodeschool.com/wp-content/uploads/2015/12/create-new-header-file-part-2.png" alt="create-new-header-file-part-2" width="800" height="552" /></a></p>
<p>Click the <span style="color: #008000;">Add</span> button (3) and our new file will be created for us.</p>
<h3>Coding bat.h</h3>
<p>Now we will code the class declaration. This will look a bit different to how it did in the Introduction to OOP in C++ tutorial but when we move on to the definition which will go in a separate file (<span style="color: #008000;">Bat.cpp</span>) things will look more familiar and will make more sense.</p>
<p>Take a look at the next block of code. This will be the entire contents of our <span style="color: #008000;">bat.h</span> file. In it, we <pre class="crayon-plain-tag">#include</pre> the SFML library that we need, declare some member variables that are <pre class="crayon-plain-tag">private</pre> and then declare some functions which are <pre class="crayon-plain-tag">public</pre>.</p>
<p>We will discuss the variables and functions in more detail when we use and implement them in Bat.cpp in a minute. For now just note their names, parameters and return types. We have a <pre class="crayon-plain-tag">Vector2f</pre> called <pre class="crayon-plain-tag">position</pre> which will indeed hold the horizontal and vertical position of the player&#8217;s bat. We have an SFML <pre class="crayon-plain-tag">RectangleShape</pre> which will be the actual bat that appears on the screen and we have a <pre class="crayon-plain-tag">float</pre> called <pre class="crayon-plain-tag">batSpeed</pre> that is the number of pixels per frame that the bat can move at.</p>
<p>The functions are as follows. A function called <pre class="crayon-plain-tag">Bat</pre> which we learnt is the constructor because it has the same name as the class. Notice it takes two <pre class="crayon-plain-tag">float</pre> parameters. This is perfect for initializing the position on the screen when we first create an <pre class="crayon-plain-tag">Bat</pre> object. Next is the <pre class="crayon-plain-tag">getPosition</pre> function which returns a <pre class="crayon-plain-tag">FloatRect</pre>, the four points which define a rectangle. Then we have <pre class="crayon-plain-tag">getShape</pre> which returns a <pre class="crayon-plain-tag">RectangleShape</pre>. This will be used to return to the main game loop <pre class="crayon-plain-tag">batShape</pre>, so it can be drawn.</p>
<p>Finally, we have the <pre class="crayon-plain-tag">moveLeft</pre>, <pre class="crayon-plain-tag">moveRight</pre> and <pre class="crayon-plain-tag">update</pre> functions which take no parameters and return no values. We will see how these are useful to us very soon.</p>
<p>Add all this code we have just discussed to the bat.h file.</p>
<pre class="brush: cpp; title: ; notranslate">
#pragma once
#include &lt;SFML/Graphics.hpp&gt;

using namespace sf;

class Bat
{
private:
	Vector2f position;

	// A RectangleShape object
	RectangleShape batShape;

	float batSpeed = .3f;

public:
	Bat(float startX, float startY);

	FloatRect getPosition();

	RectangleShape getShape();

	void moveLeft();

	void moveRight();

	void update();

};
</pre>
<p>Now we can get to the real functionality of the <pre class="crayon-plain-tag">Bat</pre> class.</p>
<h3>Coding bat.cpp</h3>
<p>Let&#8217;s create the file then we can start discussing the code. Right-click the <span style="color: #008000;">Source Files</span> folder in the <span style="color: #008000;">Solution Explorer</span> window. Now select <span style="color: #008000;">C++ File (.cpp)</span> and enter <span style="color: #008000;">Bat.cpp</span> in the <span style="color: #008000;">Name:</span> field. Click the <span style="color: #008000;">Add</span> button and our new file will be created for us.</p>
<p>We will divide the code for this file into two to make discussion of it simpler. Take a look at part one of the code and explanation below.</p>
<h4>bat .cpp part one</h4>
<p>In this first part, we can see that we <pre class="crayon-plain-tag">#include</pre> bat.h. This makes all the functions and variables that were declared previously in bat.h available to us. Then we implement the constructor. Notice we use the syntax <pre class="crayon-plain-tag">Bat::Bat</pre> as the function name to make it clear we are using the <pre class="crayon-plain-tag">Bat</pre> function from the <pre class="crayon-plain-tag">Bat</pre> class.</p>
<p>This constructor receives two <pre class="crayon-plain-tag">float</pre> values, <pre class="crayon-plain-tag">startX</pre> and <pre class="crayon-plain-tag">startY</pre>. The next thing that happens is we assign these values to <pre class="crayon-plain-tag">position.x</pre> and <pre class="crayon-plain-tag">position.y</pre>. The <pre class="crayon-plain-tag">Vector2f</pre> named <pre class="crayon-plain-tag">position</pre> now holds the values that were passed in and because <pre class="crayon-plain-tag">position</pre> is a member variable, these values are accessible throughout the class. Note however that <pre class="crayon-plain-tag">position</pre> was declared as <pre class="crayon-plain-tag">private</pre> and will not accessible in our <span style="color: #008000;">Main.cpp</span> file. Not directly anyway. We will see how we resolve this issue soon.</p>
<p>Finally, in the constructor, we initialize our <pre class="crayon-plain-tag">RectangleShape</pre> called <pre class="crayon-plain-tag">batShape</pre> by setting its size and position.</p>
<p>Add the code we have just discussed to the Bat.cpp file.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Bat.h&quot;

// This the constructor and it is called when we create an object
Bat::Bat(float startX, float startY)
{
	position.x = startX;
	position.y = startY;

	batShape.setSize(sf::Vector2f(50, 5));
	batShape.setPosition(position);
}
</pre>
<p>Now for the rest of the functions.</p>
<h4>bat.cpp part two</h4>
<p>We have five more functions that we need to code. Let&#8217;s go through them one at a time. Refer to the next block of code during this discussion.</p>
<p>First, we have the <pre class="crayon-plain-tag">getPosition</pre> function. All it does is return a <pre class="crayon-plain-tag">FloatRect</pre> to the code that called it. The <pre class="crayon-plain-tag">batShape.getGlobalBounds</pre>, itself returns a <pre class="crayon-plain-tag">FloatRect</pre> that is initialized with the coordinates of the four corners of the <pre class="crayon-plain-tag">RectangleShape</pre>, <pre class="crayon-plain-tag">batShape</pre>. We will use this function in Main.cpp when we are determining whether the ball has hit the bat.</p>
<p>Next, we have <pre class="crayon-plain-tag">getShape</pre>. All this function does is pass a copy of <pre class="crayon-plain-tag">batShape</pre> to the calling code. This is necessary so we can draw the bat in Main.cpp. When we code a public function with the sole purpose of passing back private data from a class we call it a <strong>getter</strong> function.</p>
<p>Now we can look at the <pre class="crayon-plain-tag">moveLeft</pre> and <pre class="crayon-plain-tag">moveRight</pre> functions. All they do is add or subtract <pre class="crayon-plain-tag">batSpeed</pre> from <pre class="crayon-plain-tag">position.x</pre>. This means that every time we call either <pre class="crayon-plain-tag">moveLeft</pre> or <pre class="crayon-plain-tag">moveRight</pre> we will tweak the horizontal position of the player&#8217;s bat. This is just what we need.</p>
<p>The last function in the <pre class="crayon-plain-tag">Bat</pre> class is <pre class="crayon-plain-tag">update</pre>. We will call this function one per frame of the game. The <pre class="crayon-plain-tag">update</pre> function will grow in complexity as our game objects get more complicated. For now, all we need to do is set the position of <pre class="crayon-plain-tag">batShape</pre> with whatever the current values held in <pre class="crayon-plain-tag">position</pre> happen to be.</p>
<p>Add the code we have just discussed to the <span style="color: #008000;">Bat.cpp</span> file right after the previous code we added.</p>
<pre class="brush: cpp; title: ; notranslate">
FloatRect Bat::getPosition()
{
	return batShape.getGlobalBounds();
}

RectangleShape Bat::getShape()
{
	return batShape;
}

void Bat::moveLeft()
{
	position.x -= batSpeed;
}

void Bat::moveRight()
{
	position.x += batSpeed;
}

void Bat::update()
{
	batShape.setPosition(position);
}
</pre>
<p>That&#8217;s it for the <pre class="crayon-plain-tag">Bat</pre> class. What we have effectively done is this. We have a <pre class="crayon-plain-tag">RectangleShape</pre> that is initialized to a position on the screen that will be determined when we create a <pre class="crayon-plain-tag">Bat</pre>. We have the ability to change the position variable to the left or right at any time we choose by calling <pre class="crayon-plain-tag">moveLeft</pre> or <pre class="crayon-plain-tag">moveRight</pre>. Once per frame the <pre class="crayon-plain-tag">RectangleShape</pre> will be moved to whatever position is contained within the <pre class="crayon-plain-tag">position</pre> variable. The code in Main.cpp also has the ability to get a copy of this RectangleShape by calling getShape, this is ideal for when we need to draw it. The code in Main.cpp can also call <pre class="crayon-plain-tag">getPosition</pre> to get the coordinates that define the four points of the bat which we will use for detecting collisions with the ball.</p>
<p>Let&#8217;s make a ball.</p>
<h2>Building the Ball class</h2>
<p>As we did for the <pre class="crayon-plain-tag">Bat</pre> class we will create a new .h file to hold the class declaration for our <pre class="crayon-plain-tag">Ball</pre> class. Right-click on <span style="color: #008000;">Header Files</span> in the <span style="color: #008000;">Solution Explorer</span> window. And select <span style="color: #008000;">ADD | New Item</span>. Now select <span style="color: #008000;">C++ Header File (.h)</span> and enter ball<span style="color: #008000;">.h</span> in the <span style="color: #008000;">Name:</span> field. Click the <span style="color: #008000;">Add</span> button and our new file will be created for us.</p>
<h3>Coding ball.h</h3>
<p>Take a look at the next block of code. We can see we have another <pre class="crayon-plain-tag">Vector2f</pre> for holding the position of the ball. We have another <pre class="crayon-plain-tag">RectangleShape</pre> which will be used to draw the ball and we have two float variables <pre class="crayon-plain-tag">xVelocity</pre> and <pre class="crayon-plain-tag">yVelocity</pre> to represent the horizontal and vertical speeds of the ball. These variables are all private so not accessible directly from outside the code of the class.</p>
<p>We also have a selection of public functions. The one named <pre class="crayon-plain-tag">Ball</pre> will obviously be our constructor. Just like our <pre class="crayon-plain-tag">Bat</pre> constructor, it takes two <pre class="crayon-plain-tag">float</pre> parameters that will set the starting position. Just as we did with the <pre class="crayon-plain-tag">Bat</pre> class we have a <pre class="crayon-plain-tag">getPosition</pre> and <pre class="crayon-plain-tag">getShape</pre> functions that return a <pre class="crayon-plain-tag">FloatRect</pre> and <pre class="crayon-plain-tag">RectangleShape</pre> respectively.</p>
<p>Now we have the <pre class="crayon-plain-tag">getXVelocity</pre> getter function which will return the value of some private data to the calling code.</p>
<p>Now we have something a little bit different that won&#8217;t make complete sense until we actually use them. When we make a quick and simple version of a game like Pong it is possible to foresee a couple of problems we will encounter:</p>
<ol>
<li>What happens when the ball hits the side of the screen?</li>
<li>What happens when the ball hits the bat or the top of the screen?</li>
<li>What happens when the ball hits the bottom of the screen?</li>
</ol>
<p>The three functions <pre class="crayon-plain-tag">reboundSides</pre>, <pre class="crayon-plain-tag">reboundBatOrTop</pre> and <pre class="crayon-plain-tag">hitBottom</pre> will deal with the above the events. We will see exactly how in a minute.</p>
<p>Finally, just like in the <pre class="crayon-plain-tag">Bat</pre> class we have a <pre class="crayon-plain-tag">update</pre> function that will be called once per frame of the game to move the ball around.</p>
<p>Add the code we have just discussed to the ball.h file.</p>
<pre class="brush: cpp; title: ; notranslate">
#pragma once
#include &lt;SFML/Graphics.hpp&gt;

using namespace sf;

class Ball
{
private:
	Vector2f position;

	// A RectangleShape object called ref
	RectangleShape ballShape;

	float xVelocity = .2f;
	float yVelocity = .2f;

public:
	Ball(float startX, float startY);

	FloatRect getPosition();

	RectangleShape getShape();

	float getXVelocity();

	void reboundSides();

	void reboundBatOrTop();

	void hitBottom();

	void update();

};
</pre>
<p>Next for the implementation.</p>
<h3>Coding ball.cpp</h3>
<p>Let&#8217;s create the file then we can start discussing the code. Right-click the <span style="color: #008000;">Source Files</span> folder in the <span style="color: #008000;">Solution Explorer</span> window. Now select <span style="color: #008000;">C++ File (.cpp)</span> and enter <span style="color: #008000;">Ball.cpp</span> in the <span style="color: #008000;">Name:</span> field. Click the <span style="color: #008000;">Add</span> button and our new file will be created for us.</p>
<p>We will divide the code for this file into two to make discussion of it simpler. Take a look at part one of the code and explanation below.</p>
<h4>ball.cpp part one</h4>
<p>Here we have the constructor and it does exactly the same thing that the <pre class="crayon-plain-tag">Bat</pre> constructor did. It captures the required starting position passed in as parameters, sets the size and position of the <pre class="crayon-plain-tag">RectangleShape</pre> that will represent the ball on the screen. Add the code below to <span style="color: #008000;">Ball.cpp</span>.</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;stdafx.h&quot;
#include &quot;Ball.h&quot;

// This the constructor and it is called when we create an object
Ball::Ball(float startX, float startY)
{
	position.x = startX;
	position.y = startY;

	ballShape.setSize(sf::Vector2f(10, 10));
	ballShape.setPosition(position);
}
</pre>
<p>The next part of the code is much longer but not complicated in any way.</p>
<h4>ball.cpp part two</h4>
<p>[widgets_on_pages id=&#8221;udemy_advert_cpp_2&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
There are seven more functions in <pre class="crayon-plain-tag">Ball</pre>. Let&#8217;s run through them one at a time.</p>
<p>First <pre class="crayon-plain-tag">getPosition</pre> is a getter which returns a <pre class="crayon-plain-tag">FloatRect</pre> to the calling code. We will soon see how we use the <pre class="crayon-plain-tag">getPosition</pre> functions from <pre class="crayon-plain-tag">Bat</pre> and <pre class="crayon-plain-tag">Ball</pre> to do collision detection in our Main.cpp code.</p>
<p>Next we have <pre class="crayon-plain-tag">getShape</pre> which does exactly the same job that the <pre class="crayon-plain-tag">getShape</pre> function in the <pre class="crayon-plain-tag">Bat</pre> class did. It returns a copy of the <pre class="crayon-plain-tag">RectangleShape</pre> to be drawn on the screen.</p>
<p>The <pre class="crayon-plain-tag">getXVelocity</pre> function is a getter for the <pre class="crayon-plain-tag">xVelocity</pre> member variable and does it&#8217;s one simple job of returning the value stored in <pre class="crayon-plain-tag">xVelocity</pre>.</p>
<p>The <pre class="crayon-plain-tag">reboundSides</pre> function will be called every time the ball hits the sides of the screen. Look at the code inside it. It simply makes <pre class="crayon-plain-tag">xVelocity</pre> the negative of whatever it currently is. So if it is positive (moving right) it will become negative and move left, and vice versa as well.</p>
<p>The <pre class="crayon-plain-tag">ReboundBatOrTop</pre> function is a tiny bit more in-depth, but not much. The first line of code in this function <pre class="crayon-plain-tag">position.y -= (yVelocity * 30)</pre> directly alters the <pre class="crayon-plain-tag">position.y</pre> value by the equivalent of 30 frames of movement and prevents the ball from getting stuck on the bat. This is a common bug when using simplistic physics like we are here. The second line of code reverses the direction of the ball.</p>
<p>The <pre class="crayon-plain-tag">hitBottom</pre> function is very straight forward as well. First, it sets the <pre class="crayon-plain-tag">position.y</pre> value to 1, effectively placing the ball back at the top of the screen and the <pre class="crayon-plain-tag">position.x</pre> to 500, placing it around about the middle horizontally.</p>
<p>Finally, for the Ball class, we have the <pre class="crayon-plain-tag">update</pre> function which is a bit more in-depth than the <pre class="crayon-plain-tag">update</pre> function in the <pre class="crayon-plain-tag">Bat</pre> class. Unlike a bat, a ball is always moving. So the first thing that happens each frame is we update <pre class="crayon-plain-tag">position.x</pre> and <pre class="crayon-plain-tag">position.y</pre> by <pre class="crayon-plain-tag">xVelocity</pre> and <pre class="crayon-plain-tag">yVelocity</pre>. Then, just as we did for the <pre class="crayon-plain-tag">Bat</pre> class, we update the position of the <pre class="crayon-plain-tag">RectangleShape</pre> with the new values stored in <pre class="crayon-plain-tag">position</pre>.</p>
<p>Add the code we have just discussed directly after the previous code, into the <span style="color: #008000;">Ball.cpp</span> file.</p>
<pre class="brush: cpp; title: ; notranslate">
FloatRect Ball::getPosition()
{
	return ballShape.getGlobalBounds();
}

RectangleShape Ball::getShape()
{
	return ballShape;
}

float Ball::getXVelocity()
{
	return xVelocity;
}

void Ball::reboundSides()
{
	xVelocity = -xVelocity;
}

void Ball::reboundBatOrTop()
{
	position.y -= (yVelocity * 30);
	yVelocity = -yVelocity;

}

void Ball::hitBottom()
{
	position.y = 1;
	position.x = 500;
}

void Ball::update()
{
	// Update the ball position variables
	position.y += yVelocity;
	position.x += xVelocity;

	// Move the ball and the bat
	ballShape.setPosition(position);
}
</pre>
<h2>Coding Main.cpp</h2>
<p>At last, we are in a position to put our new classes to work and make the Pong game come to life. Switch to the <span style="color: #008000;">Main.cpp</span> file in Visual Studio and we can discuss the first part of six parts that go to make up the code for this file.</p>
<p>We will be displaying some text known as a HUD (Heads Up Display) in this game which will show the player&#8217;s score and remaining lives. For this, we need a font.</p>
<ol>
<li>Download this free-for-personal-use font from<a href="http://www.dafont.com/theme.php?cat=302"> http://www.dafont.com/theme.php?cat=302</a>.</li>
<li>Click the <span style="color: #008000;">Download</span> button.</li>
<li>Unzip the download.</li>
<li>Add the <span style="font-family: Consolas, Monaco, monospace; line-height: 1.5; color: #008000;">DS-DIGIT.ttf</span> file into the <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\Pong\Pong</span> folder.</li>
</ol>
<h3>Main.cpp part one</h3>
<p>Add all the following <pre class="crayon-plain-tag">#include</pre> directives and the using statement to the top of the file. Notice that we are including our two new classes by the code <pre class="crayon-plain-tag">#include "bat.h"</pre> and <pre class="crayon-plain-tag">#include "ball.h"</pre>.</p>
<pre class="brush: cpp; title: ; notranslate">
// These &quot;include&quot; code from the C++ library and SFML too
#include &quot;stdafx.h&quot;
#include &quot;bat.h&quot;
#include &quot;ball.h&quot;
#include &lt;sstream&gt;
#include &lt;cstdlib&gt;
#include &lt;SFML/Graphics.hpp&gt;

// Avoid having to put sf in front of all the SFML classes and functions
using namespace sf;
</pre>
<p>Onwards to part two.</p>
<h3>Main.cpp part two</h3>
<p>In the next block of code, we create a window that is 1024 x 768 pixels in size. As this is going to be a working game we declare two <pre class="crayon-plain-tag">int</pre> variables to keep track of the player&#8217;s lives and score. Then we create an instance of a <pre class="crayon-plain-tag">Bat</pre> and a <pre class="crayon-plain-tag">Ball</pre>. We pass in appropriate starting positions for each, as required by their constructors which we coded previously.</p>
<p>All the rest of the code in part two deals with displaying the HUD (score and lives) on the screen. Some of this we have seen previously in the <a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Hello SFML project</a> but some of it is new.  We create an SFML <pre class="crayon-plain-tag">Text</pre> object called <pre class="crayon-plain-tag">text</pre> and an SFML <pre class="crayon-plain-tag">Font</pre> object called <pre class="crayon-plain-tag">font</pre>. We then load the font that we placed in the project folder a few moments ago. Next, we use <pre class="crayon-plain-tag">setFont</pre> to assign our new font to our <pre class="crayon-plain-tag">hud Text</pre> object. Next, we set the size followed by the color of the font using <pre class="crayon-plain-tag">setCharacterSize</pre> and <pre class="crayon-plain-tag">setFillColor</pre> functions.</p>
<p>Add the code we have just discussed to <span style="color: #008000;">Main.cpp</span>.</p>
<pre class="brush: cpp; title: ; notranslate">
// This is where our game starts from
int main()
{
	int windowWidth = 1024;
	int windowHeight = 768;
	// Make a window that is 1024 by 768 pixels
	// And has the title &quot;Pong&quot;
	RenderWindow window(VideoMode(windowWidth, windowHeight), &quot;Pong&quot;);

	int score = 0;
	int lives = 3;

    // create a bat
	Bat bat (windowWidth / 2, windowHeight - 20);

	// create a ball
	Ball ball(windowWidth / 2, 1);

 // Create a &quot;Text&quot; object called &quot;message&quot;. Weird but we will learn about objects soon
Text hud;

 // We need to choose a font
 Font font;
 // http://www.dafont.com/theme.php?cat=302
 font.loadFromFile(&quot;DS-DIGIT.ttf&quot;);

 // Set the font to our message
 hud.setFont(font);

 // Make it really big
 hud.setCharacterSize(75);

 // Choose a color
 hud.setFillColor(sf::Color::White);

</pre>
<p>We are ready to enter the game loop!</p>
<h3>Main.cpp part three</h3>
<p>In this third part of the <span style="color: #008000;">Main.cpp</span> code we will handle the player&#8217;s input.  There are two ways to handle player input in SFML and I encourage you to research them both further(<a href="http://www.sfml-dev.org/tutorials/2.1/window-events.php">event handling</a> and <a href="http://www.sfml-dev.org/tutorials/2.1/window-inputs.php">keyboard input</a>). Here we use both. First, in the <pre class="crayon-plain-tag">while</pre> loop  that has the condition <pre class="crayon-plain-tag">window.pollEvent(event)</pre>, we check if any messages have been sent to the operating system and subsequently passed on to SFML. We could check for lots of different types of messages here but content ourselves by checking if the window was closed. If it was we call <pre class="crayon-plain-tag">window.close</pre> and the game will quit.</p>
<p>Next, we explicitly check for the current state of some of the keys at the given moment (as opposed to in a queue). Look carefully at the various <pre class="crayon-plain-tag">if</pre> statements and the simple but important code that we call when the <pre class="crayon-plain-tag">if</pre> statement is true.</p>
<p>If <pre class="crayon-plain-tag">Keyboard::Left</pre>, <pre class="crayon-plain-tag">bat.moveLeft()</pre>. Next is if <pre class="crayon-plain-tag">Keyboard::Right</pre>, <pre class="crayon-plain-tag">bat.moveRight()</pre>. What is happening here is that once each frame we check to see if the left or right arrow (cursor) keys are currently being pressed and if they are we call the appropriate <pre class="crayon-plain-tag">moveLeft</pre> or <pre class="crayon-plain-tag">moveRight</pre> functions on our <pre class="crayon-plain-tag">bat</pre> object. This will have the effect of updating the <pre class="crayon-plain-tag">position.x</pre> variable that we coded previously.</p>
<pre class="brush: cpp; title: ; notranslate">
        // This &quot;while&quot; loop goes round and round- perhaps forever
	while (window.isOpen())
	{
		/*
			Handle the player input
			*********************************************************************
			*********************************************************************
			*********************************************************************
		*/

		Event event;
		while (window.pollEvent(event))
		{
			if (event.type == Event::Closed)
				// Someone closed the window- bye
				window.close();
		}

		if (Keyboard::isKeyPressed(Keyboard::Left))
		{
			// move left...
			bat.moveLeft();
		}
		else if (Keyboard::isKeyPressed(Keyboard::Right))
		{
			// move right...
			bat.moveRight();
		}
		else if (Keyboard::isKeyPressed(sf::Keyboard::Escape))
		{
			// quit...
			// Someone closed the window- bye
			window.close();
		}
</pre>
<p>We will soon see the knock-on effect of changing the <pre class="crayon-plain-tag">position.x</pre> variable. First let&#8217;s work out if any collisions have taken place.</p>
<h3>Main.cpp part four</h3>
<p>This next block of code comprises four main <pre class="crayon-plain-tag">if</pre> statements although one of them has a further nested <pre class="crayon-plain-tag">if</pre> statement.</p>
<p>The first main <pre class="crayon-plain-tag">if</pre> statement checks whether the ball has hit the bottom of the screen. It does so by using the <pre class="crayon-plain-tag">getPosition</pre> function we coded in the <pre class="crayon-plain-tag">Ball</pre> class and checking the <pre class="crayon-plain-tag">top</pre> variable of the returned <pre class="crayon-plain-tag">FloatRec</pre>t to see if it has exceeded the height of the screen. If it has then a number of things happen next. First, we call the <pre class="crayon-plain-tag">hitBottom</pre> function to reposition the ball at the top of the screen and reverse its direction, then we subtract a life from the player. Next, still inside the <pre class="crayon-plain-tag">if</pre> statement that determined the ball hit the bottom, we check if the player has run out of lives. If the player has run out of lives we reset the score to zero and the lives back to three. The player is essentially starting again.</p>
<p>In the next main <pre class="crayon-plain-tag">if</pre> statement, we find out if the ball has hit the top of the screen by checking if the top of the ball is at a position less than zero. If it has, all we need to do is call the <pre class="crayon-plain-tag">reboundBatOrTop</pre> function which reverses the direction. Furthermore, we add a point to the player&#8217;s score.</p>
<p>The next <pre class="crayon-plain-tag">if</pre> statement checks for a collision on the left or right-hand side of the screen. The condition uses the logical OR <pre class="crayon-plain-tag">||</pre> operator so it can test for the ball&#8217;s left-hand side being less than zero or the ball&#8217;s right-hand side being greater than the width of the screen in one condition. If the condition is true, all we need to do is call the <pre class="crayon-plain-tag">reboundSides</pre> function on <pre class="crayon-plain-tag">ball</pre> and the ball&#8217;s direction is reversed.</p>
<p>The last <pre class="crayon-plain-tag">if</pre> statement is a little bit different to the others because it detects if the ball has hit the bat. It achieves this using the <pre class="crayon-plain-tag">getPosition</pre> function just like the other collision detecting <pre class="crayon-plain-tag">if</pre> statements did but this time it chains that function call with another call to a function called <pre class="crayon-plain-tag">intersects</pre>. Take a look at this <pre class="crayon-plain-tag">if</pre> condition closely and we will explore what is going on.</p>
<p>The <pre class="crayon-plain-tag">ball.getPosition()</pre> part of the code returns a <pre class="crayon-plain-tag">FloatRect</pre> object, just like we coded it to do. Now, because <pre class="crayon-plain-tag">FloatRect</pre>, itself is a class, it too has functions that can be called. The returned <pre class="crayon-plain-tag">FloatRect</pre> from <pre class="crayon-plain-tag">getPosition</pre> is used to call its <pre class="crayon-plain-tag">intersects</pre> function passing in as a parameter the returned <pre class="crayon-plain-tag">FloatRect</pre> from <pre class="crayon-plain-tag">bat.getposition</pre>. Essentially we are saying, does the ball intersect the bat? If it does the condition is true and we call the <pre class="crayon-plain-tag">reboundTopOrBat</pre> function which reverses the ball and sends it heading off towards the top of the screen again.</p>
<p>Enter the following code after the previous code we entered.</p>
<pre class="brush: cpp; title: ; notranslate">
        /*
			Update the frame
			*********************************************************************
			*********************************************************************
			*********************************************************************
		*/

		// Handle ball hitting the bottom
		if (ball.getPosition().top &gt; windowHeight)
		{
			// reverse the ball direction
			ball.hitBottom();

			// Remove a life
			lives --;

			// Check for zero lives
			if (lives &lt; 1) {
				// reset the score
				score = 0;
				// reset the lives
				lives = 3;
			}

		}

		// Handle ball hitting top
		if (ball.getPosition().top &lt; 0)
		{
			ball.reboundBatOrTop();

			// Add a point to the players score
			score++;

		}

		// Handle ball hitting sides
		if (ball.getPosition().left &lt; 0 || ball.getPosition().left + 10 &gt; windowWidth)
		{
			ball.reboundSides();
		}

		// Has the ball hit the bat?
		if (ball.getPosition().intersects(bat.getPosition()))
		{
			// Hit detected so reverse the ball and score a point
			ball.reboundBatOrTop();
		}
</pre>
<p>Nearly there!</p>
<h3>Main.cpp part five</h3>
<p>The final part of updating the current frame requires us to call the <pre class="crayon-plain-tag">update</pre> functions of both the <pre class="crayon-plain-tag">bat</pre> and the <pre class="crayon-plain-tag">ball</pre> objects. In the <pre class="crayon-plain-tag">bat update</pre> function, we simply update the position and in the ball update method we move the ball in the appropriate direction and then update its position. They are now ready to be drawn.</p>
<p>The last part of the code in this block is totally new. We are declaring an object of type <pre class="crayon-plain-tag">stringstream</pre> and calling it <pre class="crayon-plain-tag">ss</pre>. We can use <pre class="crayon-plain-tag">ss</pre> to <strong>concatenate</strong> (add together) characters and numerical values to create a single string-like object. This, as we will see, is perfect for displaying a dynamic score and number of lives in our <pre class="crayon-plain-tag">hud</pre> object. The slightly strange looking <pre class="crayon-plain-tag">ss &lt;&lt; "score:" &lt;&lt; score...</pre> code does exactly this. We then set the String held in <pre class="crayon-plain-tag">ss</pre> to <pre class="crayon-plain-tag">hud</pre> which of course is a <pre class="crayon-plain-tag">Text</pre> object.</p>
<p>Add the code we have just discussed.</p>
<pre class="brush: cpp; title: ; notranslate">
ball.update();
bat.update();

// Update the HUD text
std::stringstream ss;
ss &lt;&lt; &quot;Score:&quot; &lt;&lt; score &lt;&lt; &quot;    Lives:&quot; &lt;&lt; lives;
hud.setString(ss.str());
</pre>
<p>Let&#8217;s draw.</p>
<h3>Main.cpp part six</h3>
<p>First, we clear the previous frame with <pre class="crayon-plain-tag">window.clear</pre>, then we draw the bat and the ball using <pre class="crayon-plain-tag">window.draw</pre> passing in a call to the <pre class="crayon-plain-tag">getShape</pre> function of each of our two objects. As these functions return the appropriate <pre class="crayon-plain-tag">RectangleShape</pre> the effect is that they are drawn on the screen. We then call <pre class="crayon-plain-tag">window.draw</pre> and pass in <pre class="crayon-plain-tag">hud</pre> to draw the HUD. Finally we call <pre class="crayon-plain-tag">window.display</pre> to draw the current frame to the screen.</p>
<pre class="brush: cpp; title: ; notranslate">

         /*
			Draw the frame
			*********************************************************************
			*********************************************************************
			*********************************************************************
		*/

		// Clear everything from the last frame
		window.clear(Color(26, 128, 182,255));

		window.draw(bat.getShape());

		window.draw(ball.getShape());

		// Draw our score
		window.draw(hud);

		// Show everything we just drew
		window.display();
	}// This is the end of the &quot;while&quot; loop

	return 0;
}
</pre>
<p>Run the game and you will be able to entertain yourself, just as I did when I was four years old.</p>
<h2>What can we do better next time?</h2>
<p>There are a few flaws with our game. Some are obvious and some not quite as obvious.</p>
<p>If you were to run this game on a super-fast PC and then run it on an ageing laptop, you would see that the game actually runs at totally different speeds. A professional game would control the number of frames per second (FPS) so that it ran exactly the same regardless of the speed of the PC. This is not especially tough and we could have incorporated it in this project. I just thought there were enough new ideas already.</p>
<p>Another issue is that we have only used boring shapes for all the game objects. This isn&#8217;t too much of an issue for a Pong clone but we will need to use real graphics if we are going to win Indie game of the year anytime soon.</p>
<p>There is also the issue that by creating and managing each and every object individually we will eventually have an extremely cluttered code base. Imagine if we did a Zombie Survival game with dozens of Zombies. How would we manage the zombies? Would we have dozens of zombie objects like z1, z2, z3, z4&#8230; etc.?</p>
<p>We will be improving on all these issues and solve the problems as we progress with more C++ tutorials and the next SFML project.</p>
<p>Note to self: Zombie Survival game seems like a good choice for next project.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/sfml/coding-a-simple-pong-game-with-sfml/feed/</wfw:commentRss>
		<slash:comments>75</slash:comments>
		</item>
		<item>
		<title>Conditions and branching demo: Bouncing shapes</title>
		<link>https://gamecodeschool.com/sfml/conditions-and-branching-demo-bouncing-shapes/</link>
		<comments>https://gamecodeschool.com/sfml/conditions-and-branching-demo-bouncing-shapes/#comments</comments>
		<pubDate>Mon, 16 Nov 2015 16:00:18 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=12650</guid>
		<description><![CDATA[[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;] To get started we need to create a new project, complete with all the required properties to work with SFML. If you haven&#8217;t completed the Building your first SFML game project you will need to do that first. In that project we created a Visual Studio project template, so that starting a new SFML project is [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this mini-project we will get to use C++ condition checking with some <pre class="crayon-plain-tag">if</pre> statements. Like the last project we will draw some shapes (slightly different this time) and move them. This time however instead of letting them disappear off of the screen we will detect when they are leaving the screen on any of the four sides and then &#8220;bounce&#8221; them back the other way. </p>

[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-3 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this project</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to complete 30 minutes</p>
<h4>New concepts</h4>
<ul>
<li>Using C++ conditions</li>
<li>Using C++ <pre class="crayon-plain-tag">if</pre> statements</li>
<li>Another look at the SFML <pre class="crayon-plain-tag">Shape</pre> class</li>
<li>Introduction to C++ <strong>constants</strong></li>
<li>The most basic collision detection in the world</li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a title="Making games: Where do I start?" href="http://gamecodeschool.com/blog/making-games-where-do-i-start/">Know where you want to start</a></li>
<li>Find out <a href="http://gamecodeschool.com/blog/what-is-sfml-and-should-i-use-it/">what is SFML</a>.</li>
<li><a href="http://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/">C++ game coding level 1 introduction</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/game-variables-c-plus-plus/">C++ Game variables tutorial</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/manipulating-the-value-of-our-games-variables/">Manipulating the value of game variables</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/condition-checking-in-a-game/">Condition checking in a game</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/structuring-and-branching-the-code/">Structuring and branching code</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Assumed previous experience</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>Basic proficiency with Windows</li>
<li><a href="http://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Setup SFML and Visual Studio development environment</a></li>
<li><a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a></li>
<li><a href="http://gamecodeschool.com/sfml/game-variables-demo-moving-circles/">SFML variables demo: Moving circles</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>To get started we need to create a new project, complete with all the required properties to work with SFML. If you haven&#8217;t completed the <a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a> you will need to do that first. In that project we created a Visual Studio project <strong>template,</strong> so that starting a new SFML project is now a two minute job instead of a half an hour long chore.</p>
<p>The next steps set up our new SFML C++ project. If you want more detailed steps and images to perform these steps check the previous project. <a href="http://gamecodeschool.com/sfml/game-variables-demo-moving-circles/">Game variables demo: Moving circles</a>.</p>
<ol>
<li>Open Visual Studio and from the main menu choose <span style="color: #008000;">File | New Project</span>. In the left-hand menu click <span style="color: #008000;">C++</span>. Select the <span style="color: #008000;">HelloSFML</span> template and name your project <span style="color: #008000;">Conditions And Branching</span>.</li>
<li>Now click <span style="color: #008000;">OK</span>.</li>
<li>Right-click the <span style="color: #008000;">HelloSFML.cpp</span> file under the <span style="color: #008000;">Source Files</span> heading from the right-hand <span style="color: #008000;">Solution Explorer</span> window. Choose <span style="color: #008000;">Rename</span> and rename the file to <span style="color: #008000;">Main</span>. This is a more appropriate name as this will indeed be our &#8220;main&#8221; source file.</li>
<li>Open <span style="color: #008000;">Main.cpp</span> by double-clicking it. Now delete all of its contents as we will be starting fresh and discussing all of the code as well.</li>
<li>Copy &amp; paste the SFML .dll files in the <span style="color: #008000;">YOUR_DRIVE:\SFML\bin</span> to <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\Conditions And Branching\Conditions And Branching</span>.</li>
</ol>
<p>Now we can get coding.</p>
<p>[widgets_on_pages id=&#8221;bcgp_cfgp_gpp&#8221;]</p>
<h2>Writing the code</h2>
<p>Copy and paste all the code that follows into your currently empty, Main.cpp file. You don&#8217;t need to type it all in order to learn, but you should definitely read all the comments and analyse as best you can the code before we go through it a bit at a time.</p>
<pre class="brush: cpp; title: ; notranslate">
// These &quot;include&quot; code from the C++ library and SFML too
#include &quot;stdafx.h&quot;
#include &lt;SFML/Graphics.hpp&gt;

// This is where our game starts from
int main()
{
	// Make a window that is 1000 by 700 pixels
	// And has the title &quot;Conditions and branching demo&quot;
	// Change the resolution if it is unsuitable for you

	int windowWidth = 1000;
	int windowHeight = 700;

	sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), &quot;Conditions and branching demo&quot;);

	// Let's make a few shapes
	// define a circle with radius = 100
	// Our new circle is called &quot;tri&quot;!!??!!
	sf::CircleShape tri(100);

	// A circle with 3 points
	// There is a clue in the variable name
	tri.setPointCount(3);

	// Here is another &quot;circle&quot;
	sf::CircleShape bumpy(100);
	bumpy.setPointCount(15);

	// Now lets have some variables for their positions (x and y)
	float triX = 0;
	float triY = 0;

	float bumpyX = windowWidth;
	float bumpyY = windowHeight;

	// Here are some variables that can never change.
	// Thet are called constants.
	// We make their names all uppercase to remind us.
	// We use the const keyword to make them constant.
	// We will see their purpose soon.
	const float LEFT = -1;
	const float RIGHT = 1;
	const float UP = -1;
	const float DOWN = 1;

	// The direction is not constant
	// tri starts with RIGHT and DOWN
	float triDirectionX = RIGHT;
	float triDirectionY = DOWN;

	// The direction is not constant
	// bumpy starts with LEFT and UP
	float bumpyDirectionX = LEFT;
	float bumpyDirectionY = UP;

	// How fast will they move
	float speed = .1;

	// This &quot;while&quot; loop goes round and round- perhaps forever
	// It only stops when the player closes the window
	while (window.isOpen())
	{

		// Has the player closed the game window?
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				// Someone closed the window- bye
				window.close();
		}

		// Handle the ai, physics and process updates
		// Watch out for collisions with the edge of the screen

		// First the tri shape
		if (triX &gt; windowWidth) {
			// Triangle is near right of screen
			triDirectionX = LEFT;
		}
		else if (triX &lt; 0) {
			// Triangle is near left of screen
			triDirectionX = RIGHT;
		}

		if (triY &gt; windowHeight) {
			// Triangle is near bottom of screen
			triDirectionY = UP;
		}
		else if (triY &lt; 0) {
			// Triangle is near top of screen
			triDirectionY = DOWN;
		}

		// Now for bumpy
		if (bumpyX &gt; windowWidth) {
			// Bumpy shape is near right of screen
			bumpyDirectionX = LEFT;
		}
		else if (bumpyX &lt; 0) {
			// Bumpy shape is near left of screen
			bumpyDirectionX = RIGHT;
		}

		if (bumpyY &gt; windowHeight) {
			// Bumpy shape is near bottom of screen
			bumpyDirectionY = UP;
		}
		else if (bumpyY &lt; 0) {
			// Bumpy shape is near top of screen
			bumpyDirectionY = DOWN;
		}

		// Let's move our two shapes based of the values
		// held by the appropriate ...directionX and ...directionY
		// and the speed variable
		triX = triX + speed * triDirectionX;
		triY = triY + speed * triDirectionY;

		bumpyX = bumpyX + speed * bumpyDirectionX;
		bumpyY = bumpyY + speed * bumpyDirectionY;

		// Set the position of the shapes
		tri.setPosition(triX, triY);
		bumpy.setPosition(bumpyX, bumpyY);

		// Clear everything from the last run of the while loop
		window.clear();

		// Draw our game scene
		window.draw(tri);
		window.draw(bumpy);

		// Show everything we just drew
		window.display();
	}// This is the end of the &quot;while&quot; loop

	return 0;
}
</pre>
<p>Run the demo by clicking the <span style="color: #008000;">Local Windows Debugger</span> button.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_moving_bouncing_shapes_demo.png"><br />
</a> <a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_moving_bouncing_shapes_demo_debugging.png"><img class="aligncenter  wp-image-12654" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_moving_bouncing_shapes_demo_debugging.png" alt="sfml_moving_bouncing_shapes_demo_debugging" width="545" height="400" /></a></p>
<p>Try changing the value of speed by a significant amount, perhaps to .5 and watch how the shapes dramatically speed up.</p>
<p>Now we can analyse the code a bit at a time.</p>
<h2>Analyzing the code</h2>
<p>[widgets_on_pages id=&#8221;udemy_advert_cpp_2&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
The first thing we see in the code we have seen before. Two <pre class="crayon-plain-tag">#include</pre> directives to make available the necessary files to make a basic Windows program and the SFML graphics module. Then we enter the <pre class="crayon-plain-tag">main</pre> function and our code will begin to be executed.</p>
<pre class="brush: cpp; title: ; notranslate">
// These &quot;include&quot; code from the C++ library and SFML too
#include &quot;stdafx.h&quot;
#include &lt;SFML/Graphics.hpp&gt;

// This is where our game starts from
int main()
{
</pre>
<p>First, we make a window using an SFML <pre class="crayon-plain-tag">RenderWindow</pre> class. This we do very slightly differently to how we did it before. Notice we declare two variables <pre class="crayon-plain-tag">windowWidth</pre> and <pre class="crayon-plain-tag">windowHeight</pre>. We initialize them to <pre class="crayon-plain-tag">1000</pre> and <pre class="crayon-plain-tag">700</pre> respectively. We then use these two variables in the line of code that creates a window. This, of course, will have the effect of creating a window for our game that is 1000 pixels wide and 700 pixels high.</p>
<p>We will see what advantage having these two variables will bring us, soon.</p>
<pre class="brush: cpp; title: ; notranslate">
// Make a window that is 1000 by 700 pixels
// And has the title &quot;Conditions and branching demo&quot;
// Change the resolution if it is unsuitable for you

int windowWidth = 1000;
int windowHeight = 700;

sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), &quot;Conditions and branching demo&quot;);
</pre>
<p>Next, we make some shapes using the SFML <pre class="crayon-plain-tag">CircleShape</pre> class. First, slightly counter-intuitively we make a circle called <pre class="crayon-plain-tag">tri</pre>? The next line of code sets the number of points using the <pre class="crayon-plain-tag">setPointCount</pre> function, to 3. This is how we can make a whole variety of different shapes using SFML. Simply set the number of points and you have the shape you require. By setting three points we get a triangle.</p>
<p>Next, we create another <pre class="crayon-plain-tag">CircleShape</pre> object and call it <pre class="crayon-plain-tag">bumpy</pre>. We set the number of points at <pre class="crayon-plain-tag">15</pre>. If you ran the code you will have seen you get something much more like a circle, albeit quite a bumpy circle, hence the name.</p>
<p>Lastly, in this block of code, we declare and initialize some variables to hold the horizontal and vertical locations of our two shapes; <pre class="crayon-plain-tag">tri</pre> and <pre class="crayon-plain-tag">bumpy</pre>. We name the variables appropriately as <pre class="crayon-plain-tag">triX</pre>, <pre class="crayon-plain-tag">triY</pre>, <pre class="crayon-plain-tag">bumpyX</pre> and <pre class="crayon-plain-tag">bumpyY</pre>. What is perhaps more interesting is the values to which we initialize them.</p>
<p>The <pre class="crayon-plain-tag">triX</pre> and <pre class="crayon-plain-tag">triY</pre> variables are both set to zero and so when used to position the <pre class="crayon-plain-tag">tri</pre> shape will be in the top left corner of the screen. We initialize the <pre class="crayon-plain-tag">bumpyX</pre> and <pre class="crayon-plain-tag">bumpyY</pre> variables with <pre class="crayon-plain-tag">windowWidth</pre> and <pre class="crayon-plain-tag">windowHeight</pre> respectively. As <pre class="crayon-plain-tag">windowWidth</pre> and <pre class="crayon-plain-tag">windowHeight</pre>, as you would expect, contain the width and height of our window; when these variables are to set the position of the bumpy shape, it will be in the bottom right corner of the screen.</p>
<pre class="brush: cpp; title: ; notranslate">
// Let's make a few shapes
// define a circle with radius = 100
// Our new circle is called &quot;tri&quot;!!??!!
sf::CircleShape tri(100);

// A circle with 3 points
// There is a clue in the variable name
tri.setPointCount(3);

// Here is another &quot;circle&quot;
sf::CircleShape bumpy(100);
bumpy.setPointCount(15);

// Now lets have some variables for their positions (x and y)
float triX = 0;
float triY = 0;

float bumpyX = windowWidth;
float bumpyY = windowHeight;
</pre>
<p>Now we see something totally new to us. We declare four <pre class="crayon-plain-tag">float</pre> variables as we have done on other occasions but each of the lines of code is prefixed with the <pre class="crayon-plain-tag">const</pre> keyword. This makes the value that we initialize the variable to, unchangeable, constant. Technically speaking they are not actually variables(because they can&#8217;t vary); they are <strong>constants</strong>.</p>
<p>Now look at the values that we give these constants. Either -1 or 1. The exact use for these we will soon see. As a kind of advanced explanation, we use these values because when you multiply something by one it remains the same and when you multiply something by minus one it becomes its inverse. This simple fact is going to be useful.</p>
<p>It is a convention to name constants in all upper-case characters.</p>
<pre class="brush: cpp; title: ; notranslate">
// Here are some variables that can never change.
// Thet are called constants.
// We make their names all uppercase to remind us.
// We use the const keyword to make them constant.
// We will see their purpose soon.
const float LEFT = -1;
const float RIGHT = 1;
const float UP = -1;
const float DOWN = 1;
</pre>
<p>Now we declare four more <pre class="crayon-plain-tag">float</pre> variables, one for both the horizontal and vertical directions of travel for each of our two shapes. Notice that we assign their starting values using one of our four constants. These represent the starting directions of travel of our two shapes.</p>
<p>Lastly, in this next block of code, we declare and initialize a <pre class="crayon-plain-tag">speed</pre> variable at <pre class="crayon-plain-tag">.5</pre>. This will be the number of pixels per frame that our shapes will move at. We will see, however, that we can modify this value using the following variables:</p>
<ul>
<li><pre class="crayon-plain-tag">triDirectionX</pre>,</li>
<li><pre class="crayon-plain-tag">triDirectionY</pre>,</li>
<li><pre class="crayon-plain-tag">bumpyDirectionX</pre></li>
<li>and <pre class="crayon-plain-tag">bumpyDirectionY</pre>,</li>
</ul>
<p>in order to make our shapes bounce all over the place.</p>
<pre class="brush: cpp; title: ; notranslate">
// The direction is not constant
// tri starts with RIGHT and DOWN
float triDirectionX = RIGHT;
float triDirectionY = DOWN;

// The direction is not constant
// bumpy starts with LEFT and UP
float bumpyDirectionX = LEFT;
float bumpyDirectionY = UP;

// How fast will they move
float speed = .1;
</pre>
<p>Next, we enter the loop that will be continually repeated to create the frames of our game. We will finally demystify the details of loops in the next C++ tutorial but for now, all we need to know is everything in the remainder of our code is repeated over and over at least hundreds of frames per second.</p>
<pre class="brush: cpp; title: ; notranslate">
// This &quot;while&quot; loop goes round and round- perhaps forever
// It only stops when the player closes the window
while (window.isOpen())
{
</pre>
<p>This next code we have also seen before and it causes our game to exit if the player closes the window. The next working project will go into this in greater detail including handling more input from the player.</p>
<pre class="brush: cpp; title: ; notranslate">
// Has the player closed the game window?
sf::Event event;
while (window.pollEvent(event))
{
	if (event.type == sf::Event::Closed)
		// Someone closed the window- bye
		window.close();
}
</pre>
<p>This next block of code is the main learning point. Let&#8217;s examine the first <pre class="crayon-plain-tag">if</pre> statement and then we can quickly understand them all. The code <pre class="crayon-plain-tag">if(triX &gt; windowWidth)</pre> tests for the <pre class="crayon-plain-tag">triX</pre> variable being greater (higher) than the <pre class="crayon-plain-tag">windowWidth</pre> variable. If the <pre class="crayon-plain-tag">triX</pre> variable is greater then we can safely assume that the <pre class="crayon-plain-tag">tri</pre> shape is about to disappear off of the right-hand side of the screen. Now look at the code that executes inside the if block should that condition be true. The code <pre class="crayon-plain-tag">triDirectionX = LEFT</pre> assigns to <pre class="crayon-plain-tag">triDirectionX</pre> the value in the <pre class="crayon-plain-tag">LEFT</pre> constant, which is -1. Exactly what this does for us will become apparent in the next block of code</p>
<p>Before the next block of code, however, quickly look at the rest of the <pre class="crayon-plain-tag">if</pre> statements. They all look for one of our shapes either exceeding the values stored in <pre class="crayon-plain-tag">windowWidth</pre> <pre class="crayon-plain-tag">windowHeight</pre> or going below (less than) zero. In each case, the appropriate value, <pre class="crayon-plain-tag">LEFT</pre>, <pre class="crayon-plain-tag">RIGHT</pre>, <pre class="crayon-plain-tag">UP</pre> or <pre class="crayon-plain-tag">DOWN</pre> is assigned to the variable <pre class="crayon-plain-tag">triDrirectionX</pre>, <pre class="crayon-plain-tag">triDirectionY</pre>, <pre class="crayon-plain-tag">bumpyDirectionX</pre> or <pre class="crayon-plain-tag">bumpyDirectionY</pre>.</p>
<p>The other thing to observe is that the <pre class="crayon-plain-tag">if</pre> statements are paired with <pre class="crayon-plain-tag">else if</pre> statements. This is because we know that, if for instance <pre class="crayon-plain-tag">triX</pre> IS greater than <pre class="crayon-plain-tag">windowWidth</pre> then it is a waste of time also checking whether <pre class="crayon-plain-tag">triX</pre> is less than zero, in the same frame.</p>
<p>Take another look at the code that follows and if necessary refresh your memory with the following two C++ tutorials.</p>
<ul>
<li><a href="http://gamecodeschool.com/c-plus-plus/condition-checking-in-a-game/">Condition checking in a game</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/structuring-and-branching-the-code/">Structuring and branching code</a></li>
</ul>
<pre class="brush: cpp; title: ; notranslate">
// Handle the ai, physics and process updates
// Watch out for collisions with the edge of the screen

// First the tri shape
if (triX &gt; windowWidth) {
	// Triangle is near right of screen
	triDirectionX = LEFT;
}
else if (triX &lt; 0) {
	// Triangle is near left of screen
	triDirectionX = RIGHT;
}

if (triY &gt; windowHeight) {
	// Triangle is near bottom of screen
	triDirectionY = UP;
}
else if (triY &lt; 0) {
	// Triangle is near top of screen
	triDirectionY = DOWN;
}

// Now for bumpy
if (bumpyX &gt; windowWidth) {
	// Bumpy shape is near right of screen
	bumpyDirectionX = LEFT;
}
else if (bumpyX &lt; 0) {
	// Bumpy shape is near left of screen
	bumpyDirectionX = RIGHT;
}

if (bumpyY &gt; windowHeight) {
	// Bumpy shape is near bottom of screen
	bumpyDirectionY = UP;
}
else if (bumpyY &lt; 0) {
	// Bumpy shape is near top of screen
	bumpyDirectionY = DOWN;
}
</pre>
<p>In the next code, all our hard work comes together. We manipulate each of the x and y coordinates of both of our shapes using the following formula:</p>
<p><strong>coordinate x = coordinate x + speed * direction</strong></p>
<p>A specific example we demonstrate better what is happening. If we assume the <pre class="crayon-plain-tag">triX</pre> coordinate is currently equal to 120. That is, 120 pixels across from the left of the screen and it is travelling left. Where will we draw the <pre class="crayon-plain-tag">tri</pre> shape on the x axis this frame? The sum goes like this:</p>
<p><strong>new x location = 120 + .1 * -1</strong></p>
<p>Just for clarity, the <strong>120</strong> is the current coordinate, the <strong>.1</strong> is the value of the speed variable and the <strong>-1</strong> is the value of <pre class="crayon-plain-tag">triDirectionX</pre> because <pre class="crayon-plain-tag">LEFT</pre> would have been assigned to it when it reached the far right of the screen. The answer is therefore:</p>
<p><strong>new x location = 119.9</strong></p>
<p>We can see that the coordinate is indeed moving steadily to the left.</p>
<p>This formula is repeated for each of the horizontal and vertical locations of both of our shapes.</p>
<p>Finally at the end of this block of code we call <pre class="crayon-plain-tag">setPosition</pre> on each of our shapes to move them to their newly calculated positions.</p>
<pre class="brush: cpp; title: ; notranslate">
// Let's move our two shapes based of the values
// held by the appropriate ...directionX and ...directionY
// and the speed variable
triX = triX + speed * triDirectionX;
triY = triY + speed * triDirectionY;

bumpyX = bumpyX + speed * bumpyDirectionX;
bumpyY = bumpyY + speed * bumpyDirectionY;

// Set the position of the shapes
tri.setPosition(triX, triY);
bumpy.setPosition(bumpyX, bumpyY);
</pre>
<p>In this last block of code, we clear the screen and actually draw the two shapes.</p>
<pre class="brush: cpp; title: ; notranslate">
// Clear everything from the last run of the while loop
		window.clear();

		// Draw our game scene
		window.draw(tri);
		window.draw(bumpy);

		// Show everything we just drew
		window.display();

	}// This is the end of the &quot;while&quot; loop

	return 0;
}// End of the program
</pre>
<h2>Summary and what&#8217;s next?</h2>
<p>That was a big chunk of code but hopefully nothing too complicated. We now have shapes that bounce around the screen. We achieved this by moving the shapes each frame by a magnitude of .1 but by multiplying that magnitude by either 1 or -1 we controlled their up, down, left, right headings. We also used constants for the first time. Note that we could have not bothered with the constants and simply hard-coded the 1 or -1 values in the <pre class="crayon-plain-tag">if</pre> statements where we changed the direction of our shapes. However, by using appropriately named constants we make it completely plain what they are for and what their values represent. This becomes more important as our code gets longer, spread over multiple files and more complex.</p>
<p>The next logical step is to read the tutorial on C++ loops which will be followed up by another SFML project where we will expand again on the functionality of our games.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/sfml/conditions-and-branching-demo-bouncing-shapes/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Game variables demo: moving circles</title>
		<link>https://gamecodeschool.com/sfml/game-variables-demo-moving-circles/</link>
		<comments>https://gamecodeschool.com/sfml/game-variables-demo-moving-circles/#comments</comments>
		<pubDate>Wed, 11 Nov 2015 11:12:44 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=12566</guid>
		<description><![CDATA[[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;] To get started we need to create a new project complete with all the required properties to work with SFML. If you haven&#8217;t completed the Building your first SFML game project you will need to do that first. In that last project we created a Visual Studio project template so that starting a new SFML project [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this mini-project we will get to experiment with how we can use C++ variables in our games. We will play around with some <pre class="crayon-plain-tag">float</pre> variables and see how they can be used with the SFML <pre class="crayon-plain-tag">CircleShape</pre> class to put circles on the screen. We will then see how we can use what we learnt in the manipulating C++ game variables tutorial to move them around the screen. Kind of like giant pong (without the paddles). If you don&#8217;t know what a class is yet it doesn&#8217;t matter. We will see some neat things in action but learn about what is going on behind the scenes in a later tutorial.</p>

[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-4 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this project</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to complete 30 minutes</p>
<h4>New concepts</h4>
<ul>
<li>Using C++ variables</li>
<li>Changing C++ variables</li>
<li>Using a Visual Studio project template</li>
<li>Another look at the main game loop</li>
<li>Brief introduction SFML event handling</li>
<li>SFML CircleShape</li>
<li>SFML setFillColor</li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a title="Making games: Where do I start?" href="http://gamecodeschool.com/blog/making-games-where-do-i-start/">Know where you want to start</a></li>
<li>Find out <a href="http://gamecodeschool.com/blog/what-is-sfml-and-should-i-use-it/">what is SFML</a>.</li>
<li><a href="http://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/">C++ game coding level 1 introduction</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/game-variables-c-plus-plus/">C++ Game variables tutorial</a></li>
<li><a href="http://gamecodeschool.com/c-plus-plus/manipulating-the-value-of-our-games-variables/">Manipulating the value of game variables</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Assumed previous experience</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>Basic proficiency with Windows</li>
<li><a href="http://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Setup SFML and Visual Studio development environment</a></li>
<li><a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>To get started we need to create a new project complete with all the required properties to work with SFML. If you haven&#8217;t completed the <a href="http://gamecodeschool.com/sfml/building-your-first-sfml-game-project/">Building your first SFML game project</a> you will need to do that first. In that last project we created a Visual Studio project <strong>template</strong> so that starting a new SFML project is now a two minute job instead of a half an hour long chore.</p>
<p>Open Visual Studio and from the main menu choose <span style="color: #008000;">File | New Project</span>. In the left-hand menu click <span style="color: #008000;">C++</span> and you will see the following options.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/using_visual_studio_template_for-_sfml_game_project.png"><img class="aligncenter size-full wp-image-12571" src="http://gamecodeschool.com/wp-content/uploads/2015/11/using_visual_studio_template_for-_sfml_game_project.png" alt="using_visual_studio_template_for _sfml_game_project" width="800" height="553" /></a></p>
<p>&nbsp;</p>
<p>Select the <span style="color: #008000;">HelloSFML</span> template as highlighted in the previous image. Name your project <span style="color: #008000;">Variables Demo</span> as also highlighted in the above image. Now click <span style="color: #008000;">OK</span>.</p>
<p>Right-click the <span style="color: #008000;">HelloSFML.cpp</span> file under the <span style="color: #008000;">Source Files</span> heading from the right-hand <span style="color: #008000;">Solution Explorer</span> window. Choose <span style="color: #008000;">Rename</span> and rename the file to <span style="color: #008000;">Main</span>. This is a more appropriate name as this will indeed be our &#8220;main&#8221; source file. Open <span style="color: #008000;">Main.cpp</span> by double-clicking it. Now delete all of its contents as we will be starting fresh and discussing all of the code as well.</p>
<p>The only thing we need to do now is to copy all the .dll files to the current project&#8217;s working folder.</p>
<p>[widgets_on_pages id=&#8221;bcgp_cfgp_gpp&#8221;]</p>
<h2>Copying the .dll files to the project folder</h2>
<p>My project folder is <span style="color: #008000;">D:\Visual Studio Stuff\Projects\Variables Demo\Variables Demo</span>. The files we need to copy into there are located at <span style="color: #008000;">D:\SFML\bin</span>. Of course, if you installed Visual Studio and the <span style="color: #008000;">Visual Studio Stuff</span> folder on a different drive then replace <span style="color: #008000;">D:</span> from the previous paths with your appropriate drive letter. Open a window for each of the two locations and highlight the required files as shown in the next screenshot on the left.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/copy_sfml_dll_files_to_project_directory.png"><img class="aligncenter size-full wp-image-12572" src="http://gamecodeschool.com/wp-content/uploads/2015/11/copy_sfml_dll_files_to_project_directory.png" alt="copy_sfml_dll_files_to_project_directory" width="800" height="435" /></a></p>
<p>&nbsp;</p>
<p>Copy &amp; paste the files in the <span style="color: #008000;">YOUR_DRIVE:\SFML\bin</span> to <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\Variables Demo\Variables Demo</span>. Don&#8217;t drag and drop them because that will move them and they will be harder to find when we do the next project.</p>
<h2>The  actual Code</h2>
<p>Add the entire starting code for this variables demo by copy and pasting the code below. Unlike when we were just doing a &#8220;hello world&#8221; SFML project, this time, we will discuss all sections of the code. Some aspects like variables, because they are the real topic of this mini-project, we will make sure we know exactly what is going on. Some of the other aspects we will look at from a distance just to get a feel for what is happening and then revisit them after we have completed the related C++ tutorials.</p>
<p>Be sure to read all of the comments and the code. It won&#8217;t all make sense but that doesn&#8217;t matter as we will break it down into chunks and go through it all soon. Here is the code to copy and paste into <span style="color: #008000;">Main.cpp</span>.</p>
<pre class="brush: cpp; title: ; notranslate">
// Anything after // is a comment not actual C++ code
// Comments are important and I use them to explain things
// Why not read the comments in this code

// These &quot;include&quot; code from the C++ library and SFML too
#include &quot;stdafx.h&quot;
#include &lt;SFML/Graphics.hpp&gt;

// This is the main C++ program- Duh!
// It is where our game starts from
int main()
{
	// Make a window that is 800 by 600 pixels
	// And has the title &quot;Variables Demo&quot;
	sf::RenderWindow window(sf::VideoMode(800, 600), &quot;Variables Demo&quot;);

	// Make three circles with 50 pixels radius
	// called circleRed, circle Green and circleBlue
	sf::CircleShape circleRed(50);
	sf::CircleShape circleGreen(50);
	sf::CircleShape circleBlue(50);

	// Color the circles appropriately
	circleRed.setFillColor(sf::Color(255, 0, 0));
	circleGreen.setFillColor(sf::Color(0, 255, 0));
	circleBlue.setFillColor(sf::Color(0, 0, 255));

	// Here's the variables stuff
	float xGreen = 200;
	float yGreen = 200;

	float xBlue = 300;
	float yBlue = 300;

	// Position the red circle at x,y 100,100 &quot;Hard-coded&quot;
	circleRed.setPosition(100, 100);

	// Position the green circle at the postion -
	// stored in xGreen and yGreen
	circleGreen.setPosition(xGreen, yGreen);

	// Position the blue circle at the postion -
	// stored in xBlue and yBlue
	circleBlue.setPosition(xBlue, yBlue);

	// Now all our circles are ready to draw -
	// we can enter the main game loop
	// This &quot;while&quot; loop goes round and round...
	// until player closes window
	while (window.isOpen())
	{
		// The next 6 lines of code detect if the window is closed
		// And then shuts down the program
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				// Someone closed the window- bye
				window.close();
		}
                // End user input detection

		// Clear everything from the last run of the while loop
		window.clear();

		// Process game logic, AI, movement etc
		// We will add some new code here in a minute!!!!!!

        // End of new code

		// Draw our game scene here
		//Draw the cirlces
		window.draw(circleRed);
		window.draw(circleGreen);
		window.draw(circleBlue);

		// Show everything on the screen
		window.display();

	}// This is the end of the &quot;while&quot; loop

	return 0;
}
</pre>
<h2>Running the demo</h2>
<p>Now click the button shown in the next image to run our Variables Demo project.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_run_hello_world_app.png" data-caption=""><img class="aligncenter  wp-image-12484" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_run_hello_world_app.png" alt="sfml_run_hello_world_app" width="1015" height="120" /></a></p>
<p>&nbsp;</p>
<p>Wow, three circles!</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_project_drawing_circles.png"><img class="aligncenter size-full wp-image-12576" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_project_drawing_circles.png" alt="sfml_project_drawing_circles" width="800" height="631" /></a></p>
<p>&nbsp;</p>
<p>Wouldn&#8217;t it be cool to make them move? We will soon by manipulating the variables but first, let&#8217;s understand the code we have written so far.</p>
<h2>Explaining the code block by block</h2>
<p>At the top of the <span style="color: #008000;">Main.cpp</span> file we have a bunch of comments and then we have two <pre class="crayon-plain-tag">#include</pre> directives. These make available other files into our project. Sometimes we will add <pre class="crayon-plain-tag">#include</pre> directives for code that we have written ourselves and other times, like now we include other people&#8217;s code. The <pre class="crayon-plain-tag">stdafx.h</pre> file is a usual suspect of a Windows program and nothing to do with games. I suggest for now you just accept that we need it but if you&#8217;re really curious you could do a Web search for its purpose.</p>
<p>More interesting is the <pre class="crayon-plain-tag">SFML/Graphics.hpp</pre> file. This is a header file. We know it is a header file because of its <pre class="crayon-plain-tag">.hpp</pre> file extension. Header files are the files where we declare the format of the C++ code which does the actual work. This sounds a bit odd but will make sense when we learn about functions in a later tutorial. The reason we need to include <pre class="crayon-plain-tag">Graphics.hpp</pre> is because it declares some SFML <strong>classes</strong> and  <strong>functions</strong> which we use in this project.</p>
<p>At this stage, we can think of a class as a container for our code and we can think of a function as part of a class which performs a specific task. <pre class="crayon-plain-tag">CircleShape</pre> is a class in this header file, <pre class="crayon-plain-tag">setFillColor</pre> and <pre class="crayon-plain-tag">setPosition</pre> are both functions from this header file. We will look more closely at these soon in this tutorial. Take another look at the code we have just discussed.</p>
<pre class="brush: cpp; title: ; notranslate">
// Anything after // is a comment not actual C++ code
// Comments are important and I use them to explain things
// Why not read the comments in this code

// These &quot;include&quot; code from the C++ library and SFML too
#include &quot;stdafx.h&quot;
#include &lt;SFML/Graphics.hpp&gt;
</pre>
<p>&nbsp;</p>
<p>This next code is where the code begins execution from. When the player double-clicks on our .exe in a finished game or we click the Local Windows Debugger button, this is where it starts from. All C++ programs have an <pre class="crayon-plain-tag">main()</pre> entry point. Actually <pre class="crayon-plain-tag">main</pre> is itself a function.</p>
<pre class="brush: cpp; title: ; notranslate">
// This is the main C++ program- Duh!
// It is where our game starts from
int main()
{
    ...
</pre>
<p>&nbsp;</p>
<p>In the next block of code, we see the slightly daunting <pre class="crayon-plain-tag">sf::RenderWindow window(sf::VideoMode(800, 600), "Variables Demo");</pre> line of code. For now, we just need to know that it will create a window that is 800 pixels by 600 pixels and has a title of <span style="color: #008000;">Variables Demo</span>.</p>
<p>Next, we create three circles. Or, more specifically three <pre class="crayon-plain-tag">CircleShape</pre> objects. The exact way this works isn&#8217;t important at this stage except that the code is able to make these <pre class="crayon-plain-tag">CircleShape</pre> objects because we <pre class="crayon-plain-tag">#included Graphics.hpp</pre>. What is more important to us right now is that these three <pre class="crayon-plain-tag">CircleShape</pre> objects have names, very much like we have variables with names we can also create objects, from classes and give them a name. The names are <pre class="crayon-plain-tag">circleRed</pre>, <pre class="crayon-plain-tag">circleGreen</pre> and <pre class="crayon-plain-tag">circleBlue</pre>. The <pre class="crayon-plain-tag">50</pre> inside the brackets <pre class="crayon-plain-tag">()</pre> is the radius we would like our <pre class="crayon-plain-tag">CircleShape</pre> objects to have, in pixels. Try changing one of them now and re-run the project. Don&#8217;t worry about understanding objects and classes, just note that we have three <pre class="crayon-plain-tag">CircleShapes</pre> with names.</p>
<p>Study the code we have just discussed one more time.</p>
<pre class="brush: cpp; title: ; notranslate">
// Make a window that is 800 by 600 pixels
// And has the title &quot;Variables Demo&quot;
sf::RenderWindow window(sf::VideoMode(800, 600), &quot;Variables Demo&quot;);

// Make three circles with 50 pixels radius
// called circleRed, circle Green and circleBlue
sf::CircleShape circleRed(50);
sf::CircleShape circleGreen(50);
sf::CircleShape circleBlue(50);
</pre>
<p>&nbsp;</p>
<p>In the next block of code, you can see we use our object names followed by <pre class="crayon-plain-tag">setFillColor</pre>. As mentioned previously, <pre class="crayon-plain-tag">setFillColor</pre> is a function (code that does something) and we are able to use that function <em>on</em> each of our three objects. When we do this we say we are <strong>calling</strong> the function. Basically, we are executing the C++ code in that function. Notice in the brackets following the</p>
<p>Notice in the brackets following the <pre class="crayon-plain-tag">setFillColor</pre> function call it looks a little convoluted but each has a set of three numbers. These three numbers are values for red, green and blue respectively. We can think of this as a mixing palette. And depending upon the amounts of each color that are mixed in determines the color that is made. The <pre class="crayon-plain-tag">setFillColor</pre> function then makes the circle in question into that color. Each RGB color value ranges from 0 (none of that color) to 255 (strongest possible value of that color). So, 255,0,0 makes red; 0,255,0 makes green and 0,0,255 makes blue. Understanding the RGB color model at this point isn&#8217;t important. If you just about get that calling <pre class="crayon-plain-tag">setFillColor</pre> on a <pre class="crayon-plain-tag">CircleShape</pre> object allows you to set its color we can move on.</p>
<p>Study the code block we have just discussed and then we will look at the next bit of code.</p>
<pre class="brush: cpp; title: ; notranslate">
// Color the circles appropriately
circleRed.setFillColor(sf::Color(255, 0, 0));
circleGreen.setFillColor(sf::Color(0, 255, 0));
circleBlue.setFillColor(sf::Color(0, 0, 255));
</pre>
<p>&nbsp;</p>
<p>In the next block of code, we are initializing our four <pre class="crayon-plain-tag">float</pre> variables with values, just like we did in the <a href="http://gamecodeschool.com/c-plus-plus/game-variables-c-plus-plus/">Game variables in C++ tutorial</a>. What is more interesting is how we put those variables to work in the code block that comes after it. Make sure you are comfortable with initializing the variables in this next block of code then move on.</p>
<pre class="brush: cpp; title: ; notranslate">
// Here's the variables stuff
float xGreen = 200;
float yGreen = 200;

float xBlue = 300;
float yBlue = 300;
</pre>
<p>&nbsp;</p>
<p>Now we see the <pre class="crayon-plain-tag">setPosition</pre> function being called on each of our <pre class="crayon-plain-tag">CircleShape</pre> objects in turn. When we call <pre class="crayon-plain-tag">setPosition</pre> on <pre class="crayon-plain-tag">circleRed</pre> we use the values <pre class="crayon-plain-tag">100, 100</pre>. These values are <strong>passed</strong> to the <pre class="crayon-plain-tag">setPosition</pre> function and <pre class="crayon-plain-tag">circleRed</pre> will be drawn at the screen coordinates 100 pixels on the x-axis and 100 pixels on the y-axis.</p>
<p>Next, we call <pre class="crayon-plain-tag">setPosition</pre> on the <pre class="crayon-plain-tag">circleGreen</pre> object. The difference here is that we don&#8217;t use actual, real values; we use variables that contain values. <pre class="crayon-plain-tag">circleGreen.setPosition(xGreen, yGreen)</pre> will draw the circle at 200 pixels on the x-axis and 200 pixels on the y-axis. This is because the <pre class="crayon-plain-tag">xGreen</pre> and <pre class="crayon-plain-tag">yGreen</pre> variables store the values 200 and 200. At first glance a commonly asked question might be, &#8220;Why bother with the variables? We could have just passed in the values 200, 200&#8243;.</p>
<p>The simple answer is that when we use variables instead of hard-coded values, we can change them while the game is actually running.</p>
<p>Let&#8217;s quickly finish explaining the last few blocks of code then we will see how this helps us. After <pre class="crayon-plain-tag">circleGreen.setPosition</pre> is called using the <pre class="crayon-plain-tag">xGreen</pre> and <pre class="crayon-plain-tag">yGreen</pre> variables we then call <pre class="crayon-plain-tag">circleBlue.setPosition</pre> with the <pre class="crayon-plain-tag">xBlue</pre> and <pre class="crayon-plain-tag">yBlue</pre> variables. As these two variables were both initialized to 300 the position of the circle is set to the x and y-axes accordingly. Study the code we have just discussed.</p>
<pre class="brush: cpp; title: ; notranslate">
// Position the red circle at x,y 100,100 &quot;Hard-coded&quot;
circleRed.setPosition(100, 100);

// Position the green circle at the postion -
// stored in xGreen and yGreen
circleGreen.setPosition(xGreen, yGreen);

// Position the blue circle at the postion -
// stored in xBlue and yBlue
circleBlue.setPosition(xBlue, yBlue);
</pre>
<p>&nbsp;</p>
<p>We are going to brush over this next code until we have covered a later tutorial. Here is the important parts explained. The code <pre class="crayon-plain-tag">while (window.isOpen())</pre> is the start of the main game loop which is repeated over and over again. It processes all the ai, physics, user input and draws the scene. We will aim to keep this loop running at around 60 frames per second (<strong>FPS</strong>).  For now, with this simple code, it is more likely running at thousands of frames per second.</p>
<p>There is another loop within this loop that begins <pre class="crayon-plain-tag">while (window.pollEvent(/event))</pre>. This short code loops through all the messages that might have been received from the operating system. Sometimes there will be zero messages, other times there might be many. We can choose which ones we care about and respond to them. It is here where we will handle the player&#8217;s input, moving the game character, quitting, etc. In this code, we just handle what happens when the player closes the window and quits the program. To properly understand this code we need to learn a bit more C++ but take a look at it anyway the code isn&#8217;t entirely unfathomable.</p>
<pre class="brush: cpp; title: ; notranslate">
// Now all our circles are ready to draw -
// we can enter the main game loop
// This &quot;while&quot; loop goes round and round...
// until player closes window
while (window.isOpen())
{
	// The next 6 lines of code detect if the window is closed
	// And then shuts down the program
	sf::Event event;
	while (window.pollEvent(event))
	{
		if (event.type == sf::Event::Closed)
			// Someone closed the window- bye
			window.close();
	}
        // End user input detection&lt;/pre&gt;

</pre>
<p>&nbsp;</p>
<p>Now we clear whatever we drew in the last frame with <pre class="crayon-plain-tag">window.clear()</pre>. Then we draw our circles <pre class="crayon-plain-tag">circleRed</pre>, <pre class="crayon-plain-tag">circleGreen</pre> and <pre class="crayon-plain-tag">circleBlue</pre> by calling <pre class="crayon-plain-tag">window.draw</pre> for each circle in turn. Remember that at this point our program has already executed the code to color and position these circles. Also remember when we run this code; although we are looking at three static circles they are actually being rubbed out and redrawn thousands of times per second.</p>
<p>The final bit of code in this block is the closing <pre class="crayon-plain-tag">}</pre> of the while loop that started with <pre class="crayon-plain-tag">while (window.isOpen())</pre>.</p>
<p>Study this next code and as you do identify the code comments that say <pre class="crayon-plain-tag">// We will add some more code here in a minute!!!!!!</pre> and the next code comment that says <pre class="crayon-plain-tag">// End of new code</pre>. It is between these two lines that we will add some more code soon. Study the code we have just discussed.</p>
<pre class="brush: cpp; title: ; notranslate">
	// Clear everything from the last run of the while loop
	window.clear();

	// Process game logic, AI, movement etc
	// We will add some more code here in a minute!!!!!!

    // End of new code

	// Draw our game scene here
	//Draw the cirlces
	window.draw(circleRed);
	window.draw(circleGreen);
	window.draw(circleBlue);

	// Show everything on the screen
	window.display();

}// This is the end of the &quot;while&quot; loop
</pre>
<p>&nbsp;</p>
<p>The <pre class="crayon-plain-tag">return 0</pre> line of code quits the entire program. So when we call window.close() the main game loop ends and execution comes to this line and it&#8217;s all over. We will explore how the loop control works in more detail in a later tutorial.</p>
<pre class="brush: cpp; title: ; notranslate">
	return 0;
}
</pre>
<h2>Making the circles move</h2>
<p>[widgets_on_pages id=&#8221;udemy_advert_cpp_2&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
Now add this next block of code between <pre class="crayon-plain-tag">// We will add some more code here in a minute!!!!!!</pre> and the next code comment that says <pre class="crayon-plain-tag">// End of new code</pre>.</p>
<pre class="brush: cpp; title: ; notranslate">
// We will add some more code here in a minute!!!!!!

// Let's manipulate our coordinates variables
// Increase xGreen by one hundreth each game frame
xGreen = xGreen + .01;
// Decrease yGreen by one hundreth each game frame
yGreen = yGreen - .01;

// Increase xBlue by three, hundreths each game frame
xBlue = xBlue + .03;
// Increase yBlue by three, hundreths each game frame
yBlue = yBlue + .03;

// Position the green circle at the postion -
// stored in xGreen and yGreen
circleGreen.setPosition(xGreen, yGreen);

// Position the blue circle at the postion -
// stored in xBlue and yBlue
circleBlue.setPosition(xBlue, yBlue);

// End of new code
</pre>
<p>Now click the button shown in the next image to run our Variables Demo project again.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_run_hello_world_app.png" data-caption=""><img class="aligncenter  wp-image-12484" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_run_hello_world_app.png" alt="sfml_run_hello_world_app" width="1015" height="120" /></a></p>
<p>&nbsp;</p>
<p>And their off.. Each time through the loop the values of <pre class="crayon-plain-tag">xGreen</pre>, <pre class="crayon-plain-tag">yGreen</pre>, <pre class="crayon-plain-tag">xBlue</pre> and <pre class="crayon-plain-tag">yBlue</pre> are modified. Then when we call <pre class="crayon-plain-tag">setPosition</pre> again the circles are in those new locations when the scene is drawn. It is because the change is gradual over time that we see them move smoothly.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_moving_circles_demo.png"><img class="aligncenter size-full wp-image-12582" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_moving_circles_demo.png" alt="sfml_moving_circles_demo" width="800" height="631" /></a></p>
<p>What is happening here is very simple yet powerful. It demonstrates in the simplest way possible how every game&#8217;s animation works.</p>
<ol>
<li>Update the scene</li>
<li>Draw the scene</li>
<li>Repeat</li>
</ol>
<p>The code <pre class="crayon-plain-tag">xGreen = xGreen + .01</pre> adds .01 onto the value stored in <pre class="crayon-plain-tag">xGreen</pre>. The code <pre class="crayon-plain-tag">yGreen = yGreen - .01</pre> subtracts .01 from the value of <pre class="crayon-plain-tag">yGreen</pre>. Also, as we are already aware, this happens many times per second making the circle smoothly animate itself upwards and to the right.</p>
<p>The code <pre class="crayon-plain-tag">xBlue = xBlue + .03</pre> adds .03 onto the value stored in <pre class="crayon-plain-tag">xBlue</pre>. The code <pre class="crayon-plain-tag">yBlue = yBlue + .03</pre> adds .03 to the value stored in <pre class="crayon-plain-tag">yBlue</pre>. As with <pre class="crayon-plain-tag">circleGreen</pre> this happens many times per second making the blue circle smoothly (but faster than <pre class="crayon-plain-tag">circleGreen</pre>) animate itself down and to the right.</p>
<h2>Things to do and what&#8217;s next?</h2>
<p>Try playing with the values that we use to move the circles to make them faster or head in different directions. What happens when we move objects by different amounts on the x-axis than that of the y-axis.</p>
<p>Something to consider about the code we have just written is this: If we let the program run for just a short time the moving circles will disappear into oblivion. We need a way to &#8216;know&#8217; when they are going somewhere we don&#8217;t want them to go so we can change their behavior.</p>
<p>That&#8217;s as far as this tutorial will explore. The next logical step and part of the solution to the problem of &#8216;knowing&#8217; posed above would be to read the <a href="http://gamecodeschool.com/c-plus-plus/condition-checking-in-a-game/">Checking for conditions in C++ code</a> where we will get to the bottom of all those odd looking if keywords.</p>
<p>Something else to think about as an aside is to consider the imperfections of the code we have just written. Our green circle moved by .01 pixels per frame. The number of frames that are executed per second is entirely dependent upon how powerful the computer that it is running on. We are going to need to solve this problem. Otherwise, a shooter would be faster (and probably harder) on newer PCs.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/sfml/game-variables-demo-moving-circles/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		</item>
		<item>
		<title>Building your first SFML game project</title>
		<link>https://gamecodeschool.com/sfml/building-your-first-sfml-game-project/</link>
		<comments>https://gamecodeschool.com/sfml/building-your-first-sfml-game-project/#comments</comments>
		<pubDate>Thu, 05 Nov 2015 11:34:33 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=12446</guid>
		<description><![CDATA[Now that we have a working development environment we can go ahead and configure a project and write some code that actually does something. For the sake of actually seeing SFML in action we will write some code but we will not learn about each and every line of it. Rather we will improve our [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Now that we have a working development environment we can go ahead and configure a project and write some code that actually does something. For the sake of actually seeing SFML in action we will write some code but we will not learn about each and every line of it. Rather we will improve our understanding as we progress during future SFML projects and C++ tutorials .[widgets_on_pages id=&#8221;udemy_advert_cpp_1&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-5 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this project</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to complete 40 minutes (downloads might take longer)</p>
<h4>New concepts</h4>
<ol>
<li>Project configuration</li>
<li>C++ headers</li>
<li>Libraries</li>
<li>Linking</li>
<li>Visual Studio templates</li>
<li>Some real SFML/C++ code!</li>
</ol>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a title="Making games: Where do I start?" href="http://gamecodeschool.com/blog/making-games-where-do-i-start/">Know where you want to start</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Assumed previous experience</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>Basic proficiency with Windows</li>
<li><a href="http://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Set up a Visual Studio 2017 and SFML development environment</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<h2>Getting started</h2>
<p>In this project we will start from the very beginning as this is our first SFML project. It is true that there is quite a bit of messing around to be done with regard to configuring our first project to use SFML in the way that we need. We will however be saving these configurations in a Visual Studio template so that all future projects can be started with a couple of clicks. When we have done this we will finally get to see SFML in action as we draw some fancy text to the screen.</p>
<h2>Configuring the SFML project</h2>
<p>Start Visual Studio 2017 and select <span style="color: #008000;">File | New Project</span>.</p>
<p>In the <span style="color: #008000;">New Project</span> window choose <span style="color: #008000;">Visual C++</span> || <span style="color: #008000;">Windows Desktop</span> then <span style="color: #008000;">Win32 Console Application</span>. You can see all these selections in the next screenshot.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/configuring-new-sfml-project-in-visual-studio.jpg"><img class="aligncenter size-full wp-image-15993" src="http://gamecodeschool.com/wp-content/uploads/2015/11/configuring-new-sfml-project-in-visual-studio.jpg" alt="configuring-new-sfml-project-in-visual-studio" width="800" height="555" /></a></p>
<p>&nbsp;</p>
<p>Now at the bottom of the <span style="color: #008000;">New Project</span> window type <span style="color: #008000;">HelloSFML</span> in the <span style="color: #008000;">Name:</span> field. It is a tradition when learning a new language to start making a program which says &#8220;Hello World&#8221; to the user. This is what we will do in this project but we will quickly get closer and closer to a real game as we progress through future projects.</p>
<p>Next, browse to the <span style="color: #008000;">Visual Studio Stuff\Projects\</span> folder that we created in the <a href="http://gamecodeschool.com/sfml/setting-up-visual-studio-and-sfml-development-environment/">Setting up a Visual Studio 2017 and SFML development environment</a> project. This will be the location that all our project files will be kept.</p>
<p>When you have completed the steps above click <span style="color: #008000;">OK. </span> and Visual Studio will create our new project.</p>
<p>[widgets_on_pages id=&#8221;bcgp_cfgp_gpp&#8221;]</p>
<h3>The slightly dull (but important) configuration stuff</h3>
<p>Next, we will add some fairly intricate and vital project settings. This is the laborious part but we will only need to do this once. What we need to do is to tell Visual Studio, or more specifically the code compiler that is part of Visual Studio where to find a special type of code file from the SFML SDK. The special type of file I am referring to is a header file. Header files are the files that define the format of the SFML code. So when we use the SFML code the compiler knows how to handle it. Note that the header files are distinct from the main source code files and they are contained in files with the .hpp file extension. All this will become clearer when we eventually start adding our own header files in a few projects time. In addition, we need to tell Visual Studio where it can find the SFML library files.</p>
<p>We can achieve the above by doing the following:</p>
<p>From the Visual Studio main menu select <span style="color: #008000;">Project | HelloSFML properties</span>. In the resulting <span style="color: #008000;">HelloSFML Property Pages</span> window take the following steps which are numbered and can be referred to in the next image.</p>
<ol>
<li>Select <span style="color: #008000;">All Configurations</span> from the <span style="color: #008000;">Configuration:</span> drop-down.</li>
<li>Select <span style="color: #008000;">C/C++</span> then <span style="color: #008000;">General</span> from the left-hand menu.</li>
<li>Locate the <span style="color: #008000;">Additional Include Directories</span> edit box and type the drive letter where your <span style="color: #008000;">SFML</span> folder is followed by <span style="color: #008000;">\SFML\include</span>. So the full path to type if you located your <span style="color: #008000;">SFML</span> folder on your D drive is, as shown in the screen-shot <span style="color: #008000;">D:\SFML\include</span>.</li>
</ol>
<div id="attachment_12463" style="width: 810px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_additional_include_directories.png"><img class="size-full wp-image-12463" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_additional_include_directories.png" alt="This image refers to the steps above." width="800" height="267" /></a><p class="wp-caption-text">This image refers to the steps above.</p></div>
<p>&nbsp;</p>
<p>Click <span style="color: #008000;">Apply</span> to save our configurations so far.</p>
<p>Still, in the same window perform these next numbered steps which again refer to the next image.</p>
<ol>
<li>Select <span style="color: #008000;">Linker</span> then <span style="color: #008000;">General</span>.</li>
<li>Find the <span style="color: #008000;">Additional Library Directories</span> edit box and type the drive letter where your <span style="color: #008000;">SFML</span> folder is followed by <span style="color: #008000;">\SFML\lib</span>. So the full path to type if you located your <span style="color: #008000;">SFML</span> folder on your D drive is, as shown in the screen-shot is <span style="color: #008000;">D:\SFML\lib</span>.</li>
</ol>
<div id="attachment_12464" style="width: 810px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_additional_library_directories.png"><img class="size-full wp-image-12464" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_additional_library_directories.png" alt="This image refers to the steps above" width="800" height="252" /></a><p class="wp-caption-text">This image refers to the steps above.</p></div>
<p>&nbsp;</p>
<p>Click <span style="color: #008000;">Apply</span> to save our configurations so far.</p>
<p>Finally for this stage, still in the same window perform these numbered steps which again refer to the next image.</p>
<ol>
<li>Switch the <span style="color: #008000;">Configuration:</span> drop down to <span style="color: #008000;">Debug</span> as we will be running and testing our games in debug mode for now.</li>
<li>Select <span style="color: #008000;">Linker</span> then <span style="color: #008000;">Input</span>.</li>
<li>Find the <span style="color: #008000;">Additional Dependencies</span> edit box and click it at the far left. Now copy &amp; paste the following <span style="color: #008000;">sfml-graphics-d.lib;sfml-window-d.lib;sfml-system-d.lib;sfml-network-d.lib;sfml-audio-d.lib;</span> at the indicated place (3). Again be <strong>REALLY</strong> careful to place the cursor exactly and not to overwrite any of the text that is already there.</li>
<li>Click <span style="color: #008000;">OK</span>.</li>
</ol>
<div id="attachment_12474" style="width: 865px" class="wp-caption aligncenter"><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_additional_dependencies1.png"><img class=" wp-image-12474" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_additional_dependencies1.png" alt="This image refers to the previous steps" width="855" height="595" /></a><p class="wp-caption-text">This image refers to the previous steps</p></div>
<p>&nbsp;</p>
<p>Let&#8217;s make a template of our work so far so we never have to do this again.</p>
<h2>Creating a reusable project template</h2>
<p>This is really easy. In Visual Studio select <span style="color: #008000;">File | Export Template&#8230;</span>. Then in the <span style="color: #008000;">Export Template Wizard</span> window make sure the <span style="color: #008000;">Project template</span> option is selected and the <span style="color: #008000;">HelloSFML</span> project is selected for the <span style="color: #008000;">From which project do you want to create a template</span> option. Click <span style="color: #008000;">Next</span> and then <span style="color: #008000;">Finish</span>. That&#8217;s it. Next time we create a project I&#8217;ll show you how to do it from this template.</p>
<h2>Copying the .dll files to the project folder</h2>
<p>That&#8217;s the tedious stuff done. In future, we will just be able to create a new project based on the template we just made. The only other step will be to copy the .dll files into the project folder which we will step through now.</p>
<p>My project folder is <span style="color: #008000;">D:\Visual Studio Stuff\Projects\HelloSFML\HelloSFML</span>. The files we need to copy into there are located at <span style="color: #008000;">D:\SFML\bin</span>. Of course, if you installed Visual Studio and the <span style="color: #008000;">Visual Studio Stuff</span> folder on a different drive then replace <span style="color: #008000;">D:</span> from the previous paths with your appropriate drive letter. Open a window for each location and highlight the required files as shown in the next screenshot on the left.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_copy_dll_files.png"><img class="aligncenter size-full wp-image-12476" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_visual_studio_copy_dll_files.png" alt="sfml_visual_studio_copy_dll_files" width="800" height="432" /></a></p>
<p>&nbsp;</p>
<p>Copy &amp; paste the files in the <span style="color: #008000;">YOUR_DRIVE:\SFML\bin</span> to <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\HelloSFML\HelloSFML</span>.</p>
<p>Let&#8217;s code!</p>
<h2>Writing the SFML &#8220;Hello World&#8221; game code</h2>
<p>[widgets_on_pages id=&#8221;udemy_advert_cpp_2&#8243;][widgets_on_pages id=&#8221;udemy_code_details&#8221;]<br />
Notice in the Visual Studio editor window there is a code file that was created for us. You can see the tab at the top-left in the next image the file name is <span style="color: #008000;">HelloSFML.cpp</span>. The .cpp stands for C++.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/hello_sfml_c_plus_plus.png"><img class="aligncenter size-full wp-image-12478" src="http://gamecodeschool.com/wp-content/uploads/2015/11/hello_sfml_c_plus_plus.png" alt="hello_sfml_c_plus_plus" width="800" height="213" /></a></p>
<p>&nbsp;</p>
<p>As I mentioned at the start of the slightly lengthy tutorial I won&#8217;t be explaining the code but I just want you to copy &amp; paste some so you actually have something to show for all this effort.</p>
<p>Before we do SFML needs a font in order to draw text.</p>
<ol>
<li>Download this free-for-personal-use font from <a href="http://www.1001freefonts.com/28_days_later.font">http://www.1001freefonts.com/28_days_later.font</a>.</li>
<li>Click the <span style="color: #008000;">Download</span> button.</li>
<li>Unzip the download.</li>
<li>Add the <span style="color: #008000;">28 Days Later.ttf</span> file into the <span style="color: #008000;">YOUR_DRIVE:\Visual Studio Stuff\Projects\HelloSFML\HelloSFML</span> folder.</li>
</ol>
<p>Delete all the code in the <span style="color: #008000;">HelloSFML.cpp</span> code file and add this code. Don&#8217;t be overwhelmed, at least half of it is just comments that don&#8217;t do anything but give hints and we will get to the bottom of all the weird symbols and words in a future tutorial. Be sure to read all the comments!</p>
<pre class="brush: java; title: ; notranslate">
// Anything after // is a comment not actual C++ code
// Comments are important and I use them to explain things
// Why not read the comments in this code

// These &quot;include&quot; code from the C++ library and SFML too
#include &quot;stdafx.h&quot;
#include &lt;SFML/Graphics.hpp&gt;

// This is the main C++ program- Duh!
// It is where our game starts from
int main()
{
	// Make a window that is 800 by 200 pixels
	// And has the title &quot;Hello from SFML&quot;
	sf::RenderWindow window(sf::VideoMode(800, 200), &quot;Hello from SFML&quot;);

	// Create a &quot;Text&quot; object called &quot;message&quot;. Weird but we will learn about objects soon
	sf::Text message;

    // We need to choose a font
	sf::Font font;
	font.loadFromFile(&quot;28 Days Later.ttf&quot;);

	// Set the font to our message
	message.setFont(font);

	// Assign the actual message
	message.setString(&quot;Hello world&quot;);

	// Make it really big
	message.setCharacterSize(100); 

	// Choose a color
	message.setFillColor(sf::Color::White);

	// This &quot;while&quot; loop goes round and round- perhaps forever
	while (window.isOpen())
	{
		// The next 6 lines of code detect if the window is closed
		// And then shuts down the program
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				// Someone closed the window- bye
				window.close();
		}

		// Clear everything from the last run of the while loop
		window.clear();

		// Draw our message
		window.draw(message);

		// Draw our game scene here
		// Just a message for now

		// Show everything we just drew
		window.display();
	}// This is the end of the &quot;while&quot; loop

	return 0;
}
</pre>
<p>&nbsp;</p>
<p>Now click the button shown in the next image</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_run_hello_world_app.png"><img class="aligncenter  wp-image-12484" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_run_hello_world_app.png" alt="sfml_run_hello_world_app" width="1015" height="120" /></a></p>
<p>&nbsp;</p>
<p>Gaze in awe at your creation.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_hello_world.png"><img class="aligncenter size-full wp-image-12483" src="http://gamecodeschool.com/wp-content/uploads/2015/11/sfml_hello_world.png" alt="sfml_hello_world" width="600" height="300" /></a></p>
<p>If you found this tutorial hard you can rest easy. It is not uncommon when learning any language that setting up the development environment can be challenging. C++ environments can be especially so because of the way that headers and libraries work. These will become more familiar and less of a strain as we proceed. And most tutorials and projects in the future will be much shorter than this one.</p>
<p>GTA 6 is so close I can smell it! Not quite I suppose but we can start <a href="http://gamecodeschool.com/c-plus-plus/c-plus-plus-game-coding-level-1/">learning to code in C++</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/sfml/building-your-first-sfml-game-project/feed/</wfw:commentRss>
		<slash:comments>114</slash:comments>
		</item>
	</channel>
</rss>
