<?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>Hey, Javascript!</title>
	<atom:link href="http://heyjavascript.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://heyjavascript.com</link>
	<description>A blog about game programming in Javascript</description>
	<lastBuildDate>Tue, 30 Apr 2013 00:50:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>For loops, while loops, fruit loops&#8230;</title>
		<link>http://heyjavascript.com/for-loops-while-loops-fruit-loops/</link>
		<comments>http://heyjavascript.com/for-loops-while-loops-fruit-loops/#comments</comments>
		<pubDate>Tue, 30 Apr 2013 00:35:46 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=786</guid>
		<description><![CDATA[There are a lot of different kinds of ways to write loops in Javascript. You have your standard for loop and while loop, but beyond that you have the do-while loop, the object properties loop, and lots of different variation of all four &#8220;basic&#8221; loops. In this post, we&#8217;ll examine the four basic loops, the [...]]]></description>
				<content:encoded><![CDATA[<p>There are a lot of different kinds of ways to write loops in Javascript. You have your standard for loop and while loop, but beyond that you have the do-while loop, the object properties loop, and lots of different variation of all four &#8220;basic&#8221; loops. In this post, we&#8217;ll examine the four basic loops, the reverse for loop, the reverse while loop, the short reverse while loop, object property loops, and more. I&#8217;ll also explain a bit about loop unrolling and where/how it can help you optimize your code. Read on, if you dare!</p>
<p><span id="more-786"></span></p>
<h2>The classic for loop</h2>
<p>What I like to call the <strong>classic for loop</strong> is perhaps the most basic of all loops in Javascript. It looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
for(var i = 0; i&lt;10; i++) {
	// do stuff with i
}
</pre>
<p>This is the basic loop model provided by Javascript and is by far the most common variation of the for loop. You initialize an iterator (<span class="code-tag">i</span>), set a finish condition for <span class="code-tag">i</span>, and finally specify how <span class="code-tag">i</span> will be modified each iteration of the loop. Since <span class="code-tag">i++</span> is just a statement, it&#8217;s possible to modify <span class="code-tag">i</span> however you want in the loop header using statement operators. <span class="code-tag">for(var i = 0; i&lt;10; i+= 2)</span> will increment i by two each iteration, for example.</p>
<p><strong>Note</strong>: You have to be careful. If you initialize the loop without putting <span class="code-tag">var</span> in front of the iterator variable (like this: <span class="code-tag">for(i = 0; i&lt;10; i++)</span>), you&#8217;ll turn it into a global variable, which may not be what you were intending to do.</p>
<h3>Using the for loop to iterate through an array</h3>
<p>Assuming you have an array called things, you can use a for loop to iterate through it like so:</p>
<pre class="brush: jscript; title: ; notranslate">
for(var i = 0, len = things.length; i&lt;len; i++) {
	var currentThing = things[i];
}
</pre>
<h2></h2>
<h2>The classic while loop</h2>
<p>The while loop is another basic, very familiar loop. It&#8217;s a little more complicated than the for loop, but not by much. You can&#8217;t write it all on one line, but it&#8217;s about as simple as they come:</p>
<pre class="brush: jscript; title: ; notranslate">
var i = 0;
while(i &lt; 10) {
	// do stuff with i

	i++;
}
</pre>
<p>As you can see, you have to initialize i outside the loop and then increment it inside the loop. That&#8217;s why this method isn&#8217;t quite as clean as the basic for loop. However, I think it&#8217;s a bit easier to understand, because it&#8217;s more broken up. Because of this broken up format, it&#8217;s possible to do a lot with while loops, as you&#8217;ll see shortly.</p>
<p><strong>Note</strong>: You&#8217;ll want to make sure you do all your loop operations before you increment your iterator variable; otherwise, you risk skipping an iteration of your loop.</p>
<h3>The quick n&#8217; dirty while loop</h3>
<p>This method is one of the shortest methods of writing a loop, and it&#8217;s probably one of fastest, too.</p>
<pre class="brush: jscript; title: ; notranslate">
var i = 10;
while(i--) {
	// do stuff with i, which is in the range 9 to 0
}
</pre>
<p>The reason this works and isn&#8217;t an infinite loop is that the while loop performs each iteration only when its condition evaluates to a truthy value (that is, anything that can&#8217;t be coerced into 0, or <span class="code-tag">false</span>). Since 0 is a falsy value, the condition evaluates to false and the loop performs its last iteration before exiting. Pretty neat, huh?</p>
<h3>Using the while loop to iterate through an array</h3>
<p>There are a few different ways to iterate through an array with a while loop, but they&#8217;re just slight variations of the previous while loops. Here&#8217;s the basic forward-iterating while loop:</p>
<pre class="brush: jscript; title: ; notranslate">
// forward declaring our variables because that's recommended.
var 	len = things.length,
		currentThing,
		i;

while(i &lt; len) {
	currentThing = things[i];
	// do stuff with the current thing

	// increment our counter
	i++;
}
</pre>
<p>As you can see, I cached the length of the array to speed up performance a micro-bit. Don&#8217;t do this if you&#8217;re modifying the length of your array inside the while loop. Instead, compare <span class="code-tag">i</span> to the length of the array every iteration.</p>
<p>And here&#8217;s the reverse while loop:</p>
<pre class="brush: jscript; title: ; notranslate">
var 	i = things.length,
		currentThing;

while(i--) {
	currentThing = things[i];
	// do stuff with the current thing
}
</pre>
<p>This is the preferred way to loop through an array if you&#8217;re going to use a while loop. Since it&#8217;s reversed, it doesn&#8217;t care if you&#8217;re modifying the length of the array or chucking elements in each iteration (as long as you aren&#8217;t modifying elements ahead of the loop, of course). You also don&#8217;t have to define as many variables, since we no longer need to cache the length of the array.</p>
<h2>The do-while loop</h2>
<p>The do-while loop is similar to the while loop in many ways, barring syntax. It&#8217;s a broken up loop in which you have to manually increment your variable. However, the key difference here is that the do-while loop executes the statement and <em>then </em>evaluates the provided condition, meaning the loop will execute at least once. Here&#8217;s what it looks like:</p>
<pre class="brush: jscript; title: ; notranslate">
var i = 0;

do {
	// do stuff with i, which is in the range 0-9

	i++; // remember, increment your counter at the very end of the loop
} while (i &lt; 10);
</pre>
<p>As you can see, not too different from the while loop, except for a little change in the syntax. The main difference is, even if the condition at the bottom evaluates to false, the loop will still run once:</p>
<pre class="brush: jscript; title: ; notranslate">
var i = 0;

do {
	i++;
} while (i &lt; -1); // still evaluates once
</pre>
<p>I haven&#8217;t really found a use for the do-while loop yet, so if you do, feel free to let me know what you did with it in the comments below. <img src='http://heyjavascript.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<h2>The Array.forEach loop</h2>
<p><span class="code-tag">Array.forEach</span> is a relatively new addition to the ECMA-262 standard, so it&#8217;s not seen a lot of use yet, nor do many older browsers support it. Nonetheless, there is a shim for it and it&#8217;s a remarkably useful function. Here&#8217;s some example usage:</p>
<pre class="brush: jscript; title: ; notranslate">
var a = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;];

a.forEach(function(element, index, array) {
      console.log(&quot;Element: &quot; + element + &quot; at index &quot; + index);
});
</pre>
<p>As you can see, the syntax is quite simple. Simply call <span class="code-tag">forEach</span> on an array and pass in the function you want executed on each of the array&#8217;s elements. As I mentioned before, for browsers that don&#8217;t natively support forEach, there&#8217;s a shim (which can be found in <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" target="_blank">Mozilla&#8217;s forEach documentation</a>):</p>
<pre class="brush: jscript; title: ; notranslate">
if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i &lt; len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}
</pre>
<p>Simply include the above code in your Javascript project and you&#8217;ll have full support for the <span class="code-tag">forEach</span> function. Although it really just serves as syntactic sugar to cover the for loop, you have to admit it is quite nice to have.</p>
<h2></h2>
<h2>Object property loops</h2>
<p>The object property loop is a way of looping over the properties of objects that aren&#8217;t arrays, since you can&#8217;t really use the normal for loop or while loop to loop through the elements of an object effectively. Here&#8217;s how it works:</p>
<pre class="brush: jscript; title: ; notranslate">
var currentProp;

for(prop in obj) {
    if(obj.hasOwnProperty(prop)) {
        currentProp = obj[prop];
        // do something with this property, where currentProp is the actual value
        // you're looking at, and prop is the name of that value on the object.
    }
}
</pre>
<p>One of the things you need to make sure you do is check to make sure the property of the object you&#8217;re looping over actually belongs to that object and hasn&#8217;t come down the prototype chain. If you don&#8217;t do that, properties such as functions from the object&#8217;s prototype will become part of the loop. Not cool.</p>
<p>Another thing to be aware of is that the object won&#8217;t be looped over necessarily in the order that the properties are specified, nor even in the same order each time the properties are looped through. A plain object is not like an array in this respect, so you&#8217;ve got to be careful how you handle it.</p>
<h2></h2>
<h2>Partial loop unrolling (and when not to use it)</h2>
<p>Partial loop unrolling is a nice trick to have up your sleeve, especially if you&#8217;re working with large arrays (arrays with entries in the thousands or more). Basically, loop unrolling just means covering more than one element in each iteration of your loop. Here&#8217;s an example:</p>
<pre class="brush: jscript; title: ; notranslate">
var currentThing;

for(var i = 0, len = things.length; i&lt;len; i+=4) {
    currentThing = things[i];
    // do something with the current thing

    currentThing = things[i+1];
    // do something with the next thing

    currentThing = things[i+2];
    // do something with the next next thing

    currentThing = things[i+3];
    // do something with the last next thing
}
</pre>
<p>Since you&#8217;re effectively cutting your amount of iterations by half, or two thirds, or three quarters, or four fifths, or whatever amount you choose, it&#8217;s easy to see why this method should speed up your performance. However, interestingly enough, the gain you get by partially unrolling your loop isn&#8217;t that great. Therefore this isn&#8217;t a very effective method for speeding up your code until you&#8217;ve got arrays with elements numbering in the thousands (or higher).</p>
<h2></h2>
<h2>Wrapping up</h2>
<p>Well, that just about covers it for the most commonly used loops. I hope this helps, and, as always, If I&#8217;ve made any mistakes or typos, or if you just want to suggest something, feel free to leave me a note in the comments! Thanks for reading.</p>
<p>Oh, and as for fruit loops&#8230; do I really have to explain those? <img src='http://heyjavascript.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/for-loops-while-loops-fruit-loops/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Roguelike with a message-based user interface?</title>
		<link>http://heyjavascript.com/a-roguelike-with-a-message-based-user-interface/</link>
		<comments>http://heyjavascript.com/a-roguelike-with-a-message-based-user-interface/#comments</comments>
		<pubDate>Fri, 12 Apr 2013 22:49:19 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=746</guid>
		<description><![CDATA[One of the ideas that I&#8217;ve been rolling around in my head lately is the possibility of a roguelike completely lacking in any sort of graphical user interface (GUI). Basically, this means the game would have no menus or displays of any sort&#8211;not even a health display or or turn counter&#8211;on the main screen of [...]]]></description>
				<content:encoded><![CDATA[<p>One of the ideas that I&#8217;ve been rolling around in my head lately is the possibility of a roguelike completely lacking in any sort of <strong>graphical user interface</strong> (GUI). Basically, this means the game would have no menus or displays of any sort&#8211;not even a health display or or turn counter&#8211;on the main screen of the game. Instead, the user interface would all be in text, displayed in a separate message console/log thingy (don&#8217;t you just love my technical terminology?). Events in the game, player stats, monster stats, and all that would be displayed through such a console.</p>
<p>So the question is: is it possible to have a roguelike with a completely message-based interface? The answer is <b>absolutely. </b>In this post I&#8217;ll be talking about a few of the things that you&#8217;d have to deal with in the writing of such a game. (Note: not necessarily Javascript specific, just some rambling/brainstorming about RL development in general)</p>
<p><em id="__mceDel"><span id="more-746"></span></em></p>
<h2>Displaying information in a textual format</h2>
<p>There are a couple of key things the developer of a GUI-less RL needs to be aware of.</p>
<p>One of the most important things to get right is alerting the player about life-threatening events such as HPs dropping dangerously low, risk of starvation, etc. In a text game without any sort of health display it&#8217;d be awfully easy to miss the &#8220;HP low!&#8221; warnings and accidentally play your character to death.</p>
<p>Naturally, you&#8217;d want to spend a good portion of development time on creating some good grammar formatting/text generation algorithms. You don&#8217;t want &#8220;an foo&#8221; to attack you, nor would &#8220;a gloves&#8221; be a very interesting find. This is, of course, a concern for all games with messaging systems, but since the primary focus of a GUI-less game would be the text, the player would be paying a lot more attention to it, and thus would be more likely to catch any errors.</p>
<p>Furthermore, numbers don&#8217;t look very good in a textual context. A GUI-less game shouldn have very few, if any, numerical characters mixed in with the text. Instead of saying &#8220;You have 5 apples, 2 shirts, [...] in your inventory&#8221;, you&#8217;d want to display &#8220;You have <strong>five </strong>apples, <strong>two</strong> shirts, [...] in your inventory&#8221;. I suppose this might fall under creating solid algorithms for generating messages, but I feel that it&#8217;s important enough to deserve its own paragraph.</p>
<h2>Receiving user input in a textual format</h2>
<p>Another issue with a GUI-less roguelike would be how to get user input. Naturally, in the map screen, movement keys would be the same as in a &#8220;vanilla&#8221; roguelike, and I suspect many other &#8220;standard&#8221; commands such as <span class="kdb-shortcode"><kdb class="kdb-shortcode char">g</kdb></span>  for grab, <span class="kdb-shortcode"><kdb class="kdb-shortcode char">w</kdb></span>  for wear, <span class="kdb-shortcode"><kdb class="kdb-shortcode char">e</kdb></span>  for equip, and the like, would remain the same as well. However, in addition to these normal keys, which I&#8217;ll call <strong>hotkeys </strong>for the sake of clarity, there would be a second method for interfacing with the game: <strong>commands. </strong>Commands would be longer and more complex instructions, often consisting of whole words, something somewhat similar to what Nethack offers with its array of one-word commands. It would be possible to enter a whole sequence of commands and have them executed sequentially.</p>
<p>However, constantly having to type in long commands could easily get annoying, so you&#8217;d want to provide a way to save custom <strong>macros</strong> and perhaps custom hotkeys as well. These hotkeys would execute specific macros in the console, which would of course have access not only to all longer commands, but also the commands the hotkeys call as well, such as &#8220;walk north&#8221;, &#8220;walk southeast&#8221;, and the like.</p>
<p>Another feature that would be useful would be the ability to quickly scroll through previously entered commands with, say, the up arrow key. This functionality is already offered in most consoles, and for good reason. It makes doing repetitive actions which don&#8217;t necessarily require a macro much easier to execute.</p>
<h2>Closing thoughts</h2>
<p>I guess you could call the type of game I&#8217;ve been describing a <strong>roguelike in which all the game-related information is presented to the player solely through a console</strong>. I think it&#8217;d be an interesting challenge and certainly something worth attempting. I might try to write such a game in the near future, since it&#8217;s (obviously) something that I find quite intriguing. If that does happen, I&#8217;ll be posting more about what goes into a GUI-less Roguelike. In the mean time, feel free to comment if you have any corrections or just want to add on to what I&#8217;ve said. Oh, and don&#8217;t forget to subscribe to my RSS feed!</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/a-roguelike-with-a-message-based-user-interface/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementation of A* Pathfinding in Javascript</title>
		<link>http://heyjavascript.com/implementation-of-a-pathfinding-in-javascript/</link>
		<comments>http://heyjavascript.com/implementation-of-a-pathfinding-in-javascript/#comments</comments>
		<pubDate>Fri, 25 Jan 2013 00:07:22 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=644</guid>
		<description><![CDATA[I&#8217;ve been meaning to release my self-contained implementation of A* pathfinding for a while now, but it took me forever to get around to cleaning up the codebase and stuff. Anyways, once I did tidy it up, I decided to release it. Hopefully somebody out there will find it useful. Here&#8217;s a demo of it [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been meaning to release my self-contained implementation of A* pathfinding for a while now, but it took me forever to get around to cleaning up the codebase and stuff. Anyways, once I did tidy it up, I decided to release it. Hopefully somebody out there will find it useful.</p>
<p><span id="more-644"></span></p>
<p>Here&#8217;s a demo of it in action:</p>
<p><iframe src="http://heyjavascript.com/astar_pathfinding/index.html" height="500" width="500" frameborder="0" marginwidth="0" marginheight="0"></iframe><br />
Click anywhere to start a path, then click again to complete it. As you can see, my implementation is pretty quick. Although I haven&#8217;t measured its performance, strictly speaking, it can calculate a 850 or so unit long path with a barely visible delay (and I suspect even that delay is largely due to <span class="code-tag">&lt;canvas&gt;</span>&#8216;s rendering performance&#8211;it really drops after you hit about nine million pixels, or 360,000 tiles). The algorithm uses a custom ordered array so it is pretty speedy.</p>
<h2>Why use AStar.js?</h2>
<p>If you&#8217;re interested in A* pathfinding, there are a few other pathfinding packages for Javascript. However, most of them require several Javascript libraries and/or complex inter-dependencies. To use my module, you only need to include <strong>one</strong> file&#8211;<span class="code-tag">astar.js</span>, and there are no external dependancies.</p>
<h2>Getting started with AStar.js</h2>
<p>Once you&#8217;ve included <span class="code-tag">astar.js</span>, you need to create an instance of the AStar pathfinding tool before you can start calculating your path. To create an instance of AStar, you need to provide your map data, the map&#8217;s height, the map&#8217;s width, and a function to tell whether or not a particular node is blocked.</p>
<p>Say your map data looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
var map = [
    [0, 1, 0, 0, 0, 1, 0],
    [0, 1, 0, 1, 0, 1, 0],
    [0, 1, 0, 1, 0, 1, 0],
    [0, 1, 0, 1, 0, 1, 0],
    [0, 1, 0, 1, 0, 1, 0],
    [0, 1, 0, 1, 0, 1, 0],
    [0, 0, 0, 1, 0, 0, 0],
];
</pre>
<p>You&#8217;d initialize your AStar object like this:</p>
<pre class="brush: jscript; title: ; notranslate">
astar = new AStar(map, 7, 7, function(data, x, y) {
    return {
        blocks: data[x][y]
    }
});
</pre>
<p>The anonymous function you pass in takes three parameters; an inside reference to the data you passed in previously, the node&#8217;s x coordinate, and the node&#8217;s y coordinate. All it needs to return is an object with a boolean property, <span class="code-tag">blocks</span>, indicating whether or not the node in question is walkable. I may end up extending it to take values that let you determine the terrain cost of each node, but for now either a node is blocks movement or it doesn&#8217;t. In the case of the example, a &#8220;0&#8243; indicates unwalkable terrain and a &#8220;1&#8243; indicates walkable terrain. That&#8217;s why, in this example,  just returning the value at the specified node works.</p>
<p>Once you&#8217;ve initialized the <span class="code-tag">AStar</span> module, all it takes is a single line of code to get a path:</p>
<pre class="brush: jscript; title: ; notranslate">var path = astar.path(start_x, start_y, end_x, end_y);</pre>
<p><span class="code-tag" data-mce-mark="1">AStar.path()</span> returns an array containing the nodes found for the path specified, containing the starting and ending points. Each node is represented as an object with x and y values.</p>
<h2>Demos and downloading AStar.js</h2>
<p>You can find the link to the demo in the article <a href="http://heyjavascript.com/astar_pathfinding/index.html" target="_blank">here</a>. I also put up a<a href="http://heyjavascript.com/astar_stress_test/index.html" target="_blank"> pathfinding stress test</a> for fun; turns out that calculating an ~850 node long path takes about 200 ms (be warned, the linked page may take a while to load).</p>
<p>You can download AStar.js in an uncompressed format <a href="http://heyjavascript.com/astar_pathfinding/astar.js" target="_blank">here</a> (there&#8217;s also a <a href="http://heyjavascript.com/astar_pathfinding/astar_minified.js" target="_blank">minified version</a> available). I hope somebody finds this helpful, and as always, be sure to let me know if I made any typos or errors in this article! (don&#8217;t forget to subscribe to my RSS feed, too)</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/implementation-of-a-pathfinding-in-javascript/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A book on programming Roguelikes with Javascript?</title>
		<link>http://heyjavascript.com/a-book-on-programming-roguelikes-with-javascript/</link>
		<comments>http://heyjavascript.com/a-book-on-programming-roguelikes-with-javascript/#comments</comments>
		<pubDate>Wed, 19 Dec 2012 20:21:25 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=609</guid>
		<description><![CDATA[So, for a while now, I&#8217;ve been planning out a book on writing Roguelikes with Javascript. Unfortunately, there aren&#8217;t a lot of resources for RLs in Javascript at the moment, so the book will have to be pretty broad, as it won&#8217;t be able to build on previously established information. I will attempt to cover [...]]]></description>
				<content:encoded><![CDATA[<p>So, for a while now, I&#8217;ve been planning out a book on writing Roguelikes with Javascript. Unfortunately, there aren&#8217;t a lot of resources for RLs in Javascript at the moment, so the book will have to be pretty broad, as it won&#8217;t be able to build on previously established information. I will attempt to cover most of the aspects of writing a Roguelike in Javascript; the book will contain the algorithms that are most essential to writing a Roguelike.</p>
<p><span id="more-609"></span></p>
<h2>What the book will be:</h2>
<ul>
<li>A cut-and-paste resource for writing JS roguelikes, with a large number of useful algorithms covered in-depth.</li>
<li>An introduction to the pros and cons of writing roguelikes in Javascript</li>
<li>A starting point for your own browser-based roguelike</li>
</ul>
<div></div>
<h2>What it won&#8217;t be:</h2>
<div>
<ul>
<li>An introduction to Javascript</li>
<li>A tutorial on how to write your own Roguelike</li>
<li>A statement on best practices for Javascript</li>
</ul>
</div>
<h2>What will the book cover?</h2>
<p>Here&#8217;s a list of some of the major topics I&#8217;m hoping to cover in no particular order (some may be cut out due to length limitations eventually):</p>
<ol>
<li>Why Javascript? &#8212; <em>where&#8217;s the logic in using Javascript for a Roguelike?</em></li>
<li>File and data management &#8212; <em>how to manage source files and data</em></li>
<li>Display &#8212; <em>several different paradigms you can use to display your game</em></li>
<li>Main loop &#8212; <em>the main loop of the game; this handles lighting, monster AIs, stuff like that</em></li>
<li>Input handling &#8212; <em>how to handle the input from the player</em></li>
<li>Map generation &#8211;<em> how to actually generate maps</em></li>
<li>Map management &#8211;<em> keeping track of what goes where on the map</em></li>
<li>Lighting &#8211;<em> lighting the map</em></li>
<li>Items &#8212; <em>how to handle items using object oriented programming techniques such as composition and inheritance</em></li>
<li>Actors &#8212; <em>keeping track of all the actors in the game</em></li>
<li>Pathfinding &#8212; <em>several different pathfinding algorithms such as A* and Dijkstra </em></li>
<li>Actor AI &#8212; <em>handling NPC behavior</em></li>
</ol>
<h2>That&#8217;s all, folks!</h2>
<div></div>
<div>&#8230;except not really. This is just beginning, in fact; you can look forward to seeing more posts on this topic in the upcoming weeks and months. Thanks for the read, and as always, if you have questions or suggestions about the book, please be sure to let me know via comment or email!</div>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/a-book-on-programming-roguelikes-with-javascript/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Field of view in Javascript using recursive shadow casting</title>
		<link>http://heyjavascript.com/field-of-view-in-javascript-using-recursive-shadow-casting/</link>
		<comments>http://heyjavascript.com/field-of-view-in-javascript-using-recursive-shadow-casting/#comments</comments>
		<pubDate>Tue, 04 Dec 2012 04:33:41 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=589</guid>
		<description><![CDATA[Field of view, and stuff Field of view, which involves determining which tiles are visible to the player, is a particularly fun aspect of writing roguelikes, in my opinion. When writing a field of view algorithm, you often find yourself trading quality for performance, or vice versa. Some algorithms get around this with a bit [...]]]></description>
				<content:encoded><![CDATA[<h2>Field of view, and stuff</h2>
<p>Field of view, which involves determining which tiles are visible to the player, is a particularly fun aspect of writing roguelikes, in my opinion. When writing a field of view algorithm, you often find yourself trading quality for performance, or vice versa. Some algorithms get around this with a bit of trickery, like the Rogue algorithm. Other algorithms have no visible artifacts and in fact are quite pleasing visually, but pay for this with a definite decrease in performance.</p>
<p>There have been, of course, plenty of articles written about field of vision, and there is in fact an excellent compendium of resources over at Roguebasin (you can check that out <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision">here</a>). This is a problem that has been thoroughly solved many times, beginning with Rogue&#8217;s rudimentary solution (you can see all the tiles in the room you&#8217;re in, but nothing else is visible; when in corridors, only the corridor tiles next to you are visible). The thing is, only a few Javascript algorithms (if any) are available to calculate FOV. Since I&#8217;m writing a Roguelike and have of course come up with an algorithm of my own, I have decided to remedy this lack of JS algorithms by sharing mine with you. It&#8217;s nothing fancy, but does provide a rather nice gradient falloff, which works in tandem with the <span class="code-tag">display.js</span> library that I <a href="http://heyjavascript.com/console-like-display-in-the-browser/">previously posted</a>.</p>
<p><span id="more-589"></span></p>
<h2>Finding the happy medium</h2>
<p>Many FOV algorithms have been written in an attempt to find the happy medium between performance and quality. After trying a few algorithms out, I eventually settled with recursive shadowcasting, which was both optimized for maximum performance but also very few artifacts. All in all, I&#8217;m happy with my choice. Here are some of the results you can get with recursive shadowcasting combined with a gradient falloff:</p>
<p><img class="alignnone" title="Saege FoV " src="http://img585.imageshack.us/img585/760/19f0bf3687534f87945631e.png" alt="Demonstration of Saege's FOV" width="286" height="307" /></p>
<p><img class="alignnone" src="http://i.imgur.com/ftD6h.png" alt="More Saege FoV" width="218" height="225" /></p>
<p><img class="alignnone" title="More Saege FoV" src="http://i.imgur.com/nuHSo.png" alt="" width="295" height="285" /></p>
<p>The field of view you see here is using a radius that is roughly double that of which is found in my game in order to better display the nice lighting falloff. However, even with aforementioned smoothed lighting, performance isn&#8217;t impacted in the slightest.</p>
<h2>Has the happy medium been found?</h2>
<p>As I&#8217;ve mentioned before, performance is usually achieved at the cost of quality. However, I was able to find a way to boost the performance of the algorithm without impacting quality. Now, to update the lighting, most algorithms clear the map of light and reset all the tiles to &#8220;unlit&#8221; or, depending on whether the player has already seen the tiles, &#8220;unseen&#8221;, which basically means the player has seen that tile at some point but can&#8217;t currently see it. The lighting algorithm then calculates the tiles within the player&#8217;s field of view and sets those tiles to &#8220;visible&#8221;, and the rendering engine displays them as lit up. Pretty straightforward.</p>
<p>The difference in my algorithm is that instead of clearing the entire map, it only sets to &#8220;unseen&#8221; those tiles which were lit the previous turn. This means that loads of CPU cycles aren&#8217;t wasted trying to reset the entire map&#8217;s lighting, most of which is outside the player&#8217;s field of view anyways. The algorithm simply appends each tile that is set to &#8220;visible&#8221; to an array, which is stored. When the lighting is next updated, those tiles in the array, and only those tiles, are set to &#8220;unseen&#8221; and the algorithm proceeds to calculate lighting as normal; wash, rinse, repeat, and you&#8217;ve got yourself one quick little field of view algorithm.</p>
<h2>If you&#8217;ve stuck with me this long&#8230;</h2>
<p>&#8230;you must be interested in seeing the algorithm. So, without further ado, <a href="https://gist.github.com/4200578">here it is</a>. It&#8217;s been sparsely commented, but hopefully should be of some help to some of you. And, as before, the <span class="code-tag">LightSource</span> class which contains the algorithm does make use of some external functions, which I will be introducing to you later on as progress on my game continues. And, before I forget, here&#8217;s a <a href="https://gist.github.com/4200590">demo</a> demonstrating its use.</p>
<p>Hopefully this article has given you something to think about, and, as always, feel free to comment and let me know if I&#8217;ve made any mistakes or typos!</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/field-of-view-in-javascript-using-recursive-shadow-casting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating caverns with cellular automata</title>
		<link>http://heyjavascript.com/generating-caverns-with-cellular-automata/</link>
		<comments>http://heyjavascript.com/generating-caverns-with-cellular-automata/#comments</comments>
		<pubDate>Wed, 24 Oct 2012 22:27:02 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=554</guid>
		<description><![CDATA[In this article, I&#8217;ll be discussing how to generate neat-looking fully connected caves using cellular automata. This algorithm builds off of another algorithm which can be found here. As noted, the linked algorithm is incomplete and cannot be used for generating dungeons that are suitable for a real roguelike. This article is about the method I [...]]]></description>
				<content:encoded><![CDATA[<p>In this article, I&#8217;ll be discussing how to generate neat-looking fully connected caves using cellular automata. This algorithm builds off of another algorithm which can be found <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Cellular_Automata_Method_for_Generating_Random_Cave-Like_Levels">here</a>. As noted, the linked algorithm is incomplete and cannot be used for generating dungeons that are suitable for a real roguelike. This article is about the method I used to make that algorithm workable.</p>
<p><span id="more-554"></span></p>
<h2>First off, the basic algorithm:</h2>
<p>To begin, let&#8217;s take a look at basic algorithm behind generating nice-looking cave levels with cellular automata:</p>
<pre class="brush: jscript; title: ; notranslate">
1. Scatter wall blocks across the level at a 30-40% saturation level (I've found that 39% is ideal).

2. Iterate through all the tiles on the map four times:
- For each tile in each iteration, set the tile to be floor.
- Then, calculate the number of wall tiles within both one square 
    of the original tile (these are neighbors) and two squares (these tiles are nearby). Store these numbers.
- If the number of neighbors for the tile is greater than or equal to 5, or there are less
    than two wall tiles nearby, set this tile to be a wall.&lt;/div&gt;
- If it is not a wall already, leave this tile as a floor tile.

3. Iterate through all the tiles on the map three more times:
- For each tile in each iteration, set the tile to be floor.
- Calculate the number of wall tiles within both one square of the original tile.
- If this tile has five or more neighboring walls, make it a wall. Otherwise, leave it as a floor tile.
</pre>
<h2>The issue with cellular automata is&#8230;</h2>
<p>&#8230;the caves generated with the cellular automata technique are often unconnected. Since many roguelikes depend on all parts of a level being accessible, this is usually a bad thing. So, clearly, we need a way to drop the disconnected regions or otherwise ignore them. The best way to do this is with a <a href="http://en.wikipedia.org/wiki/Flood_fill">flood fill algorithm</a>. A flood fill algorithm is able to find all the nodes connected to each other that aren&#8217;t delimited by another type of node. In graphics applications, this is usually used to find regions of similar color.</p>
<p>In our algorithm, the flood fill algorithm will be used to find all the regions of the cave that are comprised of purely floor tiles&#8211;in other words, all the caverns (unconnected or not) on the map. Once we have a list of the caverns, we can select the largest cavern&#8211;this will be the main cavern. We can then simply drop the other patches, as they are small unconnected regions that are precisely what we don&#8217;t want.</p>
<h2>Flood fill algorithm in Javascript:</h2>
<p>Here&#8217;s how I managed the flood fill algorithm and subsequent cavern managing in Javascript:</p>
<pre class="brush: jscript; title: ; notranslate">
// this variable will be used to store the various unconnected caverns
var caverns = [];
 
// begin looping through the map
for(var x = 1; x&lt;this.size.x; x++) {
    for(var y = 1; y&lt;this.size.y; y++) {
        var cavern = [];
        var totalCavern = [];
        
        if(this.data[x][y].type != &quot;dirty floor&quot;) {
            // we've already been over this tile or it is already part of a cavern, 
            // no need to check it
            continue;
        }
        
        cavern.push(this.data[x][y]);
        totalCavern.push(this.data[x][y]);
        
        while(cavern.length &gt; 0) {
            var n = cavern.pop();
            
            if(n.type == &quot;dirty floor&quot;) {
                // set a flag on the tile indicating it has already been checked
                n.setType(&quot;floor&quot;);
                
                for(var i = 0; i&lt;8; i++) {
                    var curTile = this.data[n.position.x + x_array[i]][n.position.y + y_array[i]];
                    if(curTile.type == &quot;dirty floor&quot;) {
                        cavern.push(curTile);
                        totalCavern.push(curTile);
                    }
                }
            }
        }
        
        // add this cavern
        caverns.push(totalCavern);
        
        // sort the caverns
        caverns.sort(function(a, b) {
            return(b.length - a.length);
        });
    }
}
 
// remove the largest cavern, as it is the main cavern
caverns.shift();
 
// now that we've got the unconnected caverns, change their tile type
if(caverns.length &gt; 0) {
    for(var i = 0; i&lt;caverns.length; i++) {
        for(var j = 0; j&lt;caverns[i].length; j++) {
            caverns[i][j].setType(&quot;wall&quot;);
        }
    }
}
</pre>
<p>As you can see, I loop through all the tiles. First, I check to see if I&#8217;ve already been over the tile; if so, I pass it on. If I haven&#8217;t, I go through that tile and search its neighbors, too. Eventually, I&#8217;ve searched all the tiles on the map and sorted them into the various caverns to which they belong. Once I&#8217;ve done that, I sort the caverns by size, from largest to smallest, and pick out the one with the most tiles in it (in other words, the biggest cavern). This is the main cavern, so we can get rid of or ignore the rest. I personally chose to get rid of my unconnected caverns, but it&#8217;s possible to connect them or just ignore them for the rest of the dungeon generation code&#8211;it&#8217;s up to you really.</p>
<h2>In finis&#8230;</h2>
<p>If you&#8217;ve read this far, you&#8217;re at least slightly intrigued by the cellular automata/flood fill cave generation algorithm&#8211;good! Hopefully you&#8217;ll have as much fun playing around with it as I did. As you can see, the Javascript code I included above makes heavy use of some external data-managing structures, such as a map data structure and a tile structure as well; I&#8217;ll be writing more articles about how I handle the map and tile stuff later. As always, thanks for the read, and if I made any mistakes during this article or if any of my code can be improved, please let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/generating-caverns-with-cellular-automata/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Console-like display in the browser?</title>
		<link>http://heyjavascript.com/console-like-display-in-the-browser/</link>
		<comments>http://heyjavascript.com/console-like-display-in-the-browser/#comments</comments>
		<pubDate>Mon, 22 Oct 2012 02:30:24 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=517</guid>
		<description><![CDATA[I&#8217;ve been working for some time on a Roguelike in Javascript. One of the first things I had to do for my Roguelike, of course, was establish some sort of display routine. I could have gone with HTML5&#8242;s new &#60;canvas&#62; tag or something similar, but setting up a console-like environment for canvas can get a [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been working for some time on a Roguelike in Javascript. One of the first things I had to do for my Roguelike, of course, was establish some sort of display routine. I could have gone with HTML5&#8242;s new <span class="code-tag">&lt;canvas&gt;</span> tag or something similar, but setting up a console-like environment for canvas can get a little involved. So instead, I established a way to use the browser&#8217;s native text rendering. Say hello to a simple Javascript class for console-like rendering in the browser: I call it <span class="code-tag">display.js</span>.</p>
<p><span id="more-517"></span></p>
<p>So, let&#8217;s take a look at the code required initialize a basic 80 by 25 console and draw a few characters with the <span class="code-tag">display</span> class:</p>
<script src="https://gist.github.com/3929246.js"></script><noscript><pre><code class="language-javascript javascript">// create a display for console-like rendering
display = new Display(new Vector2(80, 25), new Vector2(10, 35), true);

// let's draw the classic @ sign:
display.ch(&quot;@&quot;, new Vector2(10, 10));

// maybe fake a few walls
for(var x = 0; x&lt;10; x++) {
    display.ch(&quot;#&quot;, new Vector2(x, 0));
}

// let's put a green slime down, too
display.ch(&quot;j&quot;, new Vector2(15, 15), &quot;green&quot;);</code></pre></noscript>
<p>Okay, let&#8217;s step through this code really quickly. Before we begin, though, I&#8217;d like to note the <span class="code-tag">Vector2</span> class I use here; it&#8217;s nothing more than a utility function I use to hold a position with X and Y values (you can grab a copy of it <a href="https://gist.github.com/3929297">here</a>). So, in the code, the first line initializes the console display. The first variable we pass in to this function call is the size of the display&#8211;I use 80 by 25 because that&#8217;s a standard console size, but these numbers could be anything you want. The second variable we pass in is the offset of the console from the rest of the page. The third variable we pass in is whether we want this display to open in a new window or not. If you set it to false, the display will simply be written to your HTML page. If it&#8217;s set to true, the console will open in a popup window.</p>
<p>The next line calls a function on our newly created console, namely <span class="code-tag">ch</span>. This allows you to display a character on the screen and takes a minimum of two and up to five parameters. In order, these are: the character to display, the position of that character, the color of the character, the opacity of the character, and the background color of the character. Only the character you want to write and the position of that character are required; the others are optional. The color variable accepts a few basic color names as well as hex values. The next few lines do nothing more than demonstrate the various applications of the <span class="code-tag">ch</span> function, which is the only function <span class="code-tag">display.js</span> makes use of.</p>
<h2>In finis&#8230;</h2>
<p>As you can see, the display class isn&#8217;t very advanced right now, but it&#8217;s been all I&#8217;ve needed so far. If you want to download the class, you can grab it <a href="https://gist.github.com/3929288">here</a>. Quick note, it does make use of jQuery, so make sure you include that in your project before you attempt to use it. As progress on my game continues, this library will likely be updated with more functions as I need them. Thanks for taking a look, and be sure to keep an eye on Hey Javascript for more updates in the near future! (hopefully, I&#8217;ll be posting some dungeon generation algorithms in Javascript soon)</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/console-like-display-in-the-browser/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Roguelike game programming and development in Javascript?</title>
		<link>http://heyjavascript.com/roguelike-game-programming-and-development-in-javascript/</link>
		<comments>http://heyjavascript.com/roguelike-game-programming-and-development-in-javascript/#comments</comments>
		<pubDate>Tue, 21 Aug 2012 23:04:25 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=492</guid>
		<description><![CDATA[The Roguelike genre has been in development for decades&#8211;since 1980, in fact, when Rogue, the first Roguelike game, was written. Since then, Roguelike games have been created in many different programming languages. Among the more popular of these languages are C, C++, Java, and Python. However, a new contender is appearing: Javascript. Although it&#8217;s the [...]]]></description>
				<content:encoded><![CDATA[<p>The <strong>Roguelike</strong> genre has been in development for decades&#8211;since 1980, in fact, when <a href="http://roguebasin.roguelikedevelopment.org/index.php/Rogue">Rogue</a>, the first Roguelike game, was written. Since then, Roguelike games have been created in many different programming languages. Among the more popular of these languages are C, C++, Java, and Python. However, a new contender is appearing: <strong>Javascript</strong>. Although it&#8217;s the new kid on the block, Javascript is quickly becoming a popular choice for Roguelike development and has already been used to make quite a few games.</p>
<p><span id="more-492"></span></p>
<p>Unfortunately, since it&#8217;s so new, there aren&#8217;t a lot of resources for those who want to begin working with Javascript. Many useful algorithms and formulas found in older development languages have yet to be ported to Javascript and most of the popular utility libraries aren&#8217;t available. Nonetheless, Javascript remains a powerful tool for Roguelike development, for those who are still interested.</p>
<p>Now, in order to combat this lack of resources, I&#8217;m going to be exploring the capabilities of Javascript for RL development. You can expect to see popular algorithms ranging from dungeon generation algorithms to A* pathfinding converted to Javascript and ready for you to use in your game. I&#8217;ll be explaining the shift in thinking required when switching from console-based programming languages to Javascript, which renders to the browser, and may even share with you the source code for the RL I&#8217;m currently working on.</p>
<p>Before we get to that, though, here are a few resources that I&#8217;m currently working with in my adventures into Javascript Roguelikes:</p>
<h2>1. The one wiki to rule them all: RogueBasin</h2>
<p><a href="http://roguebasin.roguelikedevelopment.org/index.php/Main_Page" target="_blank">RogueBasin</a> is an unparalleled resource for the aspiring Roguelike programmer. It&#8217;s a wiki&#8211;<em>the</em> wiki, I might go so far as to say&#8211;for Roguelike gaming, whether you&#8217;re interested in development or playing. It contains a number of excellent articles on developing Roguelikes and even has a page on the pros and cons of <a href="http://roguebasin.roguelikedevelopment.org/index.php/Javascript" target="_blank">developing Roguelikes in Javascript</a>. What makes it such an invaluable resource, however, is the number of algorithms (and more importantly, <em>explanations</em> of algorithms) that it has. It would be worth your time to read and re-read all the articles on there. While not Javascript-specific, they explain many of the key concepts that go into a good Roguelike.</p>
<h2>2. &#8220;Amit&#8217;s Game Programming Information&#8221;</h2>
<p>While not strictly related to Roguelikes, <a href="http://www-cs-students.stanford.edu/~amitp/gameprog.html" target="_blank">Amit&#8217;s Game Programming Information</a> has a number of links to various resources which can prove useful to Roguelike development. Among others, it has articles on pathfinding, line of site algorithms, AI programming, and other equally important facets of Roguelike development.</p>
<h2>3. A few resources for A* pathfinding</h2>
<p>I&#8217;m working on writing a decent implementation of A* pathfinding in Javascript to be used in my game. Here are a few of the resources I&#8217;m using to help me clean up my implementation:</p>
<p>- <a href="http://www.policyalmanac.org/games/aStarTutorial.htm">A* Pathfinding for Beginners</a>: Very explanatory and clear. If I were rating these (which I&#8217;m not) I&#8217;d give it a 5/5.</p>
<p>- <a href="http://wiki.gamegardens.com/Path_Finding_Tutorial">Path Finding Tutorial</a>: A decent tutorial, explains some uses for A* other than monster AIs.</p>
<p>- <a href="http://wiki.gamegardens.com/Path_Finding_Tutorial">Introduction to A* Pathfinding</a>: Another good tutorial. I like this article because it has cats in it.</p>
<p>I realize that I may have posted a few of these links already in my previous article on A* pathfinding, but if you didn&#8217;t catch that, no harm done. These should be enough to get you started with A* pathfinding, if you haven&#8217;t figured it out already. There aren&#8217;t really many changes we need to make to convert the algorithm to Javascript, as it&#8217;s fairly straightforward.</p>
<h2>4. Several different algorithms for field of view computations</h2>
<p>I&#8217;ve converted several different algorithms for field of view computations into Javascript, but I&#8217;m still cleaning them up, so I won&#8217;t publish them just yet. Until then, have a look at some of the resources I found useful in my ventures into field of view:</p>
<p>- <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Eligloscode">Field of view calculations via raycasting</a>: This was the first psuedocode I ported to Javascript, but as it turns out it was too slow for my uses, so I looked around for some other implementations.</p>
<p>- <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=FOV_using_recursive_shadowcasting">FOV using recursive shadowcasting</a>: This article led me into writing a recursive shadowcasting algorithm in Javascript. It&#8217;s easily the fastest FOV algorithm I&#8217;ve found yet.</p>
<p>- <a href="http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/walls-and-shadows-in-2d-r2711">Walls and Shadows in 2D</a>: This article contains the explanation of an algorithm for lighting I&#8217;ve not yet implemented, although it does seem pretty promising.</p>
<h2>5. Finally, a quick look at some dungeon generation algorithms</h2>
<p>Dungeon generation is a key factor in most modern Roguelikes, so you want to be sure you&#8217;re doing it right. This is one of my favorite parts of Roguelike development, and something I&#8217;ll be touching on again in the future. There are a few different methods you can use: let&#8217;s take a quick look at some of the more interesting ones I&#8217;ve come across:</p>
<p>- <a href="http://roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm">Dungeon-Building Algorithm</a>: This is an interesting algorithm and produces some nice results. I&#8217;ve played around with it on more than one occasion (in Javascript, of course).</p>
<p>- <a href="http://pcg.wikidot.com/pcg-algorithm:dungeon-generation">Dungeon generation on the PCG wiki</a>: The PCG (Procedural Content Generation) wiki has a number of resources for dungeon generation, and I&#8217;ve found it valuable in researching different methods of creating dungeons on more than one occasion.</p>
<p>- <a href="http://kuoi.com/~kamikaze/GameDesign/art07_rogue_dungeon.php">Rogue&#8217;s original dungeon generation algorithm</a>: The dungeon creation algorithm used in the original Rogue game. It&#8217;s actually pretty nifty.</p>
<h2>6. In finis&#8230;</h2>
<p>You&#8217;ll probably have noticed by now that most of the resources I&#8217;ve linked to have nothing to do with Javascript. That&#8217;s because, as I said earlier, there aren&#8217;t many resources for Javascript Roguelike development yet. I&#8217;ll be converting many of the algorithms I posted into Javascript in the upcoming months for your ease-of-use.</p>
<p>Eventually, if enough interest is shown, I may write a book on Roguelike development with Javascript. Let me know if you think such a book would be useful in the comments section, and as always, feel free to point out any mistakes I&#8217;ve made in this article!</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/roguelike-game-programming-and-development-in-javascript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>8 great A* pathfinding resources</title>
		<link>http://heyjavascript.com/8-great-a-pathfinding-resources/</link>
		<comments>http://heyjavascript.com/8-great-a-pathfinding-resources/#comments</comments>
		<pubDate>Fri, 25 May 2012 20:55:40 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=465</guid>
		<description><![CDATA[If you&#8217;re writing a game that incorporates both a terrain of some sort and enemies that walk around, the chances are you&#8217;ll need some version of pathfinding to control the enemy movement patterns. The thing is, pathfinding is serious business&#8211;it&#8217;s not easy to grasp. To make things worse, there aren&#8217;t many good pathfinding resources&#8211;most of the articles that [...]]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re writing a game that incorporates both a terrain of some sort and enemies that walk around, the chances are you&#8217;ll need some version of pathfinding to control the enemy movement patterns. The thing is, pathfinding is serious business&#8211;it&#8217;s not easy to grasp. To make things worse, there aren&#8217;t many <em>good</em> pathfinding resources&#8211;most of the articles that turn up on Google and such only serve to confuse you further. That&#8217;s why I&#8217;ve taken the time to compile this list of pathfinding resources that I&#8217;ve found to be actually helpful, as opposed to confusing or just plain wrong. Enjoy!</p>
<p><span id="more-465"></span></p>
<h2><strong>1)</strong> <a href="http://theory.stanford.edu/~amitp/GameProgramming/">Amit&#8217;s A* Pages</a></h2>
<p>This site is an excellent compilation of articles on A*. It&#8217;s a great resource, but the articles it contains aren&#8217;t exactly for beginners. That said, I refer to them all the time&#8211;they&#8217;re not limited to just pathfinding articles. There&#8217;s stuff in there about pretty much <em>every</em> aspect of game programming.</p>
<h2><strong>2)</strong> <a href="http://www.policyalmanac.org/games/aStarTutorial.htm">A* Pathfinding for Beginners</a></h2>
<p>This is really an excellent tutorial. It explains the concepts behind pathfinding very clearly and is pretty easy to grasp. If you&#8217;re just getting into A* pathfinding, this is definitely the article for you.</p>
<h2><strong>3)</strong> <a href="http://en.wikipedia.org/wiki/A*_search_algorithm">Wikipedia on A*</a></h2>
<p>Wikipedia&#8217;s article is also quite useful, and this page has a handy language-agnostic implementation of pathfinding.</p>
<h2><strong>4)</strong> <a href="http://www.raywenderlich.com/4946/introduction-to-a-pathfinding">Ray Wenderlich&#8217;s &#8220;Introduction to A* Pathfinding&#8221;</a></h2>
<p>Another great article. This guy uses a cat to illustrate his point, so kudos to him for that (I&#8217;m a big fan of cats).</p>
<h2><strong>5)</strong> <a href="http://wiki.gamegardens.com/Path_Finding_Tutorial">Another article and accompanying psuedocode</a></h2>
<p>I like the pseudocode in this article and there&#8217;s a useful discussion about actually implementing A* towards the end of the article&#8211;what you&#8217;ll need as far as abstract classes and interfaces go.</p>
<h2><strong>6)</strong> <a href="http://code.google.com/p/a-star-algorithm-implementation/">Justin Heyes&#8217; C++ implementation</a></h2>
<p>Justin Heyes has written an excellent implementation of A* which can be found in the above repository. Although it&#8217;s in C++ it clearly illustrates the finer points of the algorithm and how to interface with it.</p>
<h2><strong>7)</strong> <a href="http://www.briangrinstead.com/blog/astar-search-algorithm-in-javascript-updated">Brian Grinstead&#8217;s Javascript implementation</a></h2>
<p>Brian Grinstead has written a fast version of A* in Javascript. It&#8217;s quite effecient but can be tricky to understand. If you&#8217;re already &#8220;pro&#8221; and have a working implementation of A*, but want/need it to be faster, this is your article.</p>
<h2><strong>8<em></em>)</strong> <a href="http://www.edenwaith.com/products/pige/tutorials/a-star.php">Some more A* pseudocode</a></h2>
<p>Here&#8217;s yet another version of the pathfinding algorithm in pseudocode, in case you didn&#8217;t &#8220;get it&#8221; from any of the previous 7 articles. The explanation is short and sweet and the pseudocode fairly readable. There&#8217;s also a link to a version of A* written in LISP at the bottom of the page, if that&#8217;s your thing.</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/8-great-a-pathfinding-resources/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>4 creative ways to clone objects</title>
		<link>http://heyjavascript.com/4-creative-ways-to-clone-objects/</link>
		<comments>http://heyjavascript.com/4-creative-ways-to-clone-objects/#comments</comments>
		<pubDate>Tue, 22 May 2012 00:44:38 +0000</pubDate>
		<dc:creator>Elliot Bonneville</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://heyjavascript.com/?p=452</guid>
		<description><![CDATA[There are a lot of ways to clone objects in Javascript, and some of them get pretty creative. jQuery has an excellent method for cloning objects, as does Mootools. There&#8217;s a Javascript hack we can sort of &#8220;exploit&#8221;, or we could just clone our object in plain Javascript. Let&#8217;s start with the vanilla Javascript first [...]]]></description>
				<content:encoded><![CDATA[<p>There are a lot of ways to clone objects in Javascript, and some of them get pretty creative. jQuery has an excellent method for cloning objects, as does Mootools. There&#8217;s a Javascript hack we can sort of &#8220;exploit&#8221;, or we could just clone our object in plain Javascript. Let&#8217;s start with the vanilla Javascript first and move on from there.</p>
<p><span id="more-452"></span></p>
<h2>1) A vanilla Javascript method for cloning objects</h2>
<p>This is a somewhat simple function that will clone an object and return the clone. If a non-object value is passed in, that value is returned.</p>
<script src="https://gist.github.com/2765673.js"></script><noscript><pre><code class="language-javascript javascript">// recursive function to clone an object. If a non object parameter
// is passed in, that parameter is returned and no recursion occurs.

function cloneObject(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    var temp = obj.constructor(); // give temp the original obj's constructor
    for (var key in obj) {
        temp[key] = cloneObject(obj[key]);
    }

    return temp;
}

var bob = {
    name: &quot;Bob&quot;,
    age: 32
};

var bill = (cloneObject(bob));
bill.name = &quot;Bill&quot;;

console.log(bob);
console.log(bill);</code></pre></noscript>
<p>If you try the above function, you&#8217;ll see that once <span class="code-tag">bob</span> has been cloned as <span class="code-tag">bill</span>, modifying values on <span class="code-tag">bill</span> won&#8217;t change the original values on <span class="code-tag">bob</span>.</p>
<h2>2) A clever exploit of the JSON library to deep-clone objects</h2>
<p>We can exploit the JSON library for a rather fast way of deep-cloning objects. Check it out:</p>
<script src="https://gist.github.com/2765596.js"></script><noscript><pre><code class="language-javascript javascript">var bob = {
    name: &quot;Bob&quot;,
    age: 32
};

var bill = (JSON.parse(JSON.stringify(bob)));
bill.name = &quot;Bill&quot;;

console.log(bob);
console.log(bill);</code></pre></noscript>
<p>This method is nice and fast (faster as a rule than the jQuery method and possibly the Mootools function as well), and certainly rather less code than the first example. Plus, it&#8217;s pretty clever&#8211;just make sure you add a comment explaining what you&#8217;re doing. Otherwise, it could cause quite a bit of confusion!</p>
<h2>3) Using jQuery&#8217;s <span class="code-tag">$.extend()</span> function</h2>
<p>jQuery has a method that can be used to deep-clone objects, the <a href="http://api.jquery.com/jQuery.extend/">$.extend()</a> function. Let&#8217;s take a look at how it can be used:</p>
<script src="https://gist.github.com/2765618.js"></script><noscript><pre><code class="language-javascript javascript">var bob = {
    name: &quot;Bob&quot;,
    age: 32
};

var bill = $.extend(true, {}, bob);
bill.name = &quot;Bill&quot;;

console.log(bob);
console.log(bill);</code></pre></noscript>
<p>Pretty handy, eh? This method is a little slower than the JSON exploit, but that shouldn&#8217;t really be a problem when you&#8217;re only doing a few clones. If you&#8217;re doing hundreds or thousands of clones, it might be time to think about the JSON exploit or another solution.</p>
<h2>4) Using Mootools&#8217; <span class="code-tag">clone()</span> function to clone objects</h2>
<p>Last but not least, the Javascript library Mootools also provides a means of cloning objects&#8211;the rather aptly named <span class="code-tag"><a href="http://mootools.net/docs/core/Types/Object#Object:Object-clone">clone()</a></span> function. Observe the wild <span class="code-tag">clone()</span> in its natural habitat:</p>
<script src="https://gist.github.com/2765664.js"></script><noscript><pre><code class="language-javascript javascript">var bob = {
    name: &quot;Bob&quot;,
    age: 32
};

var bill = Object.clone(bob);
bill.name = &quot;Bill&quot;;

console.log(bob);
console.log(bill);</code></pre></noscript>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://heyjavascript.com/4-creative-ways-to-clone-objects/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
