<?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>Create your own games&#187; Game Creation Blog by Koonsolo</title>
	<atom:link href="http://dev.koonsolo.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://dev.koonsolo.com</link>
	<description>A blog on how to create your own computer games (by Koen Witters)</description>
	<lastBuildDate>Fri, 20 Aug 2010 19:09:20 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>My game company Koonsolo is shifting it&#8217;s focus</title>
		<link>http://www.koonsolo.com/news/koonsolo-is-shifting-its-focus/</link>
		<comments>http://www.koonsolo.com/news/koonsolo-is-shifting-its-focus/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 19:06:59 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=207</guid>
		<description><![CDATA[I got great news for everyone who likes to create his/her own games. As you might know I started this blog because I wanted to share my knowledge on creating games. Developing games by myself allowed me to give some practical advice. But now I have the opportunity to do even more for you. As [...]]]></description>
			<content:encoded><![CDATA[<p>I got great news for everyone who likes to create his/her own games. As you might know I started this blog because I wanted to share my knowledge on creating games. Developing games by myself allowed me to give some practical advice. But now I have the opportunity to do even more for you. As you can read in my latest blog post, my game company <a href="http://www.koonsolo.com/news/koonsolo-is-shifting-its-focus/">Koonsolo is shifting it&#8217;s focus from making games to making a game creation tool</a>. Yes, that&#8217;s right! So next time you can leave all the technical stuff up to me, and focus on creating your dream game <img src='http://dev.koonsolo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=207" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/koonsolo-is-shifting-its-focus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lecture Video on Game Loops</title>
		<link>http://www.koonsolo.com/news/lecture-video-on-game-loops/</link>
		<comments>http://www.koonsolo.com/news/lecture-video-on-game-loops/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 14:47:55 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=179</guid>
		<description><![CDATA[I wrote my original article on game loops a few years ago, and it&#8217;s nice to see that it&#8217;s still popular today. Recently I stumbled upon some game loop lecture slides of Aaron D. Lanterman, and he seems to use my game loop article as a reference  . He even has a video of [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote <a href="http://dev.koonsolo.com/7/dewitters-gameloop/">my original article on game loops </a>a few years ago, and it&#8217;s nice to see that it&#8217;s still popular today. Recently I stumbled upon some <a href="http://users.ece.gatech.edu/lanterma/mpg08/mpglecture08f08.pdf">game loop lecture slides</a> of Aaron D. Lanterman, and he seems to use my game loop article as a reference <img src='http://dev.koonsolo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . He even has <a href="http://blip.tv/file/1274252">a video of his session</a> online. So if you had a hard time understanding my article, maybe you should check out that video. It might make things more clear.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="300" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://blip.tv/play/Ac6URAI" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="300" src="http://blip.tv/play/Ac6URAI" allowfullscreen="true"></embed></object></p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=179" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/lecture-video-on-game-loops/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flexible use of game libraries</title>
		<link>http://www.koonsolo.com/news/flexible-use-of-game-libraries/</link>
		<comments>http://www.koonsolo.com/news/flexible-use-of-game-libraries/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 15:24:39 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=70</guid>
		<description><![CDATA[When developing a new game, the first thing you should consider is your high level game architecture. You&#8217;re probably going to use some 3rd party libraries, maybe you already have some in-house libraries that you&#8217;re going to use, or develop them for future use. How these things fit together seems obvious, but when you consider [...]]]></description>
			<content:encoded><![CDATA[<p>When developing a new game, the first thing you should consider is your high level game architecture. You&#8217;re probably going to use some 3rd party libraries, maybe you already have some in-house libraries that you&#8217;re going to use, or develop them for future use. How these things fit together seems obvious, but when you consider following architecture, it will save you a lot of time and frustration later on.</p>
<p><span id="more-70"></span>The high level architecture that I&#8217;ve developed over the years has 3 layers:</p>
<pre> ________________________
|                        |
|      Core Game         |
|________________________|
            |
 ___________V____________
|                        |
| In-house Game Library  |
|________________________|
            |
 ___________V____________
|                        |
|  3rd party libraries   |
|    - Sound             |
|    - Graphics          |
|    - GUI               |
|    - ...               |
|________________________|</pre>
<p>The Core Game only contains code <em>specific</em> to the game. Try to move as much generic code to your in-house game library, this way you can reuse it when you&#8217;re working on other games.</p>
<p>The in-house game library contains on one hand the generic code that can be shared between multiple games, and on the other hand acts as a <a href="http://en.wikipedia.org/wiki/Facade_pattern">facade</a> on top of 3rd party libraries. This means that the core game never calls the 3rd party libraries directly, but always passes through your in-house game library.</p>
<h2>Advantages</h2>
<p>Since your core game is only using your own inhouse game library, you have total control over the API that it calls. Switching 3rd party libraries or custom made has no impact on the game code. You can also extend the external libraries with some functionality that you can write on top of them. When interface changes are made in newer 3rd party libraries, you don&#8217;t have to find/replace in your game code, adapting the in-house game library is enough. Porting multiple games also becomes easier, because once your in-house game library is ported, no major adaptions are needed in the core games.</p>
<p><em>Koen Witters</em></p>
<p><a href="http://twitter.com/koonsolo"><em>Follow me on twitter</em></a></p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=70" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/flexible-use-of-game-libraries/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>19 general purpose 2D engines</title>
		<link>http://www.koonsolo.com/news/19-general-purpose-2d-engines/</link>
		<comments>http://www.koonsolo.com/news/19-general-purpose-2d-engines/#comments</comments>
		<pubDate>Sun, 26 Jul 2009 08:50:17 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=124</guid>
		<description><![CDATA[The Rampant Coyote has created a list of 19 general purpose 2D engines that you can use for you project. Now how do you choose the right one? Well, an indie game developer should consider following things:

To get as many customers as possible, use an engine that supports multiple platforms: Windows, Mac and Linux.
To make [...]]]></description>
			<content:encoded><![CDATA[<p>The Rampant Coyote has created a list of <a href="http://rampantgames.com/community/viewtopic.php?t=697">19 general purpose 2D engines</a> that you can use for you project. Now how do you choose the right one? Well, an indie game developer should consider following things:</p>
<ul>
<li>To get as many customers as possible, use an engine that supports multiple platforms: Windows, Mac and Linux.</li>
<li>To make the best use of your time, prefer higher level scripting languages over lower level programming languages.</li>
<li>Paying for an engine doesn&#8217;t necessarily mean that you get a better product or better support.</li>
</ul>
<p>My personal favorite? <a href="http://www.pygame.org/">Pygame</a> of course! <img src='http://dev.koonsolo.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=124" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/19-general-purpose-2d-engines/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Game Architecture: Model-View-Controller</title>
		<link>http://www.koonsolo.com/news/model-view-controller-for-games/</link>
		<comments>http://www.koonsolo.com/news/model-view-controller-for-games/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 17:16:42 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=9</guid>
		<description><![CDATA[When programming a new game, most of the time you implement some basic features and start from there. As the game gets bigger, your code gets more interwoven, and the classes bigger. And before you know it you end up with spaghetti code and god classes, and that&#8217;s the last thing anyone wants.
Let&#8217;s assume we&#8217;re [...]]]></description>
			<content:encoded><![CDATA[<p>When programming a new game, most of the time you implement some basic features and start from there. As the game gets bigger, your code gets more interwoven, and the classes bigger. And before you know it you end up with spaghetti code and god classes, and that&#8217;s the last thing anyone wants.</p>
<p>Let&#8217;s assume we&#8217;re programming a racing game, and we have a class called RaceCar. Soon enough that class will contain a method to update it&#8217;s state, to draw it onto the screen, to accept user input, etc. It will become huge with all kinds of different functionality in there. So how can we divide up our game so it&#8217;s nicely split up into modules and classes? Just read on and learn <img src='http://dev.koonsolo.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p><span id="more-9"></span></p>
<h2>Step 1: Split up the game into logic and rendering</h2>
<h3>Concept</h3>
<p>The first thing we should do is decouple the rendering from the logic. And this makes perfect sense. If you take look at my <a href="http://dev.koonsolo.com/7/dewitters-gameloop/">game loop article</a>, we can even let the game logic run at a different speed than the rendering.</p>
<p>The game logic will know nothing about the rendering, so it doesn&#8217;t matter if it will be displayed in 2D, 3D, ASCII art or whatever. The rendering however depends on the logic, because it needs info on how/where to display everything. The following figure shows the 2 modules with their dependencies. The rendering happens inside the &#8220;View&#8221; module.</p>
<pre>     _________          _________
    |         |        |         |
    |  Logic  |&lt;-------|  View   |
    |_________|        |_________|</pre>
<h3>Example</h3>
<p>What this means in practice is that we will create a RaceCarView class next to our RaceCar. RaceCar handles the logic and user input, and knows nothing on how to display it, and RaceCarView displays the race car on the screen, using information from RaceCar.</p>
<h3>Problem with interaction</h3>
<p>When our car is controlled by a joystick or keyboard this concept works out just fine. But assume we want to mouse click on an opponent car to take over its control. If our logic knows nothing about the view, we don&#8217;t know on which car the user clicked. So in this case our logic also needs to query the view, which creates a circular dependency, and we don&#8217;t want this. Lucky for use we can get rid of this by doing another split, explained in the following section.</p>
<h2>Step 2: Split up the logic into model and controller</h2>
<h3>Concept</h3>
<p>The second thing we can do is further split up the logic into a model and a controller. The model is basically the game world, it knows nothing about displaying, user input, etc. It just implements all the world rules, and how entities interact with each other. The controller knows about the model and can manipulate it. For example the controller checks the user input, and manipulates the car accordingly. As we saw in the previous section, the controller needs to query the view when using mouse input for manipulating on-screen objects. And thanks to the split up, the model doesn&#8217;t have any dependencies like the logic had.</p>
<pre>           ________________
          |                |
          |   Controller   |
          |________________|
            |            |
            |            |
            |            |
      ______V__        __V______
     |         |      |         |
     |  Model  |&lt;-----|  View   |
     |_________|      |_________|</pre>
<h3>Example</h3>
<p>In our RaceCar example, we will extract our user input handling into a new class RaceCarController. When the user presses the left-button, the controller sees this and calls the model&#8217;s RaceCar.steer_left(). The model then handles the world rules of the car going to the left.</p>
<h3>Where to put the AI?</h3>
<p>Most games use an AI to control certain game objects, so the question is where to implement this, in the model or the controller? The answer is pretty simple: if the AI controls the same object in the same manner as the user does (i.e. a &#8216;bot&#8217;), implement it in the controller. In the other case, it&#8217;s part of the game world so you should implement it in the model. In our example the car AI&#8217;s should be implemented in the controller, because they are basically bots. If we would have pedestrians that jump out of the way, they would be implemented in the model, because they are part of the world.</p>
<h2>Summary</h2>
<p>So after dividing our code up we get 3 separate modules: the model, the view and the controller.</p>
<dl>
<dt>Model</dt>
<dd>All the rules of the game world are implemented in the model, and it also contains the state data of every game object or entity. It is a pure game world simulation, so it doesn&#8217;t know anything about user input or displaying to a screen.</dd>
<dt>View</dt>
<dd>Rendering to the screen is handled by the view. It uses the model to know where to draw everything. The view doesn&#8217;t have any other functionality than this.</dd>
<dt>Controller</dt>
<dd>The controller handles the user input and manipulates the model. First it checks for user input, then it might query the view to see which on-screen objects are being clicked by the mouse, and finally it manipulates the model. Multiple controllers can be implemented, for example a keyboard controller, joypad controller, and even AI &#8216;bot&#8217; controllers.</dd>
</dl>
<p>The model is standing on it&#8217;s own and doesn&#8217;t need to know anything about the others. The view depends only on the model to render everything on the screen. The controller receives input, can gain additional information by calling the view, and at the end manipulates the model. The advantages of this architecture:</p>
<ul>
<li>Nice modular design</li>
<li>Game world logic is nicely bundled in the model</li>
<li>Changes in rendering doesn&#8217;t impact the core game</li>
<li>Supports different input controllers and/or bots</li>
</ul>
<pre style="text-align: left;">           ________________
          |                |
          |   Controller   |&lt;============ User Input
          |________________|
            |            |                    O
            |            |                   /|\
            |            |                   / \
      ______V__        __V______
     |         |      |         |
     |  Model  |&lt;-----|  View   |=======&gt; Screen Output
     |_________|      |_________|</pre>
<p style="text-align: left;">
<p style="text-align: left;">Koen Witters</p>
<p style="text-align: left;"><a href="http://twitter.com/koonsolo"><em>Follow me on twitter</em></a></p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=9" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/model-view-controller-for-games/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>deWiTTERS Game Loop</title>
		<link>http://www.koonsolo.com/news/dewitters-gameloop/</link>
		<comments>http://www.koonsolo.com/news/dewitters-gameloop/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 17:11:13 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=7</guid>
		<description><![CDATA[The game loop is the heartbeat of every game, no 		  game can run without it. But unfortunately for every 		  new game programmer, there aren&#8217;t any good articles 		  on the internet who provide the proper information 		  on this topic. But fear not, because you have just 		  [...]]]></description>
			<content:encoded><![CDATA[<p>The game loop is the heartbeat of every game, no 		  game can run without it. But unfortunately for every 		  new game programmer, there aren&#8217;t any good articles 		  on the internet who provide the proper information 		  on this topic. But fear not, because you have just 		  stumbled upon the one and only article that gives 		  the game loop the attention it deserves.</p>
<p>Thanks to my job as a game programmer, I come into 		  contact with a lot of code for small mobile 		  games. And it always amazes me how many game loop 		  implementations are out there. You might wonder 		  yourself how a simple thing like that can be written 		  in different ways. Well, it can, and I will discuss 		  the pros and cons of the most popular 		  implementations, and give you the (in my opinion) 		  best solution of implementing a game loop.</p>
<p><span id="more-7"></span></p>
<p><em>(Thanks to Kao Cardoso Félix this article is also available in <a href="http://www.pythonbrasil.com.br/moin.cgi/GameLoop">Brazilian Portuguese</a>)</em></p>
<h2>The Game Loop</h2>
<p>Every game consists of a sequence of getting user 		  input, updating the game state, handling AI, playing 		  music and sound effects, and displaying the game. This 		  sequence is handled through the game loop. Just like 		  I said in the introduction, the game loop is the 		  heartbeat of every game. In this article I will not 		  go into details on any of the above mentioned tasks, 		  but will concentrate on the game loop alone. That&#8217;s 		  also why I simplified the tasks to only 2 functions: 		  updating the game and displaying it.</p>
<p>Here is some example code of the game loop in it&#8217;s 		  most simplest form:</p>
<pre>    bool game_is_running = true;

    while( game_is_running ) {
        update_game();
        display_game();
    }</pre>
<p>The problem with this simple loop is that it doesn&#8217;t 		  handle time, the game just runs. On slower hardware 		  the game runs slower, and on faster hardware 		  faster. Back in the old days when the speed of the 		  hardware was known, this wasn&#8217;t a problem, but 		  nowadays there are so many hardware platforms out 		  there, that we have to implement some sort of time 		  handling. There are many ways to do this, and I&#8217;ll 		  discuss them in the following sections.</p>
<p>First, let me explain 2 terms that are used throughout 		  this article:</p>
<dl>
<dt> FPS </dt>
<dd> FPS is an abbreviation for Frames Per Second. In 		    the context of the above implementation, it is the 		    number of times display_game() is called per 		    second. </dd>
<dt> Game Speed </dt>
<dd> Game Speed is the number of times the game state 		    gets updated per second, or in other words, the 		    number of times update_game() is called per 		    second. </dd>
</dl>
<h2>FPS dependent on Constant Game Speed</h2>
<h3>Implementation</h3>
<p>An easy solution to the timing issue is to just let 		  the game run on a steady 25 frames per second. The 		  code then looks like this:</p>
<pre>    const int FRAMES_PER_SECOND = 25;
    const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;

    DWORD next_game_tick = GetTickCount();
    // GetTickCount() returns the current number of milliseconds
    // that have elapsed since the system was started

    int sleep_time = 0;

    bool game_is_running = true;

    while( game_is_running ) {
        update_game();
        display_game();

        next_game_tick += SKIP_TICKS;
        sleep_time = next_game_tick - GetTickCount();
        if( sleep_time &gt;= 0 ) {
            Sleep( sleep_time );
        }
        else {
            // Shit, we are running behind!
        }
    }</pre>
<p>This is a solution with one huge benefit: it&#8217;s simple!  		Since you know that update_game() gets called 25 times 		per second, writing your game code is quite straight 		forward. For example, implementing a replay function 		in this kind of game loop is easy. If no random values 		are used in the game, you can just log the input 		changes of the user and replay them later.</p>
<p>On your testing hardware you can adapt the 		FRAMES_PER_SECOND to an ideal value, but what will 		happen on faster or slower hardware? Well, let&#8217;s find 		out.</p>
<h3>Slow hardware</h3>
<p>If the hardware can handle the defined FPS, no 		  problem. But the problems will start when the 		  hardware can&#8217;t handle it. The game will run 		  slower. In the worst case the game has some heavy 		  chunks where the game will run really slow, and some 		  chunks where it runs normal. The timing becomes 		  variable which can make your game unplayable.</p>
<h3>Fast hardware</h3>
<p>The game will have no problems on fast hardware, but 		  you are wasting so many precious clock 		  cycles. Running a game on 25 or 30 FPS when it could 		  easily do 300 FPS&#8230; shame on you! You will lose a 		  lot of visual appeal with this, especially with fast 		  moving objects.</p>
<p>On the other hand, with mobile devices, this can be 		  seen as a benefit. Not letting the game constantly 		  run at it&#8217;s edge could save some battery time.</p>
<h3>Conclusion</h3>
<p>Making the FPS dependent on a constant game speed is 		  a solution that is quickly implemented and keeps the 		  game code simple. But there are some problems: 		  Defining a high FPS will pose problems on slower 		  hardware, and defining a low FPS will waste visual 		  appeal on fast hardware.</p>
<h2>Game Speed dependent on Variable FPS</h2>
<h3>Implementation</h3>
<p>Another implementation of a game loop is to let it 		  run as fast as possible, and let the FPS dictate the 		  game speed. The game is updated with the time 		  difference of the previous frame.</p>
<pre>    DWORD prev_frame_tick;
    DWORD curr_frame_tick = GetTickCount();

    bool game_is_running = true;
    while( game_is_running ) {
        prev_frame_tick = curr_frame_tick;
        curr_frame_tick = GetTickCount();

        update_game( curr_frame_tick - prev_frame_tick );
        display_game();
    }</pre>
<p>The game code becomes a bit more complicated because 		we now have to consider the time difference in the 		update_game() function. But still, it&#8217;s not that hard.</p>
<p>At first sight this looks like the ideal solution to 		  our problem. I have seen many smart programmers 		  implement this kind of game loop. Some of them 		  probably wished they would have read this article 		  before they implemented their loop. I will show you 		  in a minute that this loop can have serious problems 		  on both slow and fast (yes, FAST!) hardware.</p>
<h3>Slow Hardware</h3>
<p>Slow hardware can sometimes cause certain delays at 		  some points, where the game gets &#8220;heavy&#8221;. This can 		  definitely occur with a 3D game, where at a certain 		  time too many polygons get shown. This drop in frame 		  rate will affect the input response time, and 		  therefore also the player&#8217;s reaction time. The 		  updating of the game will also feel the delay and 		  the game state will be updated in big time-chunks. As 		  a result the reaction time of the player, and also 		  that of the AI, will slow down and can make a simple 		  maneuver fail, or even impossible. For example, an 		  obstacle that could be avoided with a normal FPS,       can become impossible to avoid with a slow FPS.        A more serious problem with slow hardware is that when using physics, your simulation can even <a href="http://www.gaffer.org/game-physics/fix-your-timestep">explode</a>!</p>
<h3>Fast Hardware</h3>
<p>You are probably wondering how the above game loop 		  can go wrong on fast hardware. Unfortunately, it 		  can, and to show you, let me first explain something 		  about math on a computer.</p>
<p>The memory space of a float or double value is 		  limited, so some values cannot be represented. For 		  example, 0.1 cannot be represented binary, and 		  therefore is rounded when stored in a double. Let me 		  show you using python:</p>
<pre>&gt;&gt;&gt; 0.1
0.10000000000000001</pre>
<p>This itself is not dramatic, but the consequences 		are. Let&#8217;s say you have a race-car that has a speed of 		0.001 units per millisecond. After 10 seconds your 		race-car will have traveled a distance of 		10.0. If you split this calculation up like a game 		would do, you have the following function using frames 		per second as input:</p>
<pre>&gt;&gt;&gt; def get_distance( fps ):
...     skip_ticks = 1000 / fps
...     total_ticks = 0
...     distance = 0.0
...     speed_per_tick = 0.001
...     while total_ticks &lt; 10000:
...             distance += speed_per_tick * skip_ticks
...             total_ticks += skip_ticks
...     return distance</pre>
<p>Now we can calculate the distance at 40 frames per 		second:</p>
<pre>&gt;&gt;&gt; get_distance( 40 )
10.000000000000075</pre>
<p>Wait a minute&#8230; this is not 10.0??? What happened? 		Well, because we split up the calculation in 400 		additions, a rounding error got big.  I wonder what 		will happen at 100 frames per second&#8230;</p>
<pre>&gt;&gt;&gt; get_distance( 100 )
9.9999999999998312</pre>
<p>What??? The error is even bigger!! Well, because we have more 		additions at 100 fps, the rounding error has more 		chance to get big. So the game will differ when 		running at 40 or 100 frames per second:</p>
<pre>&gt;&gt;&gt; get_distance( 40 ) - get_distance( 100 )
2.4336088699783431e-13</pre>
<p>You might think that this difference is too small to 		be seen in the game itself. But the real problem will 		start when you use this incorrect value to do some 		more calculations. This way a small error can become 		big, and fuck up your game at high frame rates. Chances 		of that happening? Big enough to consider it! I have 		seen a game that used this kind of game loop, and 		which indeed gave trouble at high frame rates. After 		the programmer found out that the problem was hiding 		in the core of the game, only a lot of code rewriting 		could fix it.</p>
<h3>Conclusion</h3>
<p>This kind of game loop may seem very good at first 		  sight, but don&#8217;t be fooled. Both slow and fast 		  hardware can cause serious problems for your 		  game. And besides, the implementation of the game 		  update function is harder than when you use a fixed 		  frame rate, so why use it?</p>
<h2>Constant Game Speed with Maximum FPS</h2>
<h3>Implementation</h3>
<p>Our first solution, FPS dependent on Constant Game Speed, has a problem when running on slow hardware. Both the game speed and the framerate will drop in that case. A possible solution for this could be to keep updating the game at that rate, but reduce the rendering framerate. This can be done using following game loop:</p>
<pre>    const int TICKS_PER_SECOND = 50;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 10;

    DWORD next_game_tick = GetTickCount();
    int loops;

    bool game_is_running = true;
    while( game_is_running ) {

        loops = 0;
        while( GetTickCount() &gt; next_game_tick &amp;&amp; loops &lt; MAX_FRAMESKIP) {
            update_game();

            next_game_tick += SKIP_TICKS;
            loops++;
        }

        display_game();
    }</pre>
<p>The game will be updated at a steady 50 times per second, and rendering is done as fast as possible. Remark that when rendering is done more than 50 times per second, some subsequent frames will be the same, so actual visual frames will be dispayed at a maximum of 50 frames per second. When running on slow hardware, the framerate can drop until the game update loop will reach MAX_FRAMESKIP. In practice this means that when our render FPS drops below 5 (= FRAMES_PER_SECOND / MAX_FRAMESKIP), the actual game will slow down.</p>
<h3>Slow hardware</h3>
<p>On slow hardware the frames per second will drop, but the game itself will hopefully run at the normal speed. If the hardware still can&#8217;t handle this, the game itself will run slower and the framerate will not be smooth at all.</p>
<h3>Fast hardware</h3>
<p>The game will have no problems on fast hardware, but like the first solution, you are wasting so many precious clock cycles that can be used for a higher framerate. Finding the balance between a fast update rate and being able to run on slow hardware is crucial.</p>
<h3>Conclusion</h3>
<p>Using a constant game speed with a maximum FPS is         a solution that is easy to implement and keeps the         game code simple. But there are still some problems:         Defining a high FPS can still pose problems on slow         hardware (but not as severe as the first solution), and defining a low FPS will waste visual appeal on fast hardware.</p>
<h2>Constant Game Speed independent of Variable FPS</h2>
<h3>Implementation</h3>
<p>Would it be possible to improve the above solution even further to run faster on slow hardware, and be visually more atractive on faster hardware? Well, lucky for us, this is possible. The game state itself doesn&#8217;t need to be updated 60 times per second. Player input, AI and the updating of the game state have enough with 25 frames per second. So let&#8217;s try to call the update_game() 25 times per second, no more, no less. The rendering, on the other hand, needs to be as fast as the hardware can handle. But a slow frame rate shouldn&#8217;t interfere with the updating of the game. The way to achieve this is by using the following game loop:</p>
<pre>    const int TICKS_PER_SECOND = 25;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 5;

    DWORD next_game_tick = GetTickCount();
    int loops;
    float interpolation;

    bool game_is_running = true;
    while( game_is_running ) {

        loops = 0;
        while( GetTickCount() &gt; next_game_tick &amp;&amp; loops &lt; MAX_FRAMESKIP) {
            update_game();

            next_game_tick += SKIP_TICKS;
            loops++;
        }

        interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
                        / float( SKIP_TICKS );
        display_game( interpolation );
    }</pre>
<p>With this kind of game loop, the implementation of update_game() will stay easy. But unfortunately, the display_game() function gets more complex. You will have to implement a prediction function that takes the interpolation as argument. But don&#8217;t worry, this isn&#8217;t hard, it just takes a bit more work. I&#8217;ll explain below how this interpolation and prediction works, but first let me show you why it is needed.</p>
<h3>The Need for Interpolation</h3>
<p>The gamestate gets updated 25 times per second, so if you don&#8217;t use interpolation in your rendering, frames will also be displayed at this speed. Remark that 25 fps isn&#8217;t as slow as some people think, movies for example run at 24 frames per second. So 25 fps should be enough for a visually pleasing experience, but for fast moving objects, we can still see a improvement when doing more FPS. So what we can do is make fast movements more smooth in between the frames. And this is where interpolation and a prediction function can provide a solution.</p>
<h3>Interpolation and Prediction</h3>
<p>Like I said the game code runs on it&#8217;s own frames 		  per second, so when you draw/render your frames, it 		  is possible that it&#8217;s in between 2 gameticks. Let&#8217;s 		  say you have just updated your gamestate for the 		  10Th time, and now you are going to render the 		  scene. This render will be in between the 10Th and 		  11Th game update. So it is possible that the render 		  is at about 10.3. The &#8216;interpolation&#8217; value then 		  holds 0.3. Take this example: I have a car that 		  moves every game tick like this:</p>
<pre>    position = position + speed;</pre>
<p>If in the 10Th gametick the position is 500, and the 		  speed is 100, then in the 11Th gametick the position 		  will be 600. So where will you place your car when 		  you render it? You could just take the position of the 		  last gametick (in this case 500). But a better way 		  is to predict where the car would be at exact 10.3, 		  and this happens like this:</p>
<pre>    view_position = position + (speed * interpolation)</pre>
<p>The car will then be rendered at position 530.</p>
<p>So basically the interpolation variable contains the value that is in between the previous gametick and the next one (previous = 0.0, next = 1.0). What you have to do then is make a &#8220;prediction&#8221; function where the car/camera/&#8230; would be placed at the render time. You can base this prediction function on the speed of the object, steering or rotation speed. It doesn&#8217;t need to be complicated because we only use it to smooth things out in between the frames. It is indeed possible that an object gets rendered into another object right before a collision gets detected. But like we have seen before, the game is updated 25 frames per second, and so when this happens, the error is only shown for a fraction of a second, hardly noticeable to the human eye.</p>
<h3>Slow Hardware</h3>
<p>In most cases, update_game() will take far less time 		  than display_game(). In fact, we can assume that 		  even on slow hardware the update_game() function can 		  run 25 times per second. So our game will handle 		  player input and update the game state without much 		  trouble, even if the game will only display 15 		  frames per second.</p>
<h3>Fast Hardware</h3>
<p>On fast hardware, the game will still run at a 		  constant pace of 25 times per second, but the 		  updating of the screen will be way faster than 		  this. The interpolation/prediction method will 		  create the visual appeal that the game is actually 		  running at a high frame rate. The good thing is that 		  you kind of cheat with your FPS. Because you don&#8217;t 		  update your game state every frame, only the 		  visualization, your game will have a higher FPS than 		  with the second method I described.</p>
<h3>Conclusion</h3>
<p>Making the game state independent of the FPS seems 		  to be the best implementation for a game 		  loop. However, you will have to implement a 		  prediction function in display_game(), 		  but this isn&#8217;t that hard to achieve.</p>
<h2>Overall Conclusion</h2>
<p>A game loop has more to it than you think. We&#8217;ve         reviewed 4 possible implementations, and it seems         that there is one of them which you should         definitely avoid, and that&#8217;s the one where a variable         FPS dictates the game speed.</p>
<p>A constant frame rate can be a good and simple         solution for mobile devices, but when you want to         get everything the hardware has got, best use a         game loop where the FPS is completely independent of the game         speed, using a prediction function for high framerates.</p>
<p>If you don&#8217;t want to bother with a prediction function, you can work with a maximum frame rate, but finding the right game update rate for both slow and fast hardware can be tricky.</p>
<p style="text-align: left;">Now go and start coding that fantastic game you are 		  thinking of!</p>
<p style="text-align: left;">
<p style="text-align: left;">Koen Witters</p>
<p style="text-align: left;"><a href="http://twitter.com/koonsolo"><em>Follow me on twitter</em></a></p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=7" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/dewitters-gameloop/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>deWiTTERS Tao of Coding</title>
		<link>http://www.koonsolo.com/news/dewitters-tao-of-coding/</link>
		<comments>http://www.koonsolo.com/news/dewitters-tao-of-coding/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 16:54:29 +0000</pubDate>
		<dc:creator>Koen Witters</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.koonsolo.com/?p=21</guid>
		<description><![CDATA[This guide describes the coding style that I 		  developed over the years. My style isn&#8217;t very 		  widespread. As a matter of fact, I don&#8217;t know anyone 		  who comes even close to the weird way I program. But 		  I like it and want to share it with you [...]]]></description>
			<content:encoded><![CDATA[<p>This guide describes the coding style that I 		  developed over the years. My style isn&#8217;t very 		  widespread. As a matter of fact, I don&#8217;t know anyone 		  who comes even close to the weird way I program. But 		  I like it and want to share it with you anyway (you 		  lucky bastard!). I use it for all kinds of 		  programming languages: C, C++, Java, C#, 		  Python,&#8230; .</p>
<p><span id="more-21"></span>If you just want a quick overview of the style, 		  scroll to the bottom of this page 		  and see how some source code was rewritten to my 		  deWiTTERS Style, this should give you an quick idea of how 		  nice it all looks.</p>
<h2>Why a Coding Style?</h2>
<p>Every programmer uses some sort of style, some good, 		  some terrible. A coding style can give code a 		  uniform look. It can make algorithms more clear or 		  more complex. There are 2 main reasons for a certain 		  coding style:</p>
<ol>
<li>Develop clean and readable code, so when 		    someone else has to dig through it, he can pick it 		    up rather quickly. And more important when you get 		    back to some old code you have written a year ago, 		    you don&#8217;t start thinking &#8220;I can&#8217;t remember being 		    that wasted&#8230;&#8221;.</li>
<li>When working in team, it&#8217;s best that everybody 		    uses the same style so the code has a uniform 		    look.</li>
</ol>
<p>Since I develop most of my code on my own, I don&#8217;t 		  have to consider the second reason. And since I am 		  very stuburn, I am not going to take over someone 		  elses style. That&#8217;s why my style is completely 		  optimized to produce clean and readable code.</p>
<h2>The Basic Rules</h2>
<p>I tried to capture the most important aspects of 		  coding style in the following rules.</p>
<ol>
<li>All should be as understandable as 		    possible.</li>
<li>All should be as readable as possible, except 		    when it would conflict with the previous rule.</li>
<li>All should be as simple as possible, except when 		    it would conflict with the previous rules.</li>
</ol>
<p>The best way to look at these rules is make everything 		  as simple as possible, unless understandability or 		  readability suffer. Or to quote Albert Einstein:</p>
<blockquote><p>Make everything as simple as possible, but not 		  simpler.</p></blockquote>
<p>As a programmer you must always try to respect the 		  above rules, even if you don&#8217;t follow my style of 		  coding.</p>
<p>Writing understandable and readable code became 		  possible with the birth of modern programming 		  languages. The days when programming was entirely 		  done in assembly are long past us. Therefore my 		  style tries to be as closely to our natural language 		  as possible. You can almost say my code reads like a 		  book. This is probably also the reason why my code 		  is badly documented. I hardly document at all! I 		  even consider documenting as &#8220;bad&#8221; (and not in the 		  cool sense of the word). Only when I do something 		  weird I add a comment to explain why. In my humble 		  opinion, comments should never say what your code 		  does, let your code say what it does.</p>
<blockquote><p>Any fool can write code that a computer can 		  understand.  Good programmers write code that humans 		  can understand.</p>
<div>Martin Fowler</div>
</blockquote>
<h2>Identifiers</h2>
<p>Let&#8217;s start with the most important topic of coding 		  style: identifiers. All identifiers and the rest of 		  your code and comments should be written in 		  English. It is not unusual that software projects 		  shift from one person to another, from one company 		  to another one, located at the opposite side of the 		  world. So since you never know where your code is 		  going to be next, write all in English.</p>
<h2>Variables</h2>
<p>Variable names should be all lowercase with the 		  words separated by underscores. It resembles our 		  natural writing the most and therefore it is the 		  most readable. The underscores just replace the 		  spaces in our normal way of writing. A variable 		  called &#8220;RedPushButton&#8221; cannot be read as easely and 		  as fast as &#8220;red_push_button&#8221;, thrust me.</p>
<p>If you want the variables to be understandable, you 		  must give them obvious names. It is clear that 		  variables all represent some kind of &#8220;object&#8221; or 		  &#8220;value&#8221;, so name them accordingly. Please don&#8217;t 		  waste your time with jkuidsPrefixing vndskaVariables 		  ncqWith ksldjfTheir nmdsadType because it just isn&#8217;t 		  understandable or clean. If you have a variable 		  &#8220;age&#8221; it&#8217;s clear that it&#8217;s an int or unsigned 		  short. If it is &#8220;filename&#8221;, well then it must be a 		  string. Easy! Sometimes for some variables it is 		  more understandable if you include the type in it, 		  for example for gui buttons like &#8220;play_button&#8221; or 		  &#8220;cancel_button&#8221;.</p>
<p>There are some pre- and postfixes that can increase 		  the readability of your variables. Here follows a 		  list of the most common ones:</p>
<dl>
<dt> is_, has_ </dt>
<dd> Use these for all boolean values so there can be 		    no mistake about their type. It also fits nicely 		    in if statements. </dd>
<dt> the_ </dt>
<dd> Start all global variables with &#8220;the_&#8221;, which 		    makes it very clear that there is only one. </dd>
<dt> _count </dt>
<dd> Use _count to represent the number of 		    elements. Don&#8217;t use plural like &#8220;bullets&#8221; 		    instead of &#8220;bullet_count&#8221;, as plural will 		    represent arrays. </dd>
</dl>
<p>Arrays or other variables that represent lists must 		  be written in plural, like enemies, walls and 		  weapons. However, you don&#8217;t have to do this for all 		  array types since some arrays don&#8217;t really represent 		  a list of items. Some examples of these are &#8220;char 		  filename[64]&#8221; or &#8220;byte buffer[128]&#8220;.</p>
<h2>Const or Final</h2>
<p>Consts or finals must always be written in 		  UPPERCASE, with the words separated by underscores 		  to make them readable, like MAX_CHILDREN, X_PADDING 		  or PI. This use is widespread and should be used to 		  avoid any confusion with normal variables.</p>
<p>You can use MAX and MIN in your constant names to 		  represent value limits.</p>
<h2>Types</h2>
<p>Types define the classification of variables. It is 		  a rather abstract term, so we cannot use the English 		  language as a reference on how to write them. But we 		  should definitely make an obvious distinction 		  between them and other identifiers. So for types, I 		  use UpperCamelCase. For every class, struct, enum and 		  other things you can put in front of your variable 		  declarations, use UpperCamelCase.</p>
<p>Name your types in such a way that you can use the 		  same name for generic variables, for example:</p>
<p><code>HelpWindow help_window;<br />
FileHeader file_header;<br />
Weapon weapons[ MAX_WEAPONS ];</code></p>
<h2>Program Flow</h2>
<h3>if, else if, else</h3>
<p>There are a few ways to write if statements. Let&#8217;s 		  start with the braces. There are 3 mayor ways to place 		  your braces:</p>
<pre>    if(condition)

    if (condition)

    if( condition )</pre>
<p>I have never seen an English text where braces are 		placed like the first example, so why should we code 		like that?  The words are just not properly separated. 		The second example puts the braces with the condition 		instead of the if statement, while the braces are 		actually part of the if statement and not the 		condition, so the last example is the best. The last 		one also has the advantage that one has a better 		overview over the braces structure.</p>
<pre>    if (!((age &gt; 12) &amp;&amp; (age &lt; 18)))

    if( !((age &gt; 12) &amp;&amp; (age &lt; 18)) )</pre>
<p>Personally I would write this code differently, but 		it&#8217;s just to show you an example.</p>
<p>Now what to do with the curled braces? Don&#8217;t use 		  them! Unfortunately C, C++, Java or C# don&#8217;t allow 		  this, only Python does. So we can&#8217;t just drop them, 		  but what we can do is place our braces so it looks 		  like a Python program, simple and clean:</p>
<pre>    if( condition ) {
        statements;
    }
    else if( condition ) {
        statements;
    }
    else {
        statements;
    }</pre>
<p>When conditions get too long, you&#8217;ll have to split 		  the line. Try to split it up before an operator and 		  where conditions are leastly related. Align the next 		  line with the previous one and use indentation to 		  reveal the nested structure. Don&#8217;t put the curled 		  brace right behind the condition, but in this case 		  put it on the next line to make the subblock clear.</p>
<pre>    if( (current_mayor_version &lt; MIN_MAYOR_VERSION)
        || (current_mayor_version == MIN_MAYOR_VERSION
            &amp;&amp; current_minor_version &lt; MIN_MINOR_VERSION) )
    {
        update();
    }</pre>
<p>When there is only one statement after the if 		  condition, you can skip the curled braces, but make 		  sure you put the statement on the next line, unless 		  it is a return or a break.</p>
<pre>    if( bullet_count == 0 )
        reload();

    if( a &lt; 0 ) return;</pre>
<h3>while</h3>
<p>While loops are written the same as if structures. I 		  use 4 spaces for every indentation.</p>
<pre>    while( condition ) {
        statements;
    }</pre>
<p>For do-while loops, put the while at the same line 		  as the closing bracket. This way there is no 		  confusion if it is a while at the end or the 		  beginning of a subblock.</p>
<pre>    do {
        statements;
    } while( condition )</pre>
<h3>for</h3>
<p>for-loops&#8217; one and only purpose in life is 		  iteration. It&#8217;s what they do! for-loops can always 		  be replaced with while-loops, but please don&#8217;t do 		  that. When you iterate over some elements, try using 		  &#8216;for&#8217;, and if it really doesn&#8217;t work out, use a 		  &#8216;while&#8217;. The &#8216;for&#8217; structure is pretty straight 		  forward:</p>
<pre>    for( int i = 0; i &lt; MAX_ELEMENTS; i++ ) {
        statements;
    }</pre>
<p>Use i, j, k, l, m for iterating over numbers and 		  &#8216;it&#8217; for iterating over objects.</p>
<h3>switch</h3>
<p>Switch statements have a similar structure to if and 		  while structures. The only thing you have to 		  consider is the extra indentation. Also leave an 		  extra space right behind the break.</p>
<pre>    switch( variable ) {
        case 0:
            statements;
            break;

        case 1:
            statements;
            break;

        default:
            break;
    }</pre>
<h2>Functions</h2>
<p>Functions do things, and their name should make this 		  clear. Therefore, always include a verb in it, no 		  exceptions! Use the same naming as with variables, 		  this means all lowercase words separated by 		  underscores. This allows you to make nice little 		  sentences in your code that everyone can understand.</p>
<p>Also make sure the function does what the name says 		  it does, no more, no less. So if you have a function 		  called &#8220;load_resources&#8221;, make sure it only loads 		  resources and doesn&#8217;t do any other init 		  stuff. Sometimes you get tempted by quickly 		  initializing things in the load_resources because 		  you already call it from a higher level, but this 		  will only get you into trouble later. My deWiTTERS 		  Style uses very few comments, so a function should 		  definitely do what it&#8217;s name says it does. And when 		  a function returns something, make sure it is clear 		  from it&#8217;s name what it returns.</p>
<p>Some functions come in &#8220;yin and yang&#8221; pairs, and you 		  should be consistent with your naming. Some examples 		  are get/set, add/remove, insert/delete, 		  create/destroy, start/stop, increment/decrement, 		  new/old, begin/end, first/last, up/down, next/prev, 		  open/close, load/save, show/hide, enable/disable, 		  resume/suspend, etc.</p>
<p>Here follows a simple function call. Use a space 		  right after the opening brace and right before the 		  closing brace, just as with if structures. Also 		  leaver a space right after the comma, like done in 		  the English language.</p>
<pre>    do_something( with, these, parameters );</pre>
<p>When function calls get too long, you&#8217;ll 		  have to split it up in several lines. Align the next 		  lines with the previous so the structure gets 		  obvious, and break after the comma.</p>
<pre>    HWND hwnd = CreateWindow( "MyWin32App", "Cool application",
                              WS_OVERLAPPEDWINDOW,
                              my_x_pos, my_y_pos,
                              my_width, my_height
                              NULL, NULL, hInstance, NULL );</pre>
<h3>Definition</h3>
<p>Here follows an example of a function definition:</p>
<pre>    bool do_something_today( with, these, parameters ) {
        get_up();
        go_to( work, car );
        work();
        go_to( home, car );
        sleep();

        return true;
    }</pre>
<p>Make sure your functions don&#8217;t get too long. Or to 		quote Linus:</p>
<blockquote><p>The maximum length of a function is inversely 		  proportional to the complexity and indentation level 		  of that function. So, if you have a conceptually 		  simple function that is just one long (but simple) 		  case-statement, where you have to do lots of small 		  things for a lot of different cases, it&#8217;s ok to have 		  a longer function.  		  However, if you have a complex function, and you 		  suspect that a less-than-gifted first-year 		  high-school student might not even understand what 		  the function is all about, you should adhere to the 		  maximum limits all the more closely. Use helper 		  functions with descriptive names (you can ask the 		  compiler to in-line them if you think it&#8217;s 		  performance-critical, and it will probably do a 		  better job of it that you would have done).</p></blockquote>
<h2>Classes</h2>
<p>For the naming of classes I use the same 		  UpperCamelCase as for types. Don&#8217;t bother putting a 		  &#8216;C&#8217; as a prefix for every class, it&#8217;s just a waste of 		  bytes and time.</p>
<p>As for everything, give classes clear and obvious 		  names. So if a class is a child of class &#8220;Window&#8221;, 		  name it &#8220;MainWindow&#8221;.</p>
<p>When creating a new class, remember that 		  everything starts from data structures.</p>
<blockquote><p>Data dominates. If you&#8217;ve chosen the right data 		  structures and organized things well, the algorithms 		  will almost always be self-evident. Data structures, 		  not algorithms, are central to programming.</p>
<div>Fred Brooks</div>
</blockquote>
<h3>Inheritance</h3>
<p>&#8220;Is a&#8221; relationship should be modeled by inheritance, 		  &#8220;has a&#8221; should be modeled by containment. Make sure 		  you don&#8217;t overuse inheritance, it is a great 		  technique, but only when applied properly.</p>
<h3>Members</h3>
<p>You should definitely make a distinction between 		  members and normal variables. If you don&#8217;t do this, 		  you&#8217;ll regret it later on. Some 		  possibilities to name them are m_Member or 		  fMember. I prefer to use my_member for non static 		  members and our_member for statics. This way you get 		  nice sentences in you method bodies like</p>
<pre>    if( my_help_button.is_pressed() ) {
        our_screen_manager.go_to( HELP_SCREEN );
    }</pre>
<p>For the rest everything that applies to variable 		naming also applies to members. There is one problem 		that I was unable to fix as of yet, and that is with boolean 		members. Remember that boolean values must always have 		&#8220;is&#8221; or &#8220;has&#8221; in them. When combining this with &#8220;my_&#8221; 		you get crazy stuff like &#8220;my_is_old&#8221; and 		&#8220;my_has_children&#8221;. I haven&#8217;t found the perfect 		solution for this yet, so if you have any suggestions, 		please leave a comment below this post!</p>
<p>You shouldn&#8217;t declare members of a class as 		  public. Sometimes it seems quicker to 		  implement, and therefore better, but oh boy are you 		  wrong (as I was many times before). You should 		  pass through public methods to get to the members of 		  a class.</p>
<h3>Methods</h3>
<p>Everything that applies to functions also applies to 		  methods, so always include a verb in the name. Make 		  sure you don&#8217;t include the name of the class in your 		  method names.</p>
<h2>Code Structure</h2>
<p>Align similar lines to give your code a better overview, like:</p>
<pre>    int object_verts[6][3] = {
        {-100,  0, 100}, {100, 0,  100}, { 100, 0, -100},
        {-100, 11, 100}, (100, 0, -100}, {-100, 0, -100}
    };

    RECT rect;
    rect.left   = x;
    rect.top    = y;
    rect.right  = rect.left  + width;
    rect.bottom = rect.right + height;</pre>
<p>Never put multiple statements on the same line 		  unless you have a good reason for it. One or those reason 		  could be that simular lines can be put right after 		  each other for clarity, like:</p>
<pre>    if( x &amp; 0xff00 ) { exp -= 16; x &gt;&gt;= 16; }
    if( x &amp; 0x00f0 ) { exp -=  4; x &gt;&gt;=  4; }
    if( x &amp; 0x000c ) { exp -=  2; x &gt;&gt;=  2; }</pre>
<p>Related variables of the same type can be declared 		  in a common statement. This makes the code more compact and provides a 		  nicer overview. But never declare unrelated variables in 		  the same statement!</p>
<pre>    int x, y;
    int length;</pre>
<h2>Namespaces, packages</h2>
<p>Namespaces or packages 		should be written in lower case, without any 		underscores. Use a namespace for every module or layer 		you write so that the different layers become clear in 		the code.</p>
<h2>Design</h2>
<p>When I start a project I don&#8217;t do that much upfront 		  design. I just have a global structure in my mind 		  and start coding. Code evolves, whether you like it 		  or not, so give it the chance to evolve.</p>
<p>Evolving code means reworking bad code, and after 		  some programming your code will turn bad. I use 		  following rules to keep a good structure in the 		  code.</p>
<ol>
<li> When a functions gets too big, divide the 		      problem in some smaller helper functions.</li>
<li> If a class contains too many members and 		      methods, split a part of the class up in a 		      helper class and include the helper class in 		      your main class (don&#8217;t use inheritance for 		      this!). Make sure your helper class doesn&#8217;t 		      reference or use the main class for anything.</li>
<li> When a module contains too many classes, divide 		      it up into more modules where the higer level 		      module make use of the lower level module.</li>
<li> When you are done implementing a feature or 		    fixing a bug, read over the entire files you have 		    changed to make sure everything is in the most 		    perfect state.</li>
</ol>
<p>Some projects may become big, very big. A way to 		  cope with this increasing complexity is splitting 		  your project up into different layers. In practice, 		  layers are implemented as namespaces. Lower layers 		  are used by the higher layers. So every layer 		  provides functionality to the above, and the topmost 		  provides functionality to the user.</p>
<h2>Files</h2>
<p>Files should be named after the class they 		  contain. Don&#8217;t put more than one class in a file, so 		  you know where to look when you search a specific 		  class. The directory structure should represent the 		  namespaces.</p>
<h3>.h file structure</h3>
<p>C or C++ header files show the interface of the 		  implementation. This is crucial knowledge when 		  designing the layout of a .h file. In a class, first 		  define the &#8220;public&#8221; interface that can be used by 		  other classes, then define all &#8220;protected&#8221; methods 		  and members. This way the most important information 		  for people using the class is shown first. I don&#8217;t 		  use private methods or members so all members are 		  grouped at the bottom of the class declaration. This 		  way you have a quick overview of the contents of the 		  class at the bottom. Group the methods together by 		  their meaning.</p>
<pre>    /*
     * license header
     */

    #ifndef NAMESPACE_FILENAME_H
    #define NAMESPACE_FILENAME_H

    #include &lt;std&gt;

    #include "others.h"

    namespace dewitters {

        class SomeClass : public Parent {
            public:
                Constructor();
                ~Destructor();

                void public_methods();

            protected:
                void protected_methods();

                int     my_fist_member;
                double  my_second_member;

                const static int MAX_WIDTH;
        };

        extern SomeClass the_some_class;
    }

    #endif</pre>
<h3>.java .cs file structure</h3>
<p>.java or .cs files don&#8217;t provide an interface to the 		  class, they just contain the implementation. Since 		  data structures are more important than algorithms, 		  define your members before your methods. This way 		  when you browse through the code, you have a quick 		  impression of the class through its data members. 		  Simular methods should be grouped together.</p>
<p>Here follows a sketchy overview of a .java or .cs 		  file:</p>
<pre>    /*
     * license header
     */
    package com.dewitters.example;

    import standard.modules.*;

    import custom.modules.*;

    class SomeClass extends Parent {
        public final int MAX_WIDTH = 100;

        protected int     my_first_member;
        protected double  my_second_member;

        Constructor() {
        }

        Methods() {
        }
    }</pre>
<h2>Jokes</h2>
<p>Some people like to put little jokes in their code, 		  while others hate this kind of funny stuff. In my 		  opinion you can use them as long as the joke doesn&#8217;t 		  interfere with the readability of the code or 		  execution of the program.</p>
<p><a name="vs"></a></p>
<h2>deWiTTERS Style vs. others</h2>
<p>Here I will present you with some live action 		  code. I stole some code from others and rewrote it 		  to my style. Decide for yourself if my style is 		  better or not. In my opinion you can read faster 		  through my code since it is shorter, and all 		  identifiers are carefully named.</p>
<p>If you think you have seen code that can beat the 		  crap out of my style, leave a comment below this post,  		  and I will write it in the most extraordinary 		  &#8216;deWiTTERS&#8217; style, and post it here.</p>
<h3>Indian Hill C Style</h3>
<pre>/*
 *	skyblue()
 *
 *	Determine if the sky is blue.
 */

int			/* TRUE or FALSE */
skyblue()

{
	extern int hour;

	if (hour &lt; MORNING || hour &gt; EVENING)
		return(FALSE);	/* black */
	else
		return(TRUE);	/* blue */
}

/*
 *	tail(nodep)
 *
 *	Find the last element in the linked list
 *	pointed to by nodep and return a pointer to it.
 */

NODE *			/* pointer to tail of list */
tail(nodep)

NODE *nodep;		/* pointer to head of list */

{
	register NODE *np;	/* current pointer advances to NULL */
	register NODE *lp;	/* last pointer follows np */

	np = lp = nodep;
	while ((np = np-&gt;next) != NULL)
		lp = np;
	return(lp);
}</pre>
<h4>Rewritten to deWiTTERS Style:</h4>
<pre>bool sky_is_blue() {
    return the_current_hour &gt;= MORNING &amp;&amp; the_current_hour &lt;= EVENING;
}

Node* get_tail( Node* head ) {
    Node* tail;
    tail = NULL;

    Node* it;
    for( it = head; it != NULL; it = it-&gt;next ) {
        tail = it;
    }

    return tail;
}</pre>
<h3>&#8220;Commenting Code&#8221; from Ryan Campbell</h3>
<pre>/*
 * Summary:     Determine order of attacks, and process each battle
 * Parameters:  Creature object representing attacker
 *              | Creature object representing defender
 * Return:      Boolean indicating successful fight
 * Author:      Ryan Campbell
 */
function beginBattle(attacker, defender) {
    var isAlive;    // Boolean inidicating life or death after attack
    var teamCount;  // Loop counter

    // Check for pre-emptive strike
    if(defender.agility &gt; attacker.agility) {
        isAlive = defender.attack(attacker);
    }

    // Continue original attack if still alive
    if(isAlive) {
        isAlive = attacker.attack(defender);
    }

    // See if any of the defenders teammates wish to counter attack
    for(teamCount = 0; teamCount &lt; defender.team.length; i++) {
        var teammate = defender.team[teamCount];
        if(teammate.counterAttack = 1) {
            isAlive = teammate.attack(attacker);
        }
    }   

    // TODO: Process the logic that handles attacker or defender deaths

    return true;
} // End beginBattle</pre>
<h4>Rewritten to deWiTTERS Style:</h4>
<pre>function handle_battle( attacker, defender ) {
    if( defender.agility &gt; attacker.agility ) {
        defender.attack( attacker );
    }

    if( attacker.is_alive() ) {
        attacker.attack( defender );
    }

    var i;
    for( i = 0; i &lt; defender.get_team().length; i++ ) {
        var teammate = defender.get_team()[ i ];
        if( teammate.has_counterattack() ) {
            teammate.attack( attacker );
        }
    }

    // TODO: Process the logic that handles attacker or defender deaths
}
</pre>
<p style="text-align: left;">Koen Witters</p>
<p style="text-align: left;"><a href="http://twitter.com/koonsolo"><em>Follow me on twitter</em></a></p>
 <img src="http://dev.koonsolo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=21" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://www.koonsolo.com/news/dewitters-tao-of-coding/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
