<?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>code-spot &#187; Tutorial</title>
	<atom:link href="http://code-spot.co.za/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://code-spot.co.za</link>
	<description>a programming blog</description>
	<lastBuildDate>Sun, 27 Feb 2011 07:18:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Poisson Disk Sampling Example Code</title>
		<link>http://code-spot.co.za/2010/04/07/poisson-disk-sampling-example-code/</link>
		<comments>http://code-spot.co.za/2010/04/07/poisson-disk-sampling-example-code/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 08:57:27 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[poisson disk]]></category>
		<category><![CDATA[procedural texture]]></category>
		<category><![CDATA[sampling]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=806</guid>
		<description><![CDATA[I decided to put the Poisson disk sampling code here for download since the site that hosted it is down. The code accompanies the tutorial on Dev.Mag: Poisson Disk Sampling. Download poisson_disk_java.zip (184 KB) poisson_disk_python.zip (912 KB) poisson_disk_ruby.zip (59 KB) Related posts:Python Image Code A simple texture algorithm – faster code and more results A [...]


Related posts:<ol><li><a href='http://code-spot.co.za/python-image-code/' rel='bookmark' title='Permanent Link: Python Image Code'>Python Image Code</a></li>
<li><a href='http://code-spot.co.za/2008/12/15/a-simple-texture-algorithm-faster-code-and-more-results/' rel='bookmark' title='Permanent Link: A simple texture algorithm – faster code and more results'>A simple texture algorithm – faster code and more results</a></li>
<li><a href='http://code-spot.co.za/2008/11/14/a-simple-procedural-texture-algorithm-more-results-and-code/' rel='bookmark' title='Permanent Link: A Simple Procedural Texture Algorithm &#8211; More Results and Code'>A Simple Procedural Texture Algorithm &#8211; More Results and Code</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-817" title="poisson" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/poisson3.png" alt="poisson" width="142" height="142" />I decided to put the Poisson disk sampling code here for download since the site that hosted it is down. The code accompanies the tutorial on Dev.Mag: <a href="http://www.devmag.org.za/articles/55-POISSON-DISK-SAMPLING/">Poisson Disk Sampling</a>.</p>
<h2>Download</h2>
<table border="0">
<tbody>
<tr>
<td><a href="http://www.code-spot.co.za/downloads/poisson/poisson_disk_java.zip">poisson_disk_java.zip</a> (184 KB)<br />
<a href="http://www.code-spot.co.za/downloads/poisson/poisson_disk_python.zip"> poisson_disk_python.zip</a> (912 KB)<br />
<a href="http://www.code-spot.co.za/downloads/poisson/poisson_disk_ruby.zip"> poisson_disk_ruby.zip</a> (59 KB)</td>
</tr>
</tbody>
</table>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/python-image-code/' rel='bookmark' title='Permanent Link: Python Image Code'>Python Image Code</a></li>
<li><a href='http://code-spot.co.za/2008/12/15/a-simple-texture-algorithm-faster-code-and-more-results/' rel='bookmark' title='Permanent Link: A simple texture algorithm – faster code and more results'>A simple texture algorithm – faster code and more results</a></li>
<li><a href='http://code-spot.co.za/2008/11/14/a-simple-procedural-texture-algorithm-more-results-and-code/' rel='bookmark' title='Permanent Link: A Simple Procedural Texture Algorithm &#8211; More Results and Code'>A Simple Procedural Texture Algorithm &#8211; More Results and Code</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2010/04/07/poisson-disk-sampling-example-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guerrilla Tool Development</title>
		<link>http://code-spot.co.za/2009/10/24/guerrilla-tool-development/</link>
		<comments>http://code-spot.co.za/2009/10/24/guerrilla-tool-development/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 16:18:45 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[ai editor]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[level editor]]></category>
		<category><![CDATA[tool development]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=750</guid>
		<description><![CDATA[Tools for editing game levels and AI for your own games are nice to have, but it is not always practical to implement these for small projects, nor is it affordable to buy them off-the-shelf or bundled with expensive middleware. In the Dev.Mag article Guerrilla Tool Development, I give some ideas for getting some useful [...]


Related posts:<ol><li><a href='http://code-spot.co.za/about-me/' rel='bookmark' title='Permanent Link: About Me'>About Me</a></li>
<li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="border-right: 0px; border-top: 0px; display: inline; margin: 0px 10px 0px 0px; border-left: 0px; border-bottom: 0px" title="guerrilla_tools" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/guerrilla_tools1.png" border="0" alt="guerrilla_tools" width="142" height="142" align="left" /> Tools for editing game levels and AI for your own games are nice to have, but it is not always practical to implement these for small projects, nor is it affordable to buy them off-the-shelf or bundled with expensive middleware.</p>
<p>In the Dev.Mag article <a href="http://devmag.org.za/2009/10/23/guerrilla-tool-development/">Guerrilla Tool Development</a>, I give some ideas for getting some useful tools on a tight budget. Check it out!</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/about-me/' rel='bookmark' title='Permanent Link: About Me'>About Me</a></li>
<li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/10/24/guerrilla-tool-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>15 Steps to Implement a Neural Net</title>
		<link>http://code-spot.co.za/2009/10/08/15-steps-to-implemented-a-neural-net/</link>
		<comments>http://code-spot.co.za/2009/10/08/15-steps-to-implemented-a-neural-net/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 15:02:26 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[artificial intelligence]]></category>
		<category><![CDATA[Matlab]]></category>
		<category><![CDATA[neural network]]></category>
		<category><![CDATA[Octave]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[pattern recognition]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sampling]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=655</guid>
		<description><![CDATA[(Original image by Hljod.Huskona / CC BY-SA 2.0). I used to hate neural nets. Mostly, I realise now, because I struggled to implement them correctly. Texts explaining the working of neural nets focus heavily on the mathematical mechanics, and this is good for theoretical understanding and correct usage. However, this approach is terrible for the poor implementer, [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/' rel='bookmark' title='Permanent Link: 5 Tips for Prototyping Slow Algorithms'>5 Tips for Prototyping Slow Algorithms</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="neuron" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/neuron1.jpg" border="0" alt="neuron" width="500" height="332" /></p>
<p>(<a href="http://www.flickr.com/photos/lorelei-ranveig/2294885420/">Original image</a> by <a rel="cc:attributionURL" href="http://www.flickr.com/photos/lorelei-ranveig/">Hljod.Huskona</a> / <a rel="license" href="http://creativecommons.org/licenses/by-sa/2.0/">CC BY-SA 2.0</a>).</p>
<p>I used to hate neural nets. Mostly, I realise now, because I struggled to implement them correctly. Texts explaining the working of neural nets focus heavily on the mathematical mechanics, and this is good for theoretical understanding and correct usage. However, this approach is terrible for the poor implementer, neglecting many of the details that concern him or her.</p>
<p>This tutorial is an implementation guide. It is not an explanation of how or why neural nets work, or when they should or should not be used. This tutorial will tell you step by step how to implement a very basic neural network. It comes with a simple example problem, and I include several results that you can compare with those that you find.</p>
<p><span id="more-655"></span></p>
<p>I tried to make the design as straightforward as possible. The training algorithm is simple backpropagation. There are no hidden layers (I will treat that in an upcoming tutorial), no momentum, no adaptive learning rates, and no sophisticated stopping conditions. Those are, in a sense, easy to add once you have a working neural net against which you can benchmark more elaborate designs.</p>
<p>To keep the implementation simple, I did not bother with optimisation. This too can easily be addressed once a working neural net is in place against which you can verify correctness and measure performance improvements.</p>
<p>The brief introduction below is a very superficial explanation of a neural net; it is included mostly to establish terminology and help you map it to the concepts that are explained in more detail in other texts.</p>
<h2>Preliminary remarks and overview</h2>
<h3>What we are doing</h3>
<p>The problem we are trying to solve is this: we have some measurements (features of an object), and we have a good idea that these features might tell us in which class the object belongs. For example, if we are dealing with fruit, knowing the size, colour, and “roughness” of the skin, we might deduce which type the fruit is. Of course, we want a <em>program </em>for this.</p>
<p>Now in heaven, there is a function for exactly that task – we give the function the features, and it spits out the class.</p>
<p>Down here on earth, we are not so lucky (well, not for most problems anyway). So instead, we have to do with some approximation. A neural net is one possibility – there are also others. A neural net (one without any hidden layers) is parameterised by a weight matrix. Different problems in general have different weight matrices. To solve our problem, we need to find a suitable matrix.</p>
<p>If both our set of known samples and the problem itself are reasonable, we might expect to find such a matrix. But not directly – we have to use some kind of iterative scheme – we have to “train” our neural net. We use some of the known samples for this.</p>
<p>Behind the scenes, the weight matrix and the feature vector are combined using some matrix operations to give the output vector, which is converted to a class. The mathematical details of this can be found <a href="http://www.mth.kcl.ac.uk/courses/guide.pdf" class="broken_link">elsewhere</a> (<a href="http://www.learnartificialneuralnetworks.com/backpropagation.html">more</a>).</p>
<p>After we have trained the neural net, we can use it in an application to classify objects that we may or may not have encountered before. Generally, the training and application programs are separate. The training program is the difficult part; most of the tutorial deals with training.</p>
<p>It is common to divide the known samples in three sets, called the training set, validation set, and test set, typically divided in the ratio 50%, 25%, and 25%. The training set is used to update the weights iteratively; the validation set is used to stop the training algorithm, and the test set is used to estimate how well our trained neural net will do in the wild.</p>
<p>Each iteration of the training algorithm is called, quite poetically, an <em>epoch</em>. Many different things affect the number of epochs we will need to train the neural net: the problem complexity, how we scale our updates, and how the weight matrix has been initialised.</p>
<p>We can control the speed with a parameter called the learning rate. In general, higher learning rate means faster learning (although, when it is set too high, the network might become unstable and not learn at all).</p>
<h3>Representation</h3>
<p>We usually represent the features (our measurements) as a vector of numbers, like this:</p>
<p>[0.01, 1.07, 3.60]</p>
<p>In cases of non-numeric values, we convert whatever we have to numbers with some scheme. For instance, when dealing with colours, we might want to use RGB values, or we might want to make a list of colours (red, yellow, green, etc.), assign a number to each of these labels, and use the corresponding number.</p>
<p>Classes, usually not being numbers, are similarly treated: we assign a number (often arbitrarily) to each class, and use that in our computations. For the actual training, however, we use an output vector. The output vector has a 1 in the position of the class number, and 0 everywhere else.</p>
<p>Thus, if we are dealing with three classes of fruit (apple, pear, banana), and number the classes 1, 2, and 3 respectively, we will have the following output vectors:</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="135" valign="top"><strong>Class</strong></td>
<td width="142" valign="top"><strong>Class Number</strong></td>
<td width="121" valign="top"><strong>Output Vector</strong></td>
</tr>
<tr>
<td width="135" valign="top">Apple</td>
<td width="142" valign="top">1</td>
<td width="121" valign="top">1 0 0</td>
</tr>
<tr>
<td width="135" valign="top">Pear</td>
<td width="142" valign="top">2</td>
<td width="121" valign="top">0 1 0</td>
</tr>
<tr>
<td width="135" valign="top">Banana</td>
<td width="155" valign="top">3</td>
<td width="153" valign="top">0 0 1</td>
</tr>
</tbody>
</table>
<p>It is convenient to put all the inputs of a set together in a single matrix, where each row is a sample. Similarly, outputs and classes are also put into matrices, with input sample in a row (say row number <em>n</em>) corresponds to output sample in row <em>n</em>, and also the class in row <em>n</em>.</p>
<p>The implementation below makes use of high-level matrix operations. This avoids many of the errors that can creep in loop-dense code. The following table will give dimensions of all the matrixes involved; this will be helpful during implementation (especially for assert statements). The numbers are given in terms of the number of inputs (features) of the problem, the number of outputs.</p>
<table border="0" cellspacing="0" cellpadding="2" width="490">
<tbody>
<tr>
<td width="263" valign="top"><strong>Matrix</strong></td>
<td width="113" valign="top"><strong>Rows</strong></td>
<td width="112" valign="top"><strong>Columns</strong></td>
</tr>
<tr>
<td width="256" valign="top">input vector of a single sample</td>
<td width="117" valign="top">1</td>
<td width="115" valign="top">input_count</td>
</tr>
<tr>
<td width="251" valign="top">output vector of a single sample</td>
<td width="120" valign="top">1</td>
<td width="117" valign="top">output_count</td>
</tr>
<tr>
<td width="248" valign="top">class vector of a single sample</td>
<td width="122" valign="top">1</td>
<td width="119" valign="top">1</td>
</tr>
<tr>
<td width="245" valign="top">input matrix of training set</td>
<td width="124" valign="top">training_count</td>
<td width="120" valign="top">input_count</td>
</tr>
<tr>
<td width="243" valign="top">output matrix of training set</td>
<td width="125" valign="top">training_count</td>
<td width="121" valign="top">output_count</td>
</tr>
<tr>
<td width="242" valign="top">class vector of training set</td>
<td width="126" valign="top">training_count</td>
<td width="121" valign="top">1</td>
</tr>
<tr>
<td width="242" valign="top">bias vector of training set</td>
<td width="126" valign="top">training_count</td>
<td width="121" valign="top">1</td>
</tr>
<tr>
<td width="242" valign="top">net vector of single sample</td>
<td width="126" valign="top">1</td>
<td width="121" valign="top">output_count</td>
</tr>
<tr>
<td width="242" valign="top">weights matrix</td>
<td width="126" valign="top">input_count + 1</td>
<td width="121" valign="top">output_count</td>
</tr>
<tr>
<td width="242" valign="top">weights delta matrix</td>
<td width="126" valign="top">input_count + 1</td>
<td width="121" valign="top">output_count</td>
</tr>
<tr>
<td width="242" valign="top">error vector</td>
<td width="126" valign="top">1</td>
<td width="121" valign="top">output_count</td>
</tr>
<tr>
<td width="242" valign="top">delta (sensitivity vector)</td>
<td width="126" valign="top">1</td>
<td width="121" valign="top">output_count</td>
</tr>
</tbody>
</table>
<h3>Overview</h3>
<p>The basic idea of the training algorithm is the following:</p>
<p>First we load in the data: the training samples, the validation samples, and the test samples.</p>
<p>Then we start to train: we run the backpropagation algorithm on random samples. After each iteration, we see how our network is doing so far (on the validation set), and then we decide whether to keep training or not.</p>
<p>After we stopped, we do a final evaluation of our network on the test set – this gives us an indication of whether the neural net will generalise well to samples not originally in the training set.</p>
<p>After we have found a weight matrix that we can live with, we cfan incorporate this in the application were we need the functionality.</p>
<p>The training program has x functions:</p>
<ul>
<li>train</li>
<li>load data</li>
<li>feed-forward</li>
<li>evaluate network</li>
<li>backpropagation</li>
<li>output to class</li>
<li>class to output</li>
<li>activation</li>
<li>activation derivative</li>
</ul>
<p>The application program uses these functions:</p>
<ul>
<li>feed-forward</li>
<li>output vector to class</li>
</ul>
<h2>Implementation</h2>
<h3>1. Gather the necessary libraries (or write them)</h3>
<p>You will need the following libraries:</p>
<ul>
<li>A library that supports matrix algebra; and</li>
<li>A library that plots graphs (x versus y).</li>
</ul>
<p>If you can’t find a matrix library for your implementation language, then you can write a simple library yourself. Since neural nets do not require matrix inverses or long chains of matrix products, you need not worry (much) about numerical stability, thus the implementation is straightforward.</p>
<p>The implementation needs to support the following matrix operations:</p>
<ul>
<li>matrix transposition;</li>
<li>matrix addition;</li>
<li>matrix multiplication with a scalar;</li>
<li>ordinary matrix multiplication;</li>
<li>Hadamard multiplication (component-wise multiplication);</li>
<li>Kronecker multiplication (only necessary for between row and column vectors); and</li>
<li>horizontal matrix concatenation.</li>
</ul>
<p>The first few operations are standard matrix operations, but you might be less familiar with the last three. (Also check out the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Matrix_multiplication">matrix multiplication</a> – it covers all the types of multiplication mentioned here.)</p>
<p>Hadamard multiplication of matrices is defined for two matrices of equal dimensions. Each component of the new matrix is the product of corresponding components in the two multiplicands, that is:</p>
<pre>Z[i][j] = X[i][j] * Y[i][j]</pre>
<p>The Kronecker product of a row vector and column vector is defined as a matrix whose components are given by:</p>
<pre>Z[i][j] = X[0][i] * Y[j][0]</pre>
<p>It is possible to define the product for arbitrary matrices, but we don’t need it.</p>
<p>The horizontal concatenation combines two matrices with the same number of rows. For example, the matrices A and B below will be concatenated to form the new matrix C:<br />
<img src='http://s.wordpress.com/latex.php?latex=A%3D%5Cbegin%7Bpmatrix%7D10%20%26%203%5C%5C4%20%26%205%5Cend%7Bpmatrix%7D%2C%5C%3AB%3D%5Cbegin%7Bpmatrix%7D6%20%26%208%20%26%202%5C%5C3%261%2610%5Cend%7Bpmatrix%7D%2C%5C%3AC%3D%5Cbegin%7Bpmatrix%7D10%20%26%203%266%20%26%208%20%26%202%5C%5C4%20%26%205%26%203%20%261%2610%5Cend%7Bpmatrix%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='A=\begin{pmatrix}10 &amp; 3\\4 &amp; 5\end{pmatrix},\:B=\begin{pmatrix}6 &amp; 8 &amp; 2\\3&amp;1&amp;10\end{pmatrix},\:C=\begin{pmatrix}10 &amp; 3&amp;6 &amp; 8 &amp; 2\\4 &amp; 5&amp; 3 &amp;1&amp;10\end{pmatrix}' title='A=\begin{pmatrix}10 &amp; 3\\4 &amp; 5\end{pmatrix},\:B=\begin{pmatrix}6 &amp; 8 &amp; 2\\3&amp;1&amp;10\end{pmatrix},\:C=\begin{pmatrix}10 &amp; 3&amp;6 &amp; 8 &amp; 2\\4 &amp; 5&amp; 3 &amp;1&amp;10\end{pmatrix}' class='latex' /></p>
<p>A simple implementation simply constructs a new matrix whose components are given by</p>
<pre>if j &lt; X_width
  Z[i][j] = X[i][j]
else
   Z[i][j] = Y[i, j – X_width]</pre>
<p>If no graph libraries are available, simply write a function that will output a tab-separated list of the input and output sequences to plot. You can then load or paste this into your favourite spreadsheet program to make the necessary plots.</p>
<h3>2. Implement Output and Class conversion functions</h3>
<p>This is very simple: implement a function that converts an output matrix to a class number vector, and another that converts a class number to an output vector.</p>
<p>For example, the output_to_class function will take the following matrix</p>
<p>1 0 0</p>
<p>0 1 0</p>
<p>0 0 1</p>
<p>1 0 0</p>
<p>0 0 1</p>
<p>and convert it to:</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>1</p>
<p>3</p>
<p>(The second function will convert the second matrix back to the first matrix).</p>
<h3>3. Implement a function to read in data files</h3>
<p>For this tutorial you can use the following three files:</p>
<ul>
<li>iris_training.dat</li>
<li>iris_validation.dat</li>
<li>iris_test.dat</li>
</ul>
<p>These three files contain samples from the <a href="http://en.wikipedia.org/wiki/Iris_flower_data_set">ICU iris dataset</a>, a simple and quite famous dataset. In each file, samples or contained in rows. Each row has seven entries, separated by tabs. The first four entries are features of irises (sepal length, sepal width, petal length, and petal width); the last three is the outputs denoting the species of iris (setosa, versicolor, and virginica). I have preprocessed the values a bit to get them in the appropriate ranges.</p>
<p>You must read in the data so that you can treat the inputs of each set as a single matrix; similarly for the outputs.</p>
<p>I find it useful to store all the data in a structure, like this:</p>
<ul>
<li>data_set
<ul>
<li>input_count</li>
<li>output_count</li>
<li>training_set
<ul>
<li>inputs</li>
<li>outputs</li>
<li>classes</li>
<li>count</li>
<li>bias</li>
</ul>
</li>
<li>validation_set
<ul>
<li>inputs</li>
<li>outputs</li>
<li>classes</li>
<li>count</li>
<li>bias</li>
</ul>
</li>
<li>test_set
<ul>
<li>inputs</li>
<li>outputs</li>
<li>classes</li>
<li>count</li>
<li>bias</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>This makes it more useful to send the data as parameters.</p>
<h3>4. Implement an activation function and its derivative</h3>
<p>The activation function must take in a matrix X, and return a matrix Y. Y is computed by applying a function component-wise to X. For now, use the hyperbolic tangent function:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20f%28x%29%20%3D%20%5Cdfrac%7B%5Ctanh%28x%29%20%2B%201%7D%7B2%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' f(x) = \dfrac{\tanh(x) + 1}{2}' title=' f(x) = \dfrac{\tanh(x) + 1}{2}' class='latex' /><br />
The activation function derivative must similarly take in a matrix X, and return a matrix Y. Y is computed by applying the derivative of the activation componentwise to X. The derivative of the function above is:<br />
<img src='http://s.wordpress.com/latex.php?latex=f%27%28x%29%20%3D%20%5Cdfrac%7B1%20-%20%5Ctanh%5E2%28x%29%7D%7B2%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f&#039;(x) = \dfrac{1 - \tanh^2(x)}{2}' title='f&#039;(x) = \dfrac{1 - \tanh^2(x)}{2}' class='latex' />
<h3>5. Implement the feed-forward function</h3>
<p>The function must take as arguments an input matrix, weight matrix, and a bias node matrix.</p>
<p>The function should return an output matrix, and a net matrix</p>
<p>These are computed as follows:</p>
<pre>net = mul(weights, horcat(inputs, bias))
output = activate(net)</pre>
<p>The bias matrix is a constant column vector of 1s with as many rows as the input matrix. This vector corresponds to the bias nodes. The implementation here is a bit clumsy, but for now, the approach used here minimises the potential for error.</p>
<h3>6. Implement a weight initialisation function</h3>
<p>This function must take in a maximum weight, a width and height, and return a matrix of the given width and height, randomly initialised in the range [-max_weight max_weight].</p>
<h3>7. Implement a function that evaluates the network error.</h3>
<p>The function must take in:</p>
<ul>
<li>an input matrix,</li>
<li>a weight matrix,</li>
<li>a target output matrix,</li>
<li>a target class matrix,</li>
<li>a bias matrix.</li>
</ul>
<p>The function must return the error e, and the classification error c.</p>
<p>To compute these, first compute the output matrix Z using the feed-forward function (you can ignore the net matrix).</p>
<pre>[output net] = feedforward(inputs, weights, bias)</pre>
<p>Now subtract the target output matrix from the output matrix, square the components, add together, and normalise:</p>
<pre>error = sum_all_components((target_outputs – outputs)^2) ...</pre>
<pre>   / (sample_count * output_count)</pre>
<p>From the output matrix, calculate the classes:</p>
<pre>classes = classes_from_output_vectors(outputs)</pre>
<p>Count the number of classes that corresponds with the target classes, and divide by the number of samples to normalise:</p>
<pre>c = sum_all_components(classes != target_classes)/sample_count</pre>
<p>(Here, our inequality returns a matrix of 0s and 1s, with 1s in positions where the corresponding components in classes and target_classes are not equal.)</p>
<h3>8. Implement a dummy backpropagation function</h3>
<p>The function should take in:</p>
<ul>
<li>An input matrix</li>
<li>A weight matrix</li>
<li>a learning rate (eta, as in the Greek letter)</li>
<li>a bias vector</li>
</ul>
<p>The function must return an updated weight matrix. For now, return W as is.</p>
<h3>9. Implement the train function</h3>
<p>The training function should take in three sets, the training_set, validation_set, and test_set. Implement a way to limit the maximum number of samples that will actually be used for training (you can also do his in the main program described in the next section). This is very helpful for debugging purposes (especially if you plan to later replace the backpropagation algorithm with something a little faster – and more complicated).</p>
<p>The function should return a weight matrix, and error values as floats.</p>
<p>Initialise a value plot_graphs to true. This is a debug flag, so it is appropriate to implement this as a macro if it is supported by the implementation language.</p>
<p>The function should initialise a weight matrix using initialise weights. For now, use a max_weight of 1/2.</p>
<p>The function should also construct three bias vectors bias_training, bias_validate, and bias_test. Each must contain only 1s, with as many rows as there are inputs in the training, validation and test sets respectively.</p>
<p>Implement a while loop that stops after 500 iterations. (We will change the while condition later to something else, so do not use a for loop).</p>
<p>Inside the loop, call the backpropagation algorithm. Use the training set inputs, the weights, (for now) a fixed learning rate of 0.1, and bias vector bias_train. Assign the result to weights.</p>
<p>Still inside the loop, call the network error function three times: one time for each of the training, validation, and test sets. Use the weight matrix, and the appropriate bias vector. Wrap these calls in an if-statement that tests for a value plot_graphs. (If your language supports it, you can use conditional compilation on the value of plot_graphs).</p>
<p>Store the errors in six arrays (error_train, classification_error_train, etc.), with the current epoch number as index.</p>
<p>After the loop, plot the six error arrays as a function of epoch number. Wrap this in an if-statement (or conditional compilation statement) that tests for the value plot_graphs.</p>
<p>Call the network error function again, on all three sets as before.</p>
<p>Return the weights, and the six errors.</p>
<h3>10. Implement the main training program</h3>
<p>The program should load in the sets (using the load_sets function), and pass these to the training algorithm.</p>
<h3>11. Run the program</h3>
<p>The important thing is that everything should run. You should see your error plots; at this stage they should be straight, horizontal lines. Because of the random weight initialisation, we cannot predict where these lines will lie (so do not be alarmed if they do not look exactly the same as below – as long as they are straight and horizontal).</p>
<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="backprop" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/backprop.png" border="0" alt="backprop" width="486" height="399" /></p>
<h3>12. Implement the backpropagation function</h3>
<p>You have already created the dummy function; now you can put in the actual calculations.</p>
<p>First, select a random sample.</p>
<p>Now, calculate the net matrix and output matrix using the feed-forward function.</p>
<pre>[output, net] = feedforward(random_sample, weights, bias)</pre>
<p>Calculate the error vector</p>
<pre>error_vector = target_outputs - outputs</pre>
<p>Calculate the sensitivity.</p>
<pre>delta = hammard(error_vector, activation_diff(net))</pre>
<p>The corresponding mathematical expression in the textbook might look like this:<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Cdelta_k%20%3D%20%28t_k%20-%20z_k%29%20f%27%28y_k%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\delta_k = (t_k - z_k) f&#039;(y_k)' title='\delta_k = (t_k - z_k) f&#039;(y_k)' class='latex' /></p>
<p>Calculate the weights delta:</p>
<pre>weights_delta = scalar_mul(eta, kronecker(transpose(outputs), delta))</pre>
<p>The corresponding mathematical expression in the textbook might look like this:<br />
<img src='http://s.wordpress.com/latex.php?latex=w_%7Bkj%7D%20%3D%20%5Ceta%20%28t_k%20-%20z_k%29%20f%27%28y_k%29y_j&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='w_{kj} = \eta (t_k - z_k) f&#039;(y_k)y_j' title='w_{kj} = \eta (t_k - z_k) f&#039;(y_k)y_j' class='latex' /></p>
<p>Update the weights:</p>
<pre>weights = add(weights, weights_delta)</pre>
<p>and return the matrix.</p>
<h3>13 Run the program (AGAIN)</h3>
<p>First, set the debug option to train on only one sample. The curve should like like this:</p>
<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="backprop3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/backprop3.png" border="0" alt="backprop3" width="486" height="398" /></p>
<p>Notice that the error curves are smooth, the training error rate goes to 0, and the other error rates go to 0.4, plus or minus – this depends on the initial weights. It will also be different if you use a sample other than the first.</p>
<p>If your curve looks right, change the debug option to train on all samples. Your error curves should now look something like this:</p>
<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="backprop2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/backprop2.png" border="0" alt="backprop2" width="486" height="398" /></p>
<p>The important feature of the error curves is that they should steadily descent on average. If your curve does not resemble the one shown here; there is a mistake in your implementation. It is often helpful to limit the training set to a single sample (thereby eliminating the randomisation of sampling during training) to see what is going on.</p>
<p>Although the errors often follow the relationship training &lt; validation &lt; test, this is not always the case, so do not be alarmed if this is not true on a run (You can see it is not always true in the run above).</p>
<h3>14 Implement a proper stopping condition</h3>
<p>Change the while loop to stop when the validation error drops below a threshold. Note that this threshold usually depends on the problem. There are better stopping conditions that are less sensitive to the problem at hand, but this one will do for now.</p>
<h3>15 Implement a statistical analysis</h3>
<p>This part is important for you to get an idea of the robustness of the neural net. In practice, a very simple analysis will suffice.</p>
<p>This part need to train the algorithm 30 times, and then report the mean, standard deviation and maximum of the</p>
<ul>
<li>training time,</li>
<li>regression error, and</li>
<li>classification error (on the test sets).</li>
</ul>
<p>In general, you would like all these values to be “low”. Here are some experiments for the iris data set with different learning rates. For each, 30 runs were made; other parameters are as described earlier (max_weight = 1/2, validation_stop_threshold = 0.1).</p>
<table border="0" cellspacing="0" cellpadding="2" width="486">
<tbody>
<tr>
<td width="171" valign="top"></td>
<td width="107" valign="top"><strong>Mean</strong></td>
<td width="100" valign="top"><strong>Standard Deviation</strong></td>
<td width="106" valign="top"><strong>Maximum</strong></td>
</tr>
<tr>
<td width="171" valign="top"><strong>eta = 0.05</strong></td>
<td width="107" valign="top"></td>
<td width="100" valign="top"></td>
<td width="106" valign="top"></td>
</tr>
<tr>
<td width="171" valign="top">Training time</td>
<td width="107" valign="top">1200</td>
<td width="100" valign="top">124.681</td>
<td width="106" valign="top">1489</td>
</tr>
<tr>
<td width="171" valign="top">Regression error</td>
<td width="107" valign="top">0.115343</td>
<td width="100" valign="top">0.0017233</td>
<td width="106" valign="top">0.11894</td>
</tr>
<tr>
<td width="171" valign="top">Classification Error</td>
<td width="107" valign="top">0.17807</td>
<td width="100" valign="top">0.0456762</td>
<td width="106" valign="top">0.263158</td>
</tr>
<tr>
<td width="171" valign="top"><strong>eta = 0.1</strong></td>
<td width="107" valign="top"></td>
<td width="100" valign="top"></td>
<td width="106" valign="top"></td>
</tr>
<tr>
<td width="171" valign="top">Training time</td>
<td width="107" valign="top">582.533</td>
<td width="100" valign="top">65.3076</td>
<td width="106" valign="top">719</td>
</tr>
<tr>
<td width="171" valign="top">Regression error</td>
<td width="107" valign="top">0.114626</td>
<td width="100" valign="top">0.00180851</td>
<td width="106" valign="top">0.118697</td>
</tr>
<tr>
<td width="171" valign="top">Classification Error</td>
<td width="107" valign="top">0.214912</td>
<td width="100" valign="top">0.0317323</td>
<td width="106" valign="top">0.263158</td>
</tr>
<tr>
<td width="171" valign="top"><strong>eta = 0.5</strong></td>
<td width="107" valign="top"></td>
<td width="100" valign="top"></td>
<td width="106" valign="top"></td>
</tr>
<tr>
<td width="171" valign="top">Training time</td>
<td width="107" valign="top">120.967</td>
<td width="100" valign="top">16.7095</td>
<td width="106" valign="top">169</td>
</tr>
<tr>
<td width="171" valign="top">Regression error</td>
<td width="107" valign="top">0.115711</td>
<td width="100" valign="top">0.0038786</td>
<td width="106" valign="top">0.123573</td>
</tr>
<tr>
<td width="171" valign="top">Classification Error</td>
<td width="107" valign="top">0.245614</td>
<td width="100" valign="top">0.0242702</td>
<td width="106" valign="top">0.263158</td>
</tr>
<tr>
<td width="171" valign="top"><strong>eta = 1</strong></td>
<td width="107" valign="top"></td>
<td width="100" valign="top"></td>
<td width="106" valign="top"></td>
</tr>
<tr>
<td width="171" valign="top">Training time</td>
<td width="107" valign="top">67.1667</td>
<td width="100" valign="top">12.2477</td>
<td width="106" valign="top">99</td>
</tr>
<tr>
<td width="171" valign="top">Regression error</td>
<td width="107" valign="top">0.114755</td>
<td width="100" valign="top">0.00488566</td>
<td width="106" valign="top">0.124468</td>
</tr>
<tr>
<td width="171" valign="top">Classification Error</td>
<td width="107" valign="top">0.253509</td>
<td width="100" valign="top">0.0201287</td>
<td width="106" valign="top">0.263158</td>
</tr>
</tbody>
</table>
<h2>Using the neural net in a program</h2>
<p>To use the neural net in a program after you have trained it, you need to save the weights found by the training program to a file. Your application must then read in this weights, and use it with the feedforward function to calculate the class.</p>
<p>Here is pseudo-code for the program. Note that the training program and classification program needn’t be implemented in the same language. This allows you to take advantage of speed and interface components that might not be available in your target platform. It is a very good idea to implement your training algorithm on a computer algebra system (such as <a href="http://www.mathworks.com/">Matlab</a> or <a href="http://www.gnu.org/software/octave/">Octave</a>) where you can take advantage of both matrix and graphing capabilities (the code provided below works in both).</p>
<h2>Using the training algorithm on other problems</h2>
<p>When using your neural net for other algorithms, you might need to change the learning rate, stopping threshold, and weight_max for weight the initialisation. The error plots are indispensible for this purpose.</p>
<p>As long as the learning rate is not too high, it should not affect the quality of the solution, only the number of iterations necessary to obtain it. The stopping threshold, however, has does affect the quality of the solution: if it is tool low, the problem might not be solved, or the neural net might train very long; if it is too high, you will get poor performance. There are better stopping conditions available; once you have everything working, you should investigate these.</p>
<p>Remember that you should not base your decisions on a single run, as runs can differ quite drastically from one another. Perform a few runs, and base decisions on these.</p>
<p>The value weight_max can usually be chosen as 1/sqrt(input_count) with good results, but here too it depends on the problem.</p>
<p>For further benchmarking, check out the <a href="ftp://ftp.ira.uka.de/pub/neuron/">Proben1 datasets</a>, described <a href="http://page.mi.fu-berlin.de/prechelt/Biblio/1994-21.pdf">here</a>. (Also check out the erratum note on <a href="http://page.mi.fu-berlin.de/prechelt/Biblio/">this site</a> – search for proben on the page.)</p>
<h2>Download</h2>
<p>The following code works in Matlab and Octave. (Included is a randint function; if you are using Matlab you can remove it, because it is already implemented in Matlab).</p>
<p><a href="http://www.code-spot.co.za/downloads/neural_net/iris_data_files.zip">iris_data_files.zip</a> (3 KB)</p>
<p><a href="http://www.code-spot.co.za/downloads/neural_net/basic_neural_net_0_1.zip">basic_neural_net_0_1.zip</a> (10 KB)</p>
<p>The program provided cheats a little – instead of reading in the raw .dat files, it reads in the .mat file that already has the data in the right structure.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/' rel='bookmark' title='Permanent Link: 5 Tips for Prototyping Slow Algorithms'>5 Tips for Prototyping Slow Algorithms</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/10/08/15-steps-to-implemented-a-neural-net/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Estimating a Continuous Distribution from a Sample Set</title>
		<link>http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/</link>
		<comments>http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 14:27:06 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[convolution]]></category>
		<category><![CDATA[distribution estimation]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random distribution]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=445</guid>
		<description><![CDATA[It is sometimes necessary to find the distribution given a sample set from that distribution. If we do not know anything about the distribution, we cannot recover it exactly, so here we look at ways of finding a (discrete) approximation. I will cover the case for 2D sets here, but the ideas are easily extended [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/' rel='bookmark' title='Permanent Link: Generating Random Points from Arbitrary Distributions for 2D and Up'>Generating Random Points from Arbitrary Distributions for 2D and Up</a></li>
<li><a href='http://code-spot.co.za/2009/04/28/generating-random-integers-with-arbitrary-probabilities/' rel='bookmark' title='Permanent Link: Generating Random Integers With Arbitrary Probabilities'>Generating Random Integers With Arbitrary Probabilities</a></li>
<li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="display: inline" title="header_rand_dist2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/header-rand-dist2.png" alt="header_rand_dist2" width="500" height="374" /> It is sometimes necessary to find the distribution given a sample set from that distribution. If we do not know anything about the distribution, we cannot recover it exactly, so here we look at ways of finding a (discrete) approximation.</p>
<p><span id="more-445"></span></p>
<p>I will cover the case for 2D sets here, but the ideas are easily extended to any dimension.</p>
<h2>Visual Inspection From a Scatter Plot</h2>
<p>The easy way to estimate the distribution is to simply look at a scatter plot of the samples.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="181" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/scatter-pixel.png" alt="scatter_pixel" width="300" height="300" /></td>
<td width="316" valign="top">A scatter plot of a 2D sample set. (A pixel was simply drawn at each point of the sample. The images was slightly blurred to give the pixels more substance).Here we can already estimate the distribution, as we can intuitively &#8220;see&#8221; the shape.</td>
</tr>
<tr>
<td width="181" valign="top"></td>
<td width="316" valign="top"></td>
</tr>
</tbody>
</table>
<p>If the distribution is simple, we can often “guess” suitable parameters for a mathematical function. But this method is not suitable when more accuracy is required. And obviously this method does not work for higher dimensions.</p>
<p>I always use a visual inspection as a first step when using the other methods described here. First, it allows you to decide which approach to use. Second, it serves as a rough benchmark to test the results of a better method against.</p>
<h2>Averaging Over a Grid</h2>
<p>For this method, we divide the domain in cells, and count the number of points in each cell. To normalise, we divide the counts by the total number of points to get a distribution.</p>
<p>Typically, we choose a cell size large enough so that all cells contain a few points.</p>
<p>It is possible to use different cell sizes, so that regions of higher density has more cells, for instance, by using a quad tree. However, this approach makes it difficult to interpret the values (they should be scaled down by a factor of the area they represent), and to generate random numbers from this distribution. I can’t really imagine a situation where this approach will be preferred above using a regular grid or convolution.</p>
<h2>Convolution</h2>
<p>There are two ways to implement convolution. The first should be used when the sample set is small relative to the size of the domain, otherwise the second method will be more efficient.</p>
<h3>Sparse Point Convolution</h3>
<p>Generate a very granular empty grid over the domain.</p>
<p>For each point p in the sample set,</p>
<ul>
<li>map p to the grid (calculate the coordinates x,y of p in the grid),</li>
<li>add a number to all the cells in the neighbourhood of p in the grid.</li>
</ul>
<p>Now normalise the grid.</p>
<p>The neighbourhood is typically a circle or a square. The number you add can be the same for all neighbours (in which case any positive number will do), or it can be scaled depending on the distance from p.</p>
<p>The size of the neighbourhood depends on the density of your sample. In general, the denser it is, the smaller the neighbourhood can be. Smaller neighbourhoods lead to faster execution. To prevent “holes” in the approximation, use a radius that corresponds to the maximum of the distances between a point and its closest neighbour.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="179" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/scatter-square16.png" alt="scatter_square16" width="300" height="301" /></td>
<td width="319" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/square.png" alt="square" width="100" height="100" />Estimation with a constant square neighbourhood.</td>
</tr>
<tr>
<td width="179" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/scatter-circle16.png" alt="scatter_circle16" width="300" height="300" /></td>
<td width="319" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/circle.png" alt="circle" width="100" height="100" /><br />
Estimation with a constant circular neighbourhood.</td>
</tr>
<tr>
<td width="179" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/scatter-cone16.png" alt="scatter_cone16" width="300" height="300" /></td>
<td width="319" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2009/03/cone.png" alt="cone" width="100" height="100" /><br />
Estimation with a circular neighbourhood with a falloff.</td>
</tr>
</tbody>
</table>
<h3>Traditional Convolution</h3>
<p>Generate a very granular empty grid over the domain.</p>
<p>For each point p in the sample set, map p to the grid (calculate the coordinates x,y of p in the grid), and add one to that location in the grid.</p>
<p>Now choose a square, symmetrical convolution matrix, and perform a discrete convolution on the grid:</p>
<p>new_grid[i, j] = sum_{i,j} grid[i][j] * c[i][j]</p>
<p>Here the i, j go over the indices of the convolution matrix. (Normally, the convolution is defined as new_grid[i, j] = sum_{i,j} grid[n - i][n - j] * c[i][j]. However, since we are suing a symmetrical matrix, these definitions are equivalent, and we need not perform the extra calculation).</p>
<p>Now normalise the grid.</p>
<p>The convolution can be a square or circle of 1s, or be filled with numbers that grow smaller outwards. These correspond to the three neighbourhoods described for the sparse convolution.</p>
<p>Note that the new_grid is larger than the original by one less than the size of the convolution matrix in each dimension. The centre of the new grid corresponds with the original grid.</p>
<p>For example, if the original grid was 100&#215;100, and the convolution matrix was 5&#215;5, the new grid will be 104&#215;104. The point (2, 2) in the new grid corresponds to point (0, 0) in the original grid.</p>
<h2>About Normalisation</h2>
<p>It is customary to normalise the distribution so that all the probabilities add to 1. But for many purposes we need only relative probabilities, and this step can be skipped. For example, the method of generating random numbers described in a previous post uses only relative probabilities.</p>
<h2>A Few Tips</h2>
<ul>
<li>Always test your distribution by <a href="http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/">generating a random set from it</a>, and comparing it with the original sample. They should match qualitatively.</li>
<li>The smaller your sample set, the cruder the approximation should be. That is, cells, neighbourhoods or convolution matrices should be big. There is a limit to the accuracy you can obtain from any sample – if you try to exceed it, your results will be poor.</li>
<li>The most common implementation errors are made at the borders (of any grid or matrix) – watch out for them!</li>
</ul>
<h2>Download</h2>
<p>There is an example of implementation in 2D in with the <a href="http://code-spot.co.za/python-image-code/">Python Image Code</a>. See the file random_distributions_demo.py.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/' rel='bookmark' title='Permanent Link: Generating Random Points from Arbitrary Distributions for 2D and Up'>Generating Random Points from Arbitrary Distributions for 2D and Up</a></li>
<li><a href='http://code-spot.co.za/2009/04/28/generating-random-integers-with-arbitrary-probabilities/' rel='bookmark' title='Permanent Link: Generating Random Integers With Arbitrary Probabilities'>Generating Random Integers With Arbitrary Probabilities</a></li>
<li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cellular Automata for Simulation in Games</title>
		<link>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/</link>
		<comments>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 08:34:57 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[blending]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[Conway's game of life]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[diffusion]]></category>
		<category><![CDATA[discrete dynamics]]></category>
		<category><![CDATA[disease simulation]]></category>
		<category><![CDATA[fire simulation]]></category>
		<category><![CDATA[force]]></category>
		<category><![CDATA[Game Maker]]></category>
		<category><![CDATA[grids]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[social dynamics]]></category>
		<category><![CDATA[sum]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=499</guid>
		<description><![CDATA[A cellular automata system is one of the best demonstrations of emergence. If you do not know what cellular automata (CA) is, then you should go download Conway&#8217;s Game of Life immediately: Conway’s Game of Life Essentially, CA is a collection of state machines, updated in discrete time intervals. The next state of one of [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/' rel='bookmark' title='Permanent Link: A Simple Trick for Moving Objects in a Physics Simulation'>A Simple Trick for Moving Objects in a Physics Simulation</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="display: inline" title="header" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/header1.png" alt="header" width="500" height="371" /></p>
<p>A cellular automata system is one of the best demonstrations of emergence. If you do not know what cellular automata (CA) is, then you should go download Conway&#8217;s Game of Life immediately:</p>
<p><a href="http://psoup.math.wisc.edu/Life32.html">Conway’s Game of Life</a></p>
<p>Essentially, CA is a collection of state machines, updated in discrete time intervals. The next state of one of these depends on the current state as well as the states of neighbours. Usually, the state machines correspond to cells in a grid, and the neighbours of a cell are the cells connected to that cell. For a more detailed explanation, see <a href="http://en.wikipedia.org/wiki/Cellular_automata">the Wikipedia article</a>.</p>
<p>Even simple update rules can lead to interesting behaviour: patterns that cannot be predicted from the rules except by running them. With suitable rules, CA can simulate many systems:</p>
<ul>
<li>Natural phenomena: weather, fire, plant growth, migration patterns, spread of disease.</li>
<li>Socio-economic phenomena: urbanisation, segregation, construction and property development, traffic, spread of news.</li>
</ul>
<p><span id="more-499"></span></p>
<p>In games, these can be used as game elements (such as fire and disease), or they can also add some decorative life to a game (such as city development in a simulation game).</p>
<p>The great thing about CA systems is that they are not hard to implement, and they have intrinsic fun value (I mean here, for the programmer!).</p>
<p>Before we get into the details, let me add a small disclaimer here:</p>
<ul>
<li>This tutorial is not comprehensive. I only touch on a few ideas in a wide field. See some of the resources at the end for more information.</li>
<li>This tutorial is not representative. I merely chose topics I found interesting or thought would be useful for game developers.</li>
<li>I am not suggesting that using cellular automata is the best way to simulate any of the examples given here. For any problem, there might be solutions that are faster, easier to implement, or yield better results.</li>
</ul>
<h2>Implementation</h2>
<p>To implement a CA system, you need to do the following:</p>
<ul>
<li>Use a suitable system to store states, for example, a 2D array.</li>
<li>Decide on a suitable neighbourhood shape, and work out some preliminary rules. Decide how you will handle edges.</li>
<li>Implement a suitable way to describe your rules.</li>
<li>Implement an update function that hooks into the main game loop.</li>
<li>Implement a visualisation scheme (for example, drawing tiles depending on states in the array).</li>
</ul>
<p>Some details of these are described below.</p>
<h3>Grid</h3>
<p>A typical implementation uses two grids for storing states. One is the current world state; the other is the new world state. Once all cells have been updated for the current iteration, pointers to the arrays can be swapped. This way updating the cells one by one will not have an effect on other cells until the next iteration, and you do not have to create a new array in each iteration.</p>
<p>Using grids with square cells are the easiest to implement, but the concept is also applicable to other grids: hexagonal and triangular grids are also common, and even polar grids have been used to simulate spiral star systems.</p>
<p>It is also possible to use irregular systems, although the implementation then becomes a challenge. One example of an irregular system is a presentation based on a Poisson distribution of points. The trick here is to find an efficient way to locate neighbours. Fortunately, this problem has already been solved in creating the points (see the <a href="http://devmag.org.za/2009/05/03/poisson-disk-sampling/">Poisson Sampling tutorial in Dev.Mag</a> and download code from <a href="http://www.luma.co.za/labs/tag/poisson-disk/" class="broken_link">Luma Labs</a>). It is in fact done by using an invisible grid! Of course, visualising a state is also a bit more difficult.</p>
<h3>Neighbourhoods</h3>
<p>For 2D cellular automata, the most common neighbourhoods are the Von Neumann neighbourhood and the Moore neighbourhood, shown below (the blue cell’s neighbourhood is shown in red). Other neighbourhoods are also possible.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="vonneumann" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/vonneumann.png" alt="vonneumann" width="88" height="88" /></td>
<td width="166" valign="top"><img style="display: inline" title="moore" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/moore.png" alt="moore" width="88" height="88" /></td>
<td width="166" valign="top"><img style="display: inline" title="road" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/road.png" alt="road" width="88" height="88" /></td>
</tr>
<tr>
<td width="166" valign="top">Von Neumann neighbourhood</td>
<td width="166" valign="top">Moore neighbourhood</td>
<td width="166" valign="top">Extended Von Neumann neighbourhood</td>
</tr>
</tbody>
</table>
<p>The cell can be included in the neighbourhood or not. It is advisable to keep the neighbourhoods as small as possible: not only does the neighbourhood size impact performance, it also affects the number of rules to be specified and thus the tweaking complexity.</p>
<h3>Specifying Update Rules</h3>
<p>Specifying the rules concisely is the most challenging part of implementing CA. With very simple models, you might want to use a few if/else statements. This, however, makes it hard to modify (tweak or extend), and is therefore not suitable for more complicated systems.</p>
<p>It is best to implement rules as a table that can be indexed using the neighbourhood states.</p>
<p><strong>Table as an array.</strong> In this method, each row represents the combined state of the surrounding cells. The final entry in the row is the new state of the current cell. Each of the remaining columns represents a state. The entries in these columns represent the number of cells surrounding the current cell in that state.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top">Dry Bush</td>
<td width="125" valign="top">Burning Bush</td>
<td width="125" valign="top">Charcoal</td>
<td width="125" valign="top">New State</td>
</tr>
<tr>
<td width="125" valign="top">4</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Dry Bush</td>
</tr>
<tr>
<td width="125" valign="top">3</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">3</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">Dry Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">2</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">2</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
</tbody>
</table>
<p>A cell surrounded with three cells in the Dry Bush state and one cell in the Burning Bush state will go into the Burning Bush state.</p>
<p>This table can be quite large, so that you must take care to implement lookups efficiently. Keep the table sorted, and perform binary search to lookup entries. Below are some improvements on this scheme.</p>
<p><strong>Table as a tree.</strong> In the table above, it is easy to see that if there are three dry bush nodes, there are two possibilities for the other states (either 1 0, or 0 1). We can use this to implement a tree. Each level in the tree represents a state. A value in a node represents how many cells in the neighbourhood are in that state. A path from root to leaf fully describes the states of the entire neighbourhood. We do not add nodes for the last state, as it is uniquely determined by the other states.</p>
<p>Below is a tree corresponding to the piece of table above.</p>
<p>BB = Burning Bush</p>
<p>DB = Dry Bush</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="41" valign="top">root</td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 4</td>
<td width="50" valign="top"></td>
<td width="49" valign="top"></td>
<td width="171" valign="top">DB</td>
</tr>
<tr>
<td width="42" valign="top"></td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 3</td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 1</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top">|</td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 0</td>
<td width="171" valign="top">DB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 2</td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 2</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top"></td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 1</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top"></td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 0</td>
<td width="171" valign="top">BB</td>
</tr>
</tbody>
</table>
<p>This is a more efficient implementation; unfortunately, it is also more complicated. It is inconvenient to specify the tree in a tree-friendly format (XML or s-expressions, for example). You still need to specify it in table format (space separated text file, for example) and build the tree from that.</p>
<p><strong>Implementation as a hash table.</strong> Here you use tuples of state counts as keys. For example, the third entry in the table above can be accessed with the tuple (3, 0, 1). If your implementation language does not support tuples, you might need to implement them yourself. Be sure to make them immutable!</p>
<p><strong>Implementation as an N-dimensional array.</strong> This is a very simple method, although it wastes a lot of memory. N is the number of states, and we use the state counts to index into the array. In our example, we will use a 3D array, so that the third element can be accessed using transition_array[3, 0, 1].</p>
<p>The method above can be used even when the implementation language does not provide N dimensional arrays. Simply use a 1D array, and interpret the state counts as the digits of a base-4 number. Thus, the third row will be located at 3*16 + 0*4 + 1*1 = 49.</p>
<p>Note that since the numbers are restricted by the requirement that they add to four, there will be unused array positions in both these last two methods. You can save memory by not using the last state to index (since it is uniquely determined by the other states). Thus, we can use a 2D array, and access the 3,0,1 rule with 3,0 alone: transition_array[3, 0]. Alternatively, if we need to use a 1D array, we can store the rule in the position 3*4 + 0*1 = 12. Although the same scheme is possible for the hash table implementation, I would advise you to use the full indexing scheme instead, since it will not waste more memory if you do, and it is somewhat easier to understand if you use full indices.</p>
<p>Some rules do not need the detailed tables above. For instance, in a system of only two states, where transitions depend on the count of the states of the neighbourhood, we can use a simple array, indexed by one of the states’ counts. Many other schemes are possible: in general, aim for quick lookups and easy specification.</p>
<h3>Edges</h3>
<p>The edges of your simulation might present some problems: edges often serve as unwanted sources, sinks or stabilisers.</p>
<p>A <strong>source</strong> is the origin of outward growth (states change progressively to a specific state in an outward direction).</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top"><img style="display: inline" title="growth4" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth41.png" alt="growth4" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth31.png" alt="growth3" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth21.png" alt="growth2" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth11.png" alt="growth1" width="88" height="88" /></td>
</tr>
</tbody>
</table>
<p>A <strong>sink</strong> is the exact opposite:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top"><img style="display: inline" title="growth1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth11.png" alt="growth1" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth21.png" alt="growth2" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth31.png" alt="growth3" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth4" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth41.png" alt="growth4" width="88" height="88" /></td>
</tr>
</tbody>
</table>
<p>Sources and sinks are emergent properties of the CA system, and are not physical attributes of the cells.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="screenshot186" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1861.png" alt="screenshot186" width="144" height="108" align="left" /> A <strong>stabiliser</strong> is a section that keeps neighbouring states fixed. For example, in the fire simulation (described below), there is an unnatural wall of fire around the edges at the end of the simulation.</p>
<p>There are several ways you can handle edges:</p>
<p><strong>Ignore them.</strong> When the edge anomalies are acceptable, it is best not to complicate the model. This is only possible if the rules are specified in a way that does not require state counts to sum to the size of the neighbourhood. For example, if there is a rule “if num_states_fire &gt; 1, then …”.</p>
<p><strong>Wrap around.</strong> This solution is very elegant, easy to implement, and its effects are easy to understand. However, it is usually easy to see that the world has been wrapped in this way, and hence it is not always a visually a satisfactory solution. It is possible, however, to simulate a grid bigger than displayed area (say about double). This will hide the fact that it is wrapped, but still give you the benefits of having a world without any discontinuities.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="wrapped" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/wrapped.png" alt="wrapped" width="88" height="88" align="left" /> In the CA system shown left, we want to calculate the next state of the grey cell. Two neighbours fall outside the edges. If we wrap around, we use the four red squares as shown.</p>
<p><strong>Reflection.</strong> Use a neighbouring state to perform calculations.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="reflect" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/reflect.png" alt="reflect" width="88" height="88" align="left" /> The CA system shown left is the same situation as above. If we use neighbouring states for the cells beyond the edges, we use the state of the grey cell (twice!), in addition to the two red cells shown.</p>
<p><strong>Fix their states. </strong>The edges can be given special, constant states that make the CA behave as intended. Finding the right state(s) for the edges might be difficult.</p>
<p>An implementation trick that applies to the last three edge-handling techniques is to include a border in your simulation. For the Von Neumann and Moore neighbourhoods, this border is only one cell thick.</p>
<p>This border is used for updates like all other cells, but is itself updated differently. The update rules for wrapping and reflection will simply copy states from the right places; the border for fixed states will never be updated.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="edges_implementation" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/edges-implementation.png" alt="edges_implementation" width="123" height="123" align="left" /> In the figure, hatched cells are updated according to the special rules of the edge-handling scheme – in this case, wrapping is used, so they are simply copied from the appropriate cells. All other cells are updated normally. Note that here we do not need special logic for updating the grey cell.</p>
<h2>A Few Examples</h2>
<p>(Also see the downloads at the bottom of the post).</p>
<h3>Heat</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="screenshot210" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot210.png" alt="screenshot210" width="144" height="108" align="left" /> Here, continuous states (floats between 0 and 1) are used. Every cell is updated to a weighted average of its Moore neighbourhood cells: corners have a smaller weight than other cells. For this simulation, heat sinks and sources have been added: they keep the cell’s temperature at 0 and 1 respectively.</p>
<h3>City Roads</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="roads" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/roads.png" alt="roads" width="144" height="108" align="left" /> This simulation use separate neighbourhoods for creating and destroying a road. The creation neighbourhood is an extended Von Neumann neighbourhood; the destruction neighbourhood is a Moor neighbourhood. Creation and destruction is according to probabilities based on the count of neighbouring roads.</p>
<h3>Influence</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="anger" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/anger.png" alt="anger" width="288" height="216" align="left" /></p>
<p>This simulation models human emotion as influenced by others. A character has an internal state, and an externally visible state. Characters can only observer the external state of their neighbours. The internal state is then a modified: a character surrounded by angry people will itself become angry, and so on. The external state is probabilistically determined by the internal state.</p>
<h3>Disease Spread</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="epeidemic" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/epeidemic.png" alt="epeidemic" width="288" height="216" align="left" /> For our game <a href="http://www.luma.co.za/labs/2007/10/15/epidemic/" class="broken_link">Epidemic</a>, <a href="http://blog.cunnington.co.za/">Chris</a> and I used a simple diffusion model. We used a floating-point number for the state, and represented the number of infected people in a cell. We used different colours for different ratios to visualise infection. At each time step, a cell would become infected by an amount proportional to that of the neighbourhood, with some random scaling.</p>
<h2>Visualising States</h2>
<h3>Versions of tiles</h3>
<p>A very effective way of making CA simulations more impressive is to have more than one tile for each state, and display them randomly. This is especially helpful for hiding regularity in off-line simulations. Tile sets with different versions for corners, edges, and central regions can drastically improve the look of the game, although it complicates choosing the correct tile version. In addition, it means you need tiles for various combinations of states. Assuming we can rotate and reflect tiles, in the fire example with three states, we need the following tiles:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="250" valign="top">3 centre tiles</td>
<td width="59" valign="top"><img style="display: inline" title="centre" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/centre1.png" alt="centre" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 straight-edge tiles</td>
<td width="59" valign="top"><img style="display: inline" title="edge" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/edge1.png" alt="edge" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 diagonal line tiles</td>
<td width="59" valign="top"><img style="display: inline" title="diagonal" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/diagonal1.png" alt="diagonal" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 cross tiles</td>
<td width="59" valign="top"><img style="display: inline" title="cross" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/cross1.png" alt="cross" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">6 corner tiles</td>
<td width="59" valign="top"><img style="display: inline" title="corner" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/corner1.png" alt="corner" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 half-straight tiles</td>
<td width="59" valign="top"><img style="display: inline" title="half_edge" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/half-edge1.png" alt="half_edge" width="49" height="49" /></td>
</tr>
</tbody>
</table>
<p>This is 21 tiles for only three states. It is advisable to automate tile creation.</p>
<h3>Tile <a name="_Toc226913823"></a></h3>
<p>States can be animated. Instead of displaying a single tile, display an animation sequence. You will need to think about how to start and stop these animations so that they are seamless. For instance, you can make all animation sequences the same length, and only update states between animation sequences.</p>
<p>You can also increase the seamlessness of the simulation by animating transitions between states. This can be as easy as blending between two tiles over a period of time (assuming that updates are made far enough apart).</p>
<h3>No Tiles</h3>
<p>Instead of using tiles to represent a state of a cell, you can put objects in a cell. For instance, in a plant growth simulation, you can put a number of trees in the cell depending on the state. The advantages of this are:</p>
<ul>
<li>You do not have to create dozens of tiles for variety.</li>
<li>The player can interact with the objects. For instance, the plant placement of trees can hinder a player’s movement.</li>
</ul>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="detail" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/detail1.png" alt="detail" width="140" height="108" align="left" /> This shows a simple forest simulation. Trees grow and die depending on the surrounding trees. This system uses a grid, but not tiles: trees can grow in random positions in tiles. For this simulation, three random coordinates have been chosen for each cell at the beginning of the simulation. Depending on the states, one, two, or three trees will be drawn at these points. Choosing a fixed set of points makes it easier to draw trees at the same coordinates every tick. A somewhat more complicated simulation can choose new points whenever a new tree comes into being.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot191" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1911.png" alt="screenshot191" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot193" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1931.png" alt="screenshot193" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot196" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1961.png" alt="screenshot196" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<h2>CA Enhancements</h2>
<p>The images below show three frames from a simple fire simulation.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot181" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1811.png" alt="screenshot181" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot182" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1821.png" alt="screenshot182" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot183" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1831.png" alt="screenshot183" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>The green is grass (Dry Bush), the orange is fire (Burning Bush) and the brown is burnt grass (Charcoal).</p>
<p>As you can see, the simulation captures some features of a fire:</p>
<ul>
<li>fire grows outward,</li>
<li>grass only burns once,</li>
<li>grass needs fire to catch fire (there is no spontaneous combustion).</li>
</ul>
<p>Even so, the symmetry and regularity makes this fire very unconvincing. Below we look at some ideas to enhance a simple CA simulation.</p>
<h3>Probabilistic State Transitions</h3>
<p>Instead changing to some specific state based on the surrounding states, you can change to any state with some probability. These probabilities depend on the surrounding states, and can possibly be zero.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot167" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1671.png" alt="screenshot167" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot168" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1681.png" alt="screenshot168" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot169" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1692.png" alt="screenshot169" width="144" height="108" /></td>
</tr>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot170" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1702.png" alt="screenshot170" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot171" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1712.png" alt="screenshot171" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot172" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1721.png" alt="screenshot172" width="144" height="108" /></td>
</tr>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot173" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1731.png" alt="screenshot173" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot174" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1741.png" alt="screenshot174" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot175" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1751.png" alt="screenshot175" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Adding probability to the mix can have several advantages:</p>
<p><strong>It introduces variability in patterns.</strong> This means a specific (perhaps the start-up pattern) will not always produce the same results.</p>
<p><strong>It can enhance the organic look of the system.</strong> Cross and squares patterns are common in deterministic CA systems. For many purposes, this is unsatisfactory (have you ever seen a fire spreading as a growing square?) Adding probabilistic state changes will make the patterns more organic and varied.</p>
<p><strong>It can make discreet behaviour more continuous.</strong> For example, two common &#8220;problems&#8221; with CA systems are exponential growth (where all cells go to a certain state outwards very quickly), or sudden death (where all cells go to a certain state very quickly inwards). The problem is often that a single change in the update rules results in a exponential growth system to become a sudden death system, with seemingly no way to get a &#8220;sweet spot&#8221;. If states can only change with a certain probability, tweaking the probabilities allows you to get intermediate patterns (stable growth, equilibrium, or stable death).</p>
<p><strong>It allows you to control the speed of the simulation.</strong> It is especially helpful to slow down a simulation without making it more granular (in the time dimension). It is useful to multiply all your probabilities with a global parameter that you can tweak to control the speed.</p>
<p>Note that in the example above, certain cells did not burn at all – per chance, they did not caught fire when their neighbours were burning. Timers (see below) can reduce or eliminate this effect.</p>
<p>Adding randomness can increase the emergence, and hence also unwanted emergence, so care must be taken that the simulation is always valid.</p>
<h3>Tile Interpolation</h3>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot169" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1693.png" alt="screenshot169" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot170" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1703.png" alt="screenshot170" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot171" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1713.png" alt="screenshot171" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Normally, you want your simulation to be as simple as possible. However, when such simple simulations are displayed (visualised), the results can be unsatisfactory. One way to get better visual quality is to use tile (cell) interpolation to make the simulation seem more complicated than it really is. When combined with a bit of randomisation, the effects can be very convincing.</p>
<p>The basic idea is to simulate only every nth cell with the CA approach. Other cells are interpolated. The number of interpolated cells can be adjusted, depending on the detail level required (balanced with the combinatorial number of tiles required!)</p>
<p>In the fire simulation, using only three states makes the simulation seem very primitive. Suppose that we simulate only every second row, and in these, only every second column, and fill the remaining cells depending on their neighbours. We have to create a function that will return a tile for each combination of surrounding tiles:</p>
<p>get_center_tile(north, east, south, west)</p>
<p>Interpolation rules are similar to update rules of the simulation, and hence can easily be as complicated. If this is the case, you would do better to implement more states and not do any interpolation. Interpolation should only be used if it significantly reduces the implementation complexity.</p>
<h3>Timers</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody></tbody>
</table>
</h3>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot177" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1771.png" alt="screenshot177" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot178" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1781.png" alt="screenshot178" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot179" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1791.png" alt="screenshot179" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Some interesting effects can be obtained if each cell has a timer, that is, each cell only updates once the timer expires. Some rule determines when the timer is reset. For instance, the timer can be set:</p>
<ul>
<li>randomly,</li>
<li>as a function of the state,</li>
<li>as a function of the surrounding cells,</li>
<li>as a function of another property of the tile (*1),</li>
<li>as a function of some external process (*2).</li>
</ul>
<p>(*1) For instance, if each cell has an associated &#8220;burning capacity&#8221; parameter, (simulating material types), a fire state timer can be set in proportion to this parameter.</p>
<p>(*2) For example, we can set timers according to a wind factor.</p>
<p>Timers can have the following effects:</p>
<ul>
<li>add some randomness to a simulation,</li>
<li>slow the simulation down,</li>
<li>smear the simulation (for example, in the fire simulation, the burning border is much thicker, and no cells are skipped).</li>
</ul>
<p>Although you can often implement your grid cells as classes (or structs, or whatever aggregating construct your language provides) with states and timers embedded, it is simpler (on more efficient) to have separate integer grids – one for states and one for timers.</p>
<p>Note that if timers do not have the same expiration time, you the CA system is asynchronous and the behaviour can differ dramatically from a synchronous CA system. Thus, you should include timers early in the development process, so that their effect does not force you to re-tweak all the parameters.</p>
<h2><a name="_Toc226913828"></a></h2>
<p>If your world is big, you cannot run the CA for the whole world at every time step – it will kill performance. Below are some ideas for improving performance.</p>
<h3><a name="_Toc226913829"></a></h3>
<p>Instead of simulating the entire world, you can only simulate the part that is relevant to the game, usually the visible region of the game. A simple technique is to use a wrapped grid, similar to the grids used for the visual port in scrollable 2D games. This grid can be slightly larger than the visible grid, so that it allows cells to update naturally for a few iterations before they become visible, and so increase the illusion of a persistent world.</p>
<p>To hide that fact that you are only simulating a very small piece of the world, you must update “new” cells appropriately. There are several options:</p>
<p><strong>Update cells to a natural starting state.</strong> In many cases, this solution is adequate, especially if you simulate a slightly larger grid than is visible.</p>
<p><strong>Copy states from the existing simulation.</strong> Here you can copy neighbouring cells, or randomly from a nearby region. Copying from nearby cells promotes spatial coherence.</p>
<p><strong>Initialise states statistically.</strong> Based on a neighbourhood of cells, each cell is initialised probabilistically. For example, each cell can be initialised randomly to one of three neighbouring cell’s states.</p>
<p><strong>Use hierarchical modelling.</strong> Use another CA system that represents the entire world in very low detail, and use this to initialise the cells of the high detail version. Note that both the states and the update rules will differ for the high and low detail simulations. Use probabilities to prevent homogeneous systems. You can even use several levels of detail, and incorporate them as needed. Beware the extra implementation complexity, though!</p>
<p>This technique does not work when the world is should be changed permanently.</p>
<h3><a name="_Toc226913830"></a></h3>
<p>Instead of only simulating a part of the world, you can only update a part of the world. This requires enough memory for the whole world, but only processing power for the cells you wish to update. This method has the advantage of real persistence, thus permanent changes can be reliably simulated. Which cells you update will determine how your simulation will play out:</p>
<ul>
<li>Update all visible cells (or a slightly larger region). This is the most natural update scheme, and its effects are similar to partial simulation described above.</li>
<li>Divide the world into discontiguous regions, and update a different region each time step. For example, divide the world into two sets: one contains every other cell, the other the rest, and update these two sets alternately. To save a significant amount of processing, you need many sets. To hide patterns in the updates that might break the illusion of a continuous world, the sets should be irregular. This method has the advantage that real things happen off screen. On the down side, it slows down the simulation significantly.</li>
<li>Combine the two methods above.</li>
</ul>
<p>Partial updating, like the inclusion of timers, lead to an asynchronous system, and hence the behaviour might be very different from that of a fully updated system.</p>
<h3><a name="_Toc226913831"></a></h3>
<p>In certain cases, simulations can be baked offline and be used in games. This means you perform the simulation before the time, and record each frame. The game then reads these frames, and plays them back.</p>
<p>Various schemes are possible to get more with less. For instance, you can also interpolate the simulation in time. With some thought, you can simulate events in a way that they can be looped, stacked together, and started and stopped unobtrusively. This means you can blend them with the interaction in a way that will not make it obvious that the simulation has been performed off-line.</p>
<h3>Unwanted Emergence</h3>
<p>Not all emergence is good, and you might find it hard to prevent certain behaviours. If the unwanted behaviour is only visual, and it occurs only rarely, it might be acceptable. However, if behaviour impacts play negatively, it must be prevented.</p>
<p>As with all tweaking, you should not spend too much time fumbling around. To proceed more &#8220;scientifically&#8221;, ask yourself the following questions:</p>
<ul>
<li>Is there a way to detect (measure objectively) the unwanted behaviour?</li>
<li>Instead of tweaking your CA, can you detect-and-recover system be used?</li>
<li>Is the behaviour continuous? In other words, is there a degree of badness, or is it either good or bad?</li>
<li>If it is continuous, is it feasible to kick in a preventative system? (When the badness goes above a threshold, updates are processed differently).</li>
<li>Is it feasible to find a set of parameters through an optimisation algorithm (for instance, genetic programming)? It might even be possible to search exhaustively for a solution.</li>
<li>Is my model too complex? Try to eliminate states and simplify transition rules. You might even consider breaking your simulation into two or more independent CA systems.</li>
<li>If you find yourself struggling to tweak the parameters for too long, you should perhaps look for a better model that is less sensitive to the exact parameters.</li>
</ul>
<h2>Links</h2>
<h3>Online Demo</h3>
<p><a href="http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata">http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata</a> Browswer-based demo with ActionScript source code.</p>
<h3>General</h3>
<p><a href="http://cell-auto.com/">http://cell-auto.com/</a> A nice breakdown of various topics related to Cellular Automata. The article on <a href="http://cell-auto.com/optimisation/">optimisation</a> is especially interesting.</p>
<p><a href="http://www.collidoscope.com/modernca/">http://www.collidoscope.com/modernca/</a> Contains many non-traditional variations of cellular automata.</p>
<p><a href="http://www.fourmilab.ch/cellab/">http://www.fourmilab.ch/cellab/</a> Application for exploring cellular automata.</p>
<h3>Applications and Implementation</h3>
<p><a href="http://realtimecollisiondetection.net/blog/?p=57">http://realtimecollisiondetection.net/blog/?p=57</a> Path finding using cellular automata.</p>
<p><a href="http://www.ibm.com/developerworks/java/library/j-camusic/">http://www.ibm.com/developerworks/java/library/j-camusic/</a> Cellular Automata and music (interesting way of creating procedural music).</p>
<p><a href="http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html">http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html</a> About using lazy, infinite containers for cellular automata.</p>
<p><a href="http://madeira.cc.hokudai.ac.jp/RD/takai/automa.html">http://madeira.cc.hokudai.ac.jp/RD/takai/automa.html</a> Graphics applications for cellular automata – lots of videos!</p>
<h3>Game Design</h3>
<p><a href="http://www.gamestudies.org/0102/pearce/">http://www.gamestudies.org/0102/pearce/</a> An article about game design.</p>
<p><a href="http://www.cp.eng.chula.ac.th/~vishnu/gameResearch/Sweetser_Thesis.pdf">http://www.cp.eng.chula.ac.th/~vishnu/gameResearch/Sweetser_Thesis.pdf</a> A thesis that looks at game design from a emergence perspective.</p>
<p><a href="http://fora.tv/2006/06/26/Will_Wright_and_Brian_Eno#chapter_01">http://fora.tv/2006/06/26/Will_Wright_and_Brian_Eno#chapter_01</a> Will Wright and Brian Eno on generative systems.</p>
<h2>Downloads</h2>
<h3>Game Maker Demos</h3>
<ul>
<li>Requires Game Maker 7.</li>
<li>Contains 9 demos.</li>
</ul>
<p><a href="http://www.code-spot.co.za/downloads/game_maker/ca_demos.zip">ca_demos.zip</a> (135 KB)</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/' rel='bookmark' title='Permanent Link: A Simple Trick for Moving Objects in a Physics Simulation'>A Simple Trick for Moving Objects in a Physics Simulation</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</title>
		<link>http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/</link>
		<comments>http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/#comments</comments>
		<pubDate>Wed, 08 Apr 2009 11:22:00 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[art pipeline]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[game tools]]></category>
		<category><![CDATA[level editor]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[XSI Mod Tool]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=457</guid>
		<description><![CDATA[Last year I wrote a tutorial explaining how to use XSI Mod Tool as a level editor, specifically for XNA. Below is the same tutorial, updated for XNA 3.0. There are only a few minor changes: You need not copy compiled assets from the batch file as before. A section is included that describes how [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2008/09/14/google-app-engine-for-games/' rel='bookmark' title='Permanent Link: Google App Engine for Games'>Google App Engine for Games</a></li>
<li><a href='http://code-spot.co.za/2009/10/24/guerrilla-tool-development/' rel='bookmark' title='Permanent Link: Guerrilla Tool Development'>Guerrilla Tool Development</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-643" title="header" src="http://code-spot.co.za/blog/wp-content/uploads/2009/06/header.png" alt="header" width="500" height="371" /></p>
<p>Last year I wrote a <a href="http://www.luma.co.za/labs/2008/05/08/xsi-mod-tool-as-level-editor-for-xna-20/trackback/" class="broken_link">tutorial</a> explaining how to use <a href="http://www.softimage.com/products/modtool/">XSI Mod Tool</a> as a level editor, specifically for <a href="http://creators.xna.com/en-GB/">XNA</a>. Below is the same tutorial, updated for XNA 3.0. There are only a few minor changes:</p>
<ul>
<li>You need not copy compiled assets from the batch file as before.</li>
<li>A section is included that describes how to use the content pipeline classes for easy reading of XML files (useful for level files, etc.).</li>
</ul>
<p>I also corrected quite a few typos.<br />
<span id="more-457"></span></p>
<h2>Link</h2>
<p>The article <a href="http://www.gamedev.net/reference/programming/features/XSIinXNA/" class="broken_link">Integrating Your XNA Engine With XSI ModTool</a> is very relevant to this tutorial. Among other things, it explains how to make XNA shaders work in XSI.</p>
<h2>Download</h2>
<h3>PDF Tutorial</h3>
<p><a href="http://www.code-spot.co.za/downloads/tutorials/How to Turn XSI Mod Tool into a Level Editor for your XNA Games v3.pdf">How to Turn XSI Mod Tool into a Level Editor for your XNA Games v3.pdf (463 KB)</a></p>
<h3>Example</h3>
<p>(XSI Plug-in and C# code. Includes the tutorial PDF)</p>
<p><a href="http://www.code-spot.co.za/downloads/tutorials/XSIModToolLevelEditor3.zip">XSIModToolLevelEditor3.zip (5.2 MB)</a>.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2008/09/14/google-app-engine-for-games/' rel='bookmark' title='Permanent Link: Google App Engine for Games'>Google App Engine for Games</a></li>
<li><a href='http://code-spot.co.za/2009/10/24/guerrilla-tool-development/' rel='bookmark' title='Permanent Link: Guerrilla Tool Development'>Guerrilla Tool Development</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Generating Random Numbers with Arbitrary Distributions</title>
		<link>http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/</link>
		<comments>http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 18:16:59 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[distribution function]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random number generation]]></category>
		<category><![CDATA[response curve]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[Special Numbers Library]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=123</guid>
		<description><![CDATA[For many applications, detailed statistical models are overkill. Instead, we can get away with a rough description of the distribution &#8211; not in mathematical formula form, but just as a graph with a few sample points. For example, when trying to model the traffic around a school, you might know that the graph looks something [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/' rel='bookmark' title='Permanent Link: Generating Random Points from Arbitrary Distributions for 2D and Up'>Generating Random Points from Arbitrary Distributions for 2D and Up</a></li>
<li><a href='http://code-spot.co.za/2009/04/28/generating-random-integers-with-arbitrary-probabilities/' rel='bookmark' title='Permanent Link: Generating Random Integers With Arbitrary Probabilities'>Generating Random Integers With Arbitrary Probabilities</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img zemanta-action-click">
<p class="zemanta-img-attribution">For many applications, detailed statistical models are overkill. Instead, we can get away with a rough description of the distribution &#8211; not in mathematical formula form, but just as a graph with a few sample points.</p>
<p class="zemanta-img-attribution">For example, when trying to model the traffic around a school, you might know that the graph looks something like this:</p>
<p class="zemanta-img-attribution"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/school.png" alt="school" width="481" height="289" /></p>
<p class="zemanta-img-attribution">The input is the number of minutes before the first bell rings, and the output the number of children dropped off at that time. You know that most kids are brought before the bell rings, and that the closer to the bell, the more kids are being brought every minute. Only a few kids are late.</p>
<p class="zemanta-img-attribution">This tutorial describes how to generate random numbers that can generate a distribution described by an arbitrary (piece-wise linear) curve, as the one above.</p>
<p class="zemanta-img-attribution"><span id="more-123"></span></p>
<h2>Implementation</h2>
</div>
<h3>1. Calculate an accumulative probability</h3>
<p>The first step is to run an accumulative sum of our original sample points. The following code snippet shows how it can be done in C++; the array &#8220;samples&#8221; contains the original samples.</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i = 1; i &lt; n; i++)
{
    samples[i] += samples[i - 1];
}</pre>
</div>
<p>   The snippet above does the calculations in-place, but it is not necessary, as is shown in the snippet below:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">newSamples[0] = samples[0];

<span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i = 1; i &lt; n; i++)
{
    newSamples[i] = samples[i] + newSamples[i - 1];
}</pre>
</div>
<p>   <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/accumulative.png" alt="accumulative" width="481" height="289" /> The graph above shows the accumulative probability density.</p>
<h3>2. Calculate inverse sample points</h3>
<p>This step is easy &#8211; we simply swap the input and output samples. It is not necessary to do this explicitly, just swap them in the argument list of the function call in the next step.  <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/inverse.png" alt="inverse" width="481" height="289" /></p>
<h3>3. Interpolate between samples</h3>
<p>I use a special data structure that makes it very easy to compute the interpolations from discreet sample points: the response curve. There are two varieties. The ordinary response curve, with uniformly spaced samples, and the xy-response curve, where samples can be arbitrarily spaced.  <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/u-response.png" alt="u-response" width="481" height="289" /> <strong>Ordinary Response Curve.</strong> <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/xy-response.png" alt="xy-response" width="481" height="289" /> <strong>XY-Response Curve.</strong> The implementation is very simple, so I won&#8217;t describe it here. A C++ implementation is available in the <a href="http://code.google.com/p/specialnumbers/">Special Numbers Library</a>; a Python implementation is available with the example below. Here I simply explain the usage as it relates to this tutorial.  We proceed as follows:</p>
<ul>
<li>First, we construct an xy-response curve from our samples of the inverse accumulative probability.</li>
<li>Then we sample this curve at regular intervals, and load it into a ordinary response curve (we do this, simply because the ordinary response curve is much faster than the xy-version).</li>
</ul>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #008000">//...</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">int</span> oldSampleCount = 7;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">int</span> newSampleCount = 20;

<span style="color: #0000ff">float</span> inputMin = 0.0f;
<span style="color: #0000ff">float</span> inputMax = 3.2f;

<span style="color: #008000">//note: input and output is swopped arround, because we want the inverse!</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">XYResponseCurve&lt;<span style="color: #0000ff">float</span>, oldSampleCount&gt; xyCurve(outputSamples, inputSamples);</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i = 0; i &lt; newSampleCount; i++)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">{</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">    input = ((float) i / (newSampleCount - 1)) * (inputMax - inputMin) + inputMin;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">    uniformOutput[i] = xyCurve(input);</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">}</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">ResponseCurve&lt;<span style="color: #0000ff">float</span>, newSampleCount&gt; curve(inputMin, inputMax, uniformOutput);</pre>
</div>
<p>   <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/uniform.png" alt="uniform" width="481" height="289" /></p>
<h3>4. Map uniform random numbers to the input range of the IAPDF, and calculate the output</h3>
<p>Now that we have the response curve, we can map uniform random numbers to the appropriate input range. For the example above, we need to map to the range [0, 3.2]. The snippet below shows how to generate random numbers with the distribution shown above:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #008000">//...create the curve c</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">float</span> input = random(); <span style="color: #008000; ">//Uniformly distributed function between 0 and 1.</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">float</span> scaledInput = r * (inputMax - inputMin) + inputMin;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #0000ff">float</span> output = curve(scaledInput);</pre>
</div>
<p>   The graph below shows how 10 000 random numbers are distributed. It follows the original graph closely; the discrepancy at -10 is caused by the way samples are counted (all samples between -10 (inclusive) and 0 (exclusive) are counted and plotted at -10.   <img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/result.png" alt="result" width="481" height="289" /></p>
<h2>Tips and Pitfalls to Avoid</h2>
<ol>
<li>Generate sequences for all intermediary steps.</li>
<li>Use Excel, Calc, or some other spread sheet program to debug these sequences visually when things go wrong.</li>
<li>It is very easy to get confused with input, and output, especially after the swap. Watch out for this!</li>
<li>It is easy to get confused with the number of samples for the various sequences.</li>
<li>If you implement your own Response Curve data structure, unit tests will save you huge amounts of time.</li>
<li>Always make sure that you sample enough points, especially if your original distribution graph has rapid changes in it.</li>
<li>Always confirm that your random output follows the distribution you wanted.</li>
<li>It might be faster to use this method even when mathematical formulas are available.</li>
</ol>
<h2>Downloads</h2>
<h3>Example C++ Source Code</h3>
<p><a href="http://code-spot.co.za/downloads/cpp_examples/arbitrary_distribution.cpp">http://code-spot.co.za/downloads/cpp_examples/arbitrary_distribution.cpp</a> Requires <span style="font-weight: normal;"><a href="http://code.google.com/p/specialnumbers/">Special Numbers Library</a></span></p>
<h3>Example Python Source Code</h3>
<p><a href="http://code-spot.co.za/downloads/python_examples/random_distributions.py">http://code-spot.co.za/downloads/python_examples/random_distributions.py</a></p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/15/generating-random-points-from-arbitrary-distributions-for-2d-and-up/' rel='bookmark' title='Permanent Link: Generating Random Points from Arbitrary Distributions for 2D and Up'>Generating Random Points from Arbitrary Distributions for 2D and Up</a></li>
<li><a href='http://code-spot.co.za/2009/04/28/generating-random-integers-with-arbitrary-probabilities/' rel='bookmark' title='Permanent Link: Generating Random Integers With Arbitrary Probabilities'>Generating Random Integers With Arbitrary Probabilities</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Google App Engine for Games</title>
		<link>http://code-spot.co.za/2008/09/14/google-app-engine-for-games/</link>
		<comments>http://code-spot.co.za/2008/09/14/google-app-engine-for-games/#comments</comments>
		<pubDate>Sun, 14 Sep 2008 08:42:12 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/blog/?p=5</guid>
		<description><![CDATA[Google App Engine has many properties that makes it suitable for indie development. Two articles in Dev.Mag look at GAE for game development (Issue 24 and Issue 25). The first is an overview of Google App Engine, with some focus on games. The second is a tutorial that explains the implementation of &#8220;Guess a Number&#8221; [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="size-medium wp-image-31 alignleft" title="gae" src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/gae.jpg" alt="" width="111" height="111" />Google App Engine has many properties that makes it suitable for indie development. Two articles in Dev.Mag look at GAE for game development (<a href="http://devmag.org.za/uploads/DevMag_Issue24.zip" class="broken_link">Issue 24</a> and <a href="http://devmag.org.za/uploads/DevMag_Issue25.zip" class="broken_link">Issue 25</a>). The first is an overview of <a href="http://code.google.com/appengine/">Google App Engine</a>, with some focus on games. The second is a tutorial that explains the implementation of &#8220;<a href="http://code-spot.appspot.com/game/">Guess a Number</a>&#8221; on Google App Engine, for which you can <a href="http://code.google.com/p/code-spot/">download the code</a>.  For the tutorial you will need:</p>
<ul>
<li><a id="Requirements">Python runtime (</a><a rel="nofollow" href="http://www.python.org/download/">http://www.python.org/download/</a>).</li>
<li>A Google App Engine account (<a rel="nofollow" href="http://appengine.google.com/">http://appengine.google.com/</a>).</li>
<li>The Google App Engine SDK (<a rel="nofollow" href="http://code.google.com/appengine/downloads.html">http://code.google.com/appengine/downloads.html</a>).</li>
<li>The files for this tutorial (<a rel="nofollow" href="http://code-spot.googlecode.com/files/code-spot_0.1.zip">http://code-spot.googlecode.com/files/code-spot_0.1.zip</a>).</li>
<li>Your favourite web browser and general purpose code editor.</li>
</ul>
<p><span id="more-5"></span>Below are some links to related web sites.</p>
<h2>Links</h2>
<h3>Reference</h3>
<p><a title="http://appengine-cookbook.appspot.com/" href="http://appengine-cookbook.appspot.com/">http://appengine-cookbook.appspot.com/</a> Google App Engine Cookbook.</p>
<p><a href="http://www.poromenos.org/tutorials/python">http://www.poromenos.org/tutorials/python</a> Learn Python in 10 minutes.</p>
<p><a href="http://www.djangoproject.com/documentation/templates/">http://www.djangoproject.com/documentation/templates/</a> Django template reference.</p>
<p><a href="http://www.djangobook.com/en/1.0/chapter04/">http://www.djangobook.com/en/1.0/chapter04/</a> Django templates from the Django book.</p>
<p><a href="http://code.google.com/appengine/articles/rpc.html">http://code.google.com/appengine/articles/rpc.html</a> Using AJAX with Google App Engine.</p>
<p><a href="http://aralbalkan.com/1318">http://aralbalkan.com/1318</a> Using Flash with Google App Engine.</p>
<h3>Games on Google App Engine</h3>
<p><img class="alignleft size-medium wp-image-37" title="ajax_battle" src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/ajax_battle.png" alt="" width="200" height="179" align="left" /> <a href="http://www.ajaxbattle.net/">http://www.ajaxbattle.net/</a> AjaxBattle is a multi-player real-time strategy game for 2 to 4 players. It is a web-based version of the old X-Windows game xbattle. Works best with Firefox 2.</p>
<p><a href="http://uboggle.appspot.com/" class="broken_link">http://uboggle.appspot.com/</a> uBoggle is a app to play Boggle &#8211; the popular word making game.</p>
<p><a href="http://mnk.appspot.com/">http://mnk.appspot.com/</a> This game lets users set up most types of x-in-a-row type games – can be played against another online player, or the computer.</p>
<p><img class="alignleft size-medium wp-image-38" title="monkey" src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/monkey.png" alt="" width="200" height="188" /><a href="http://gaesudoku.appspot.com/">http://gaesudoku.appspot.com/</a> Sudoku.</p>
<p><a href="http://games.wtanaka.com/" class="broken_link">http://games.wtanaka.com/</a> Card and board games.</p>
<p><a href="http://www.guessasketch.com/">http://www.guessasketch.com/</a> A multiplayer game where players guess what other players draw.</p>
<p><a href="http://achi.appspot.com/">http://achi.appspot.com/</a> A tic-tac-toe-like board game.</p>
<p><a href="http://photomunchers.appspot.com/">http://photomunchers.appspot.com/</a> and <a href="http://jamendogame.appspot.com/">http://jamendogame.appspot.com/</a>. These two games are really ways to get users to tag images and music, respectively. They illustrate how to tap into other networks.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/09/14/google-app-engine-for-games/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>60 Ways to make Game Maker projects more maintainable</title>
		<link>http://code-spot.co.za/2008/09/06/60-ways-to-make-game-maker-projects-more-maintainable/</link>
		<comments>http://code-spot.co.za/2008/09/06/60-ways-to-make-game-maker-projects-more-maintainable/#comments</comments>
		<pubDate>Sat, 06 Sep 2008 17:37:26 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[Game Maker]]></category>
		<category><![CDATA[good practices]]></category>
		<category><![CDATA[maintainability]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/blog/?p=69</guid>
		<description><![CDATA[Game Maker is a great tool; it is especially suited for rapid development and small projects. However, as a project becomes bigger, it becomes more difficult to find things, easier to break it, and generally harder to work on. This is of course true for any production environment, and there are many things you can [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/09/14/google-app-engine-for-games/' rel='bookmark' title='Permanent Link: Google App Engine for Games'>Google App Engine for Games</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.yoyogames.com/make">Game Maker</a> is a great tool; it is especially suited for rapid development and small projects. However, as a project becomes bigger, it becomes more difficult to find things, easier to break it, and generally harder to work on. This is of course true for any production environment, and there are many things you can do to tame the beast of scale. Here are 60 things to make Game Maker projects more maintainable.</p>
<p><span id="more-69"></span></p>
<h2>General</h2>
<h3>Use postfixes to prevent name clashes</h3>
<p>It is possible (but incorrect) to give, for example, an object and sprite the same name. To prevent this from happening accidentally, use postfixes to distinguish different types of game-elements (sprites, sounds, objects, rooms, and so on). Use postfixes instead of prefixes &#8211; this makes it easier to find specific objects in the object tree, and to read your code.</p>
<p><strong>[EDIT]</strong></p>
<p>The following Game Maker file illustrates how name clashes can lead to bugs:</p>
<p><a href="http://code-spot.co.za/downloads/game_maker/test_name_clash.gmk">test_name_clash.gmk (19.2KB)</a></p>
<h3>Use folders to structure resources</h3>
<p>Generally, the object folder structure should follow the inheritance hierarchy, with further separation as necessary. Other resource folders should reflect the groups of the objects to which they belong, or be subdivided by their function.</p>
<h3>Use a Development Standards Document</h3>
<p>Compile and work from a development standards document to promote consistency across projects and between developers. At the very least, this document should define:</p>
<ul>
<li>your naming convention;</li>
<li>your folder structure;</li>
<li>your layering convention (see below);</li>
<li>positions of controllers; and</li>
<li>icon code (if you use one &#8211; see below).</li>
</ul>
<h2>Resources</h2>
<h3>Do not make the embedded drawing tool part of the pipeline</h3>
<p>&#8230;if your main drawing tool is an external tool. This prevents every change from becoming an error-prone two-step process.</p>
<h3>Use dynamic content</h3>
<p>Loading images from files, creating sprites and objects dynamically, and constructing levels programmatically makes it a lot easier to change assets, since the Game Maker file doesn&#8217;t need to change whenever the asset changes.</p>
<h3>Design art around a grid</h3>
<p>Use a grid, and design objects for that grid to simplify world construction and object placement.</p>
<h2>GUI</h2>
<h3>Draw your GUI in a separate room</h3>
<p>&#8230;and overlay this room over every level.</p>
<h3>Use a widget-and-style approach for complicated GUIs</h3>
<p>For complicated GUIs, it is worth defining generic widgets (such as buttons or menus) that can be configured using parameters. Keep style elements (colour, font, borders) in separate objects. This makes it easier to change styles in one place, instead of in every widget. It also makes it easier to make the GUI skinnable.</p>
<h3>Do as much of the GUI layout programmatically as is possible</h3>
<p>Laying out a complicated GUI can be extremely labour intensive, so that changes to the GUI layout can become unmanageable. Using layout functions can greatly improve the ease with which the GUI can be extended or otherwise modified.</p>
<h2>Extensions</h2>
<h3>Make extensive use of Game Maker extensions</h3>
<p>Using <a href="http://www.yoyogames.com/make/extensions">extensions</a> provide several advantages:</p>
<ul>
<li>extensions make it possible to reuse functions more effectively;</li>
<li>extensions make it easier for more people to work together (people making extensions needn&#8217;t modify the main Game Maker file); and</li>
<li>extensions can be put under separate version control, and so reduce the impact of a roll-back.</li>
</ul>
<p>Every script function you define should be considered for implementation as a DnD action in an extension. It is useful to have a general usage extension, that you can use across projects, as well as a project-specific extension. Remember to <a href="http://gmbase.cubedwater.com/">check</a> whether somebody has not already implemented a particular function in an extension!</p>
<h3>Document extension actions properly</h3>
<p>Don&#8217;t leave any of the fields (such as Description, List Text, and Hint Text) in the extension maker empty, and take care to make the List Text and Hint Text display as much field information as possible (by using the @keywords &#8211; see the Extension Maker Help Documentation).</p>
<h3>Spend time making (or searching for) proper icons for your extension actions</h3>
<p>Forgetting what an action does kills maintainability; a descriptive icon will significantly reduce this.</p>
<h3>Always define a script function for every DnD action</h3>
<p>This way it is easier to unit-test features (see below), and possible to use the functionality from a script.</p>
<h2>Actions and Scripts</h2>
<h3>Learn how to use the merge facility effectively to facilitate for teamwork</h3>
<p>This is not Game Maker&#8217;s safest feature: there are many pitfalls, for example:</p>
<ul>
<li>be careful for name clashes; and</li>
<li>all elements get new IDs (so be careful if you use hard=coded IDs).</li>
</ul>
<p>However, with careful planning, this feature can help several developers can work together on a project. for example, every developer works on his / her own file, which is merged into a final game.</p>
<h3>Avoid complicated branch logic in the GUI action editor</h3>
<p>Complicated branch statements are hard to read in the DnD interface, and editing these constructs is error-prone. Put complicated branch logic in a script.</p>
<p><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/complicated-branches.png" alt="complicated_branches" width="259" height="392" /></p>
<h3>Avoid assigning too many variables in the GUI action editor</h3>
<p>Rather use a script. This way, tweaking the values of several variables becomes a lot easier.</p>
<h3>Never use the Execute Code action</h3>
<p>Always use the Run Script action, and put the code in a separate script. This way the code is easier to find, reuse, and use in an extension.</p>
<h3><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/if-blocks.png" alt="if_blocks" width="163" height="100" align="left" />Always use blocks to demarcate if-then-else constructs in the DnD interface</h3>
<p>&#8230;even when a statement block is only one line. This makes it much more convenient to add stements to the block in future, and reduces the risk of introducing a bug because of incorrect blocks.</p>
<h3>Make use of named global constants</h3>
<p>Using named constants makes code easier to read, less error-prone, and easier to change the value. If you define them in the Global Game Settings dialog, they appear highlighted in your code.</p>
<h3>Use expressions as constant values</h3>
<p>You can use expressions when you define constants (in the Game Settings dialog). For instance, to define a colour, you can set the value as make_color(255, 128, 64).</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" src="http://code-spot.co.za/blog/wp-content/uploads/2008/09/constants.png" border="0" alt="constants" width="473" height="141" /></p>
<h3>Initialise the variables of an object in one place</h3>
<p>&#8230;either in a single file, or as DnD actions in the Create event of that object. It might be better to do it in a file if you need to document usage.</p>
<h3>Declare global variables in one file only</h3>
<p>This serve as an easy way to see all the global variables, and is a good place to document their usage.</p>
<h3>Always assign function arguments to named variables</h3>
<p>Like this:</p>
<div>
<div style="font-size: 8pt; margin: 20px 0px 10px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border: gray 1px solid; padding: 4px;">
<div style="font-size: 8pt; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   1:</span> {</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   2:</span>     <span style="color: #0000ff">var</span> width, height;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   3:</span>     width = argument0;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   4:</span>     height = argument1;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   5:</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   6:</span>     <span style="color: #0000ff">return</span> width * height;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   7:</span> }</pre>
<p> </p></div>
<p> </p></div>
</div>
<p>Notice that you can immediately deduce what the arguments should be, and that this function returns an area.</p>
<h3>Use the with-statement as a for-each loop</h3>
<p>The with-statement can be used as a for-each loop over the instances of an object (where the variable <code>self</code> serves as the loop counter).</p>
<p>The following two examples illustrate this:</p>
<div style="font-size: 8pt; margin: 20px 0px 10px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border: gray 1px solid; padding: 4px;">
<div style="font-size: 8pt; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   1:</span> <span style="color: #008000">//kills all monsters</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   2:</span> with(monster)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   3:</span> {</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   4:</span>     instance_destroy();</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   5:</span> }</pre>
<p> </p></div>
</div>
<p> </p>
<div style="font-size: 8pt; margin: 20px 0px 10px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border: gray 1px solid; padding: 4px;">
<div style="font-size: 8pt; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   1:</span> <span style="color: #008000">//Resets all object positions to 0 0</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   2:</span> with(all)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   3:</span> {</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   4:</span>     x = 0;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   5:</span>     y = 0;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   6:</span> }</pre>
<p> </p></div>
</div>
<h2>Objects</h2>
<h3>Use sprite frames to represent object states,</h3>
<p>&#8230;rather than using separate sprites or objects per state.</p>
<h3>Use inheritance</h3>
<p>&#8230; and refactor aggressively throughout development. See <a href="http://www.gamedotdev.co.za/index.php?option=com_content&amp;task=view&amp;id=25&amp;Itemid=29">The Power of Inheritance</a>.</p>
<h3>Use tiles instead of sprites for the visual appearance of objects</h3>
<p>See for example <a href="http://www.youtube.com/watch?v=zM3iQbzM4C4">http://www.youtube.com/watch?v=zM3iQbzM4C4</a>.</p>
<h3>Use unique sprites even for invisible and control objects</h3>
<p>This makes it easier to place these objects in rooms, and identify them properly. If you cannot spend time making proper visually descriptive icons, use a coding system (based on colour, shape and text).</p>
<h3>Avoid creation order dependence&#8230;</h3>
<p>Creation order dependence is hard to remember, and thus something that is easy to break. Creation order dependence can often be eliminated by removing initialisation code, and making sure that the update function will do the work the first time it is called.</p>
<h3>&#8230;Or use spawning to control order dependence</h3>
<p>When creation order dependence is unavoidable, let objects spawn those objects which should be created after them. This way you control the creation order, but also make it explicit (and thus, not necessary to remember).</p>
<h3>Use parameterised objects instead of separate objects where possible&#8230;</h3>
<p>For example, when the only difference between two objects is their sprites, you could do better to make them the same object, and control the sprite that is used by a parameter. The fewer objects you have, the easier it is to restructure or otherwise change the objects.</p>
<h3>&#8230;But use separate objects to avoid type checking</h3>
<p>If you have to do type checking to distinguish between objects to differentiate behaviour, you should use separate objects. This is especially true when you have to perform group operations.</p>
<h3>Use Game Maker objects to mimic record data types</h3>
<p>For example, you might create an Abilities object that contains variables for strength and magic power. Every character in the game can make its own Abilities object, which allows you to write code like this:</p>
<div style="font-size: 8pt; margin: 20px 0px 10px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border: gray 1px solid; padding: 4px;">
<div style="font-size: 8pt; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   1:</span> <span style="color: #0000ff">if</span> (monster.abilities.strength &gt; human.abilities.strength)</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   2:</span> {</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   3:</span>     kill_human(human);</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   4:</span> }</pre>
<p> </p></div>
</div>
<p>Of course, nowhere in the game the user will actually see an Abilities object, nor will it ever be put in a room (as would monsters, for example).</p>
<h3>Use object composition</h3>
<p><a href="http://en.wikipedia.org/wiki/Object_composition">Object composition</a> is a great way to reuse objects, and is a great substitute for multiple inheritance (which is not available in Game Maker). For example, a monster can be composed of its static attributes (strength, aggressiveness), its current state (health, anger) and its items (weapons and potions).</p>
<h3>Avoid Using the Test Chance action</h3>
<p>Because it is only possible to express a limited set of probabilities with a single Test Chance action, it is not easy to tweak it. Rather use a Test Expression action, with the expression something like:</p>
<div>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">random(100) &lt;= 60</pre>
</div>
<h2>Idioms</h2>
<h3>Choose a layering convention</h3>
<p>Choose it up-front, document it, and keep to it! For example, choose the layers for the background, static elements, dynamic elements, main character, and effects (such as particles and glows).</p>
<h3>Use the controller idiom</h3>
<p>Controllers are used to group together logic that does not belong to an in-game-object (such as the player, a monster, or item). Typically, controllers are used to maintain room state and global game state, and to draw interface elements.</p>
<h3>Choose a standard position on screen for controllers</h3>
<p>This makes them easy to find, and avoids duplication.</p>
<h3>Standardise idioms that are relevant to your game</h3>
<p>For example, I always use the init-update-draw idiom for each interesting object (i.e. init_monster, update_monster, draw_monster). Recognise the patterns in your own games, document them, and follow these as standards.</p>
<h3>Avoid putting code in the room initialisation section</h3>
<p>It is usually better to put initialisation code in a controller, and it is necessary if you want the code to execute before other objects are created. It is easy to forget about code in the room initialisation section, which can result in code duplication and hard-to-track bugs.</p>
<h2>Time</h2>
<h3>Use timelines with care</h3>
<p>Step numbers can only be hard-coded values. Thus, tweaking a set of timelines can become a maintenance nightmare if their step numbers are somehow related to each other or other game parameters. It might be a better idea to use a script and counter approach, which will allow you to define these relationships (for example, the growling time of a monster is always proportional to it&#8217;s size).</p>
<p>Use a script file to document important global issues, such as script entry points, general architecture of the game, and so on.</p>
<h3>Design your game around fixed unit time intervals</h3>
<p>For example, everything in the game happens in intervals of multiples of ten steps. Using this scheme makes constructing time-dependent events easier for the same reason that using a grid make level-construction easier.</p>
<h3>Never use frame rate to change simulation speed</h3>
<p>This can lead to ugly glitches in animation. Simulation speed is better controlled with a time scale variable independent of the frame rate.</p>
<h3>Always animate sprites at the same frame rate</h3>
<p>It is just easier not to have to think about this for every object. And if you need to tweak the frame rates of sprites individually, you can easily find yourself in a maintenance nightmare.</p>
<h3>Do not use any text in your graphics</h3>
<p>When text is part of a graphic, it is very hard to change it. Also, it means that you need a new graphic for each piece of text, which puts a bottleneck on the amount you can produce. Drawing text with Game Maker is a pain, but it will save a lot of work in the long run, and will make it easier to make the game data-driven and scale gracefully.</p>
<h2>Events</h2>
<h3>Choose a fixed place to call the parent event</h3>
<p>You should always call the parent event either first, or last, and do it consistently throughout (the game, or even better &#8211; all your games). This reduces the chance of having hard-to-debug logic as a result of calling the parent event, especially along complicated hierarchies.</p>
<h3>Never rely on the order of events for something to work</h3>
<p>Even though the order is well defined, and can be expected to stay the same for future releases of Game Maker, it is hard to remember this order, and hard to remember that the order for a piece of logic is important. Therefor mistakes are easily made. This is especially true in teamwork, where  reliance on event order might not be communicated properly.</p>
<h3>Avoid using custom events when possible&#8230;</h3>
<p>Custom events are not named (you have to use indices to refer to them), and hence it is hard to remember which event does what.</p>
<h3>&#8230;But use custom events instead of global states</h3>
<p>Custom events can be used to broadcast changes in game conditions. This not only eliminates global variables, but also the if-statements that are necessary to check the global state at every step.</p>
<h2>Testing and Debugging</h2>
<h3>Use asserts</h3>
<p>Define an assert function, and use it to confirm game conditions. Using asserts make it much easier to make changes safely.</p>
<h3>Always make sure that the number of enums is correct</h3>
<p>When you iterate over enums, you usually have a constant that holds the number of enums in a set. It is important to assert that this number is correct (it is easy to forget to update this number when inserting or deleting enums). Do it in a place where it is easy to see how many there should be. Below is an example.</p>
<div style="font-size: 8pt; margin: 20px 0px 10px; overflow: auto; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border: gray 1px solid; padding: 4px;">
<div style="font-size: 8pt; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;">
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   1:</span> globalvar activity_dict;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   2:</span></pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   3:</span> activity_dict[0] = bed;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   4:</span> activity_dict[1] = tv;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   5:</span> activity_dict[2] = stove;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   6:</span> activity_dict[3] = washingmachine;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   7:</span> activity_dict[4] = radio;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   8:</span> activity_dict[5] = noone;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">   9:</span> activity_dict[6] = computer;</pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">  10:</span> </pre>
<pre style="font-size: 8pt; margin: 0em; overflow: visible; width: 100%; color: black; line-height: 12pt; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4; border-style: none; padding: 0px;"><span style="color: #606060">  11:</span> assert(ACTIVITY_COUNT == 7, <span style="color: #006080">"The wrong number of activities have been initilised in the script 'init'"</span>);</pre>
<p> </p></div>
</div>
<h3>Always check that functions do not return noone</h3>
<p>When searching for the nearest instance of an object, for example, make sure that the function does not return noone (even when you think it is impossible). At the very least, display a helpful message. It is common that your assumption of impossibility might be violated by future changes.</p>
<h3>Use unit tests</h3>
<p>Write <a href="http://en.wikipedia.org/wiki/Unit_testing">unit tests</a> for all your script functions. You can also set up unit tests in special test rooms, that will test object behaviour in specific preset conditions. When you are protected with unit tests, you make make changes boldly. Log success and failures to a file.</p>
<h3>Make unit tests runnable with command line parameter</h3>
<p>This way, unit testing can be automated. Use the log file to detect failures. You can use the <code>parameter_count</code> and <code>parameter_string</code> functions to get the command line parameters fed to the game.</p>
<h3>Use a Game Maker file to put in unit tests for the general purpose library</h3>
<p>This special file will not only help detect bugs in your extensions, but also serve as a usage document.</p>
<h3>Implement a debug menu screen</h3>
<p>Implement a screen with special debug functionality, and only display this when the game is run under a special mode. The debug screen should have ways to:</p>
<ul>
<li>run any level;</li>
<li>run scratchpad levels (see below); and</li>
<li>run unit tests.</li>
</ul>
<h3>Implement a test room for a scratch pad</h3>
<p>It is often necessary to test a new feature in a room that is already part of the game. Resist the temptation to test new features in existing rooms. It is easy to mess up a room when implementing a new, untested feature, and it can be hard to remove this feature if it doesn&#8217;t work out. Rather, have a minimal room ready that is fully integrated into the game, and use it as a scratchpad to test new features.</p>
<h3>Implement debug drawing mode</h3>
<p>In many cases your game can be too complex to rely on logging or inspecting variables one by one to perform adequate debugging. Drawing extra information with instances, and using colours and other graphical elements effectively, can make it a lot easier to spot errors. This technique is especially useful for AI and simulation.</p>
<h3>Implement cheats</h3>
<p>It is not only a useful debugging aid, but also guides the design (the technical design &#8211; not the game design!) to be more modular and flexible. A cheat (for example, a God-mode) that is hard to implement, can indicate a problem in the design (for instance, deductions to health is made in several objects, instead of in a single one or just a few).</p>
<h3>Use a global game options to switch on and off some features</h3>
<p>For example, this can be used to display debug info, or skip some eye-candy to increase load speeds. Do not chaotically comment in and out pieces of code or action logic to achieve this effect: it is error prone in larger projects and in teams.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/09/14/google-app-engine-for-games/' rel='bookmark' title='Permanent Link: Google App Engine for Games'>Google App Engine for Games</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/09/06/60-ways-to-make-game-maker-projects-more-maintainable/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

