<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Tim's Blog</title><link>http://timlabonne.com:80/</link><description>Another code blog</description><item><title>Shadow Codex 2 Now Available For Pre-Order</title><link>http://timlabonne.com:80/shadow-codex-2-now-available-for-pre-order</link><description>&lt;p&gt;I'm excited to announce that Shadow Codex 2 is now available for pre-order on the App Store with an expected release date of November 21, 2019!&lt;/p&gt;
&lt;p&gt;&lt;a href="https://apps.apple.com/us/app/shadow-codex-2/id1466242240"&gt; &lt;img src="https://tblabonne.blob.core.windows.net:443/media/Default/Images/Pre-order_on_the_App_Store_Badge_US-UK_RGB_blk_121217.svg" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;From the App Store Description:&lt;/strong&gt;&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;The beloved word/role-playing game mash-up is back! Battle monsters with words to earn experience, collect and craft equipment to increase power, level-up to improve your stats, and learn magic skills to defeat your enemies in battle!&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;FEATURES&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Over 40 monsters to battle each with unique abilities and personalities.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Over 60 skills to learn and master. Can be used to manipulate the puzzle board, heal yourself, or attack your opponent. Use skills in combinations to uncover satisfying strategic opportunities.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; New Crafting system! Collect raw ingredients and materials from enemy drops or the new Forage mini-game to make new equipment, potions, and cook food for healing!&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Collect items with the Forage mini-game. Upgrade your storehouse to store all of the goodies you'll find.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Test your spelling prowess in the timed Endurance Challenge mini-game to earn extra gold and experience.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Defeat enemies to gain access to loot boxes and keys to open dungeon doors.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; New skills and equipment unlock as you level-up.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Defeat enemies to uncover keys to open dungeon doors or reveal a gift box with something special in it!&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;HOW TO PLAY&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Fight a monster by spelling words to gain points. Each letter scores a different amount based on its rarity. Spelling is accomplished by selecting letters that are adjacent to each other.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Score +12 points or more to gain an extra attack! Or find words with a gem on a letter to gain 2x the points!&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Use the points to gain weapon attacks. Each attack can be banked until you want to use it. Strong weapons use more points for an attack. Some weapons can use two attacks at a time.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Consume mana to use skills and spells to manipulate the puzzle board, or cast an effect on your opponent.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Use items to heal yourself or increase mana in battle.&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&amp;bull; Collect items to craft new weapons and armor or buy items from the in-game shop using in-game currency (also available to buy through in-app purchases).&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;&lt;/p&gt;
&lt;p dir="ltr" data-test-bidi="" style="box-sizing: inherit; margin: 0px; padding: 0px; color: #333333; font-family: 'SF Pro Text', 'SF Pro Icons', 'Apple WebExp Icons Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif; letter-spacing: -0.065px;"&gt;Forget about those tired match-3 RPGs and try something different - what players are calling a "breath of fresh air."&lt;/p&gt;</description><pubDate>Fri, 18 Oct 2019 12:44:12 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/shadow-codex-2-now-available-for-pre-order</guid></item><item><title>Announcement:  Shadow Codex 2</title><link>http://timlabonne.com:80/announcement-shadow-codex-2</link><description>&lt;p&gt;I just wanted to announce that I've started work on the sequel to Shadow Codex, tentatively named Shadow Codex 2.&amp;nbsp; Here is a list of new things coming to the game:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;User Interface update and improvement - the game is going to portrait mode with the puzzle board in the middle and one opponent on top and one on the bottom.&amp;nbsp; This gives it a much better experience on the phone and uses the space available in a more phone-centric way.&amp;nbsp; You will be able to play using only one hand.&lt;/li&gt;
&lt;li&gt;New characters to fight with more advanced AI.&lt;/li&gt;
&lt;li&gt;An entirely new adventure, new story, and new quests.&lt;/li&gt;
&lt;li&gt;About half of the spells will be new offerings (with some updates to existing spells).&amp;nbsp; Spells have been renamed "skills", btw.&lt;/li&gt;
&lt;li&gt;New tile power-ups: XP and MP bonuses.&lt;/li&gt;
&lt;li&gt;Two new mini-games.&lt;/li&gt;
&lt;li&gt;There will be some sort of crafting (details are still being designed).&lt;/li&gt;
&lt;li&gt;Generally, faster, sleeker and more polished.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Technical:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Better support for screen sizes for iPhone X (all models) and iPad Pro&lt;/li&gt;
&lt;li&gt;Possibly Android support&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I think the biggest change is going to be the move to portrait mode.&amp;nbsp; When I originally conceived the game, I had no expectations of releasing on phones.&amp;nbsp; That's why it has a 16:9 landscape orientation and doesn't fit quite as well with modern phones like the iPhone X.&amp;nbsp; With Shadow Codex 2, that will no longer be the case and all phone models will be supported so that the screen fills out and uses the most space it can to be universal, even on non-phone devices like iPad.&lt;/p&gt;
&lt;p&gt;I'll probably be posting some screenshots soon when I get a bit farther along and do some phone builds of the game.&lt;/p&gt;</description><pubDate>Thu, 23 May 2019 13:34:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/announcement-shadow-codex-2</guid></item><item><title>Shadow Codex Released!</title><link>http://timlabonne.com:80/shadow-codex-released</link><description>&lt;p&gt;Shadow Codex, a turn-based RPG that uses a word game combat mechanic has been relased on the popular indie games site &lt;a href="http://itch.io"&gt;itch.io&lt;/a&gt;!&amp;nbsp; It is available for Windows or macOS.&amp;nbsp; Alternatively, you can purchase on the Mac App Store.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;iframe frameborder="0" src="https://itch.io/embed/382196?link_color=0484d1" width="552" height="167"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;Watch the Trailer:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/iwAGtYDOWww" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""&gt;&lt;/iframe&gt;&lt;/p&gt;</description><pubDate>Sat, 09 Mar 2019 01:19:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/shadow-codex-released</guid></item><item><title>Shadow Codex Available For Pre-Order!</title><link>http://timlabonne.com:80/shadow-codex-available-for-pre-order</link><description>&lt;p&gt;My latest game project is finally done:&amp;nbsp; Shadow Codex which is a unique word-game/RPG hybrid.&amp;nbsp; It is available now for pre-order on the App Store for iPhone, iPad, and iPod Touch and is also available on the Mac App Store for macOS.&lt;/p&gt;
&lt;p&gt;Here is a video showing the first few minutes of gameplay:&lt;/p&gt;
&lt;p&gt;&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/ayTKULkJPUk" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://itunes.apple.com/us/app/shadow-codex/id1452014771?mt=8"&gt; &lt;img src="https://tblabonne.blob.core.windows.net:443/media/Default/Images/Pre-order_on_the_App_Store_Badge_US-UK_RGB_blk_121217.svg" /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&lt;a href="https://geo.itunes.apple.com/us/app/shadow-codex/id1453561193?mt=12&amp;amp;app=apps"&gt;&lt;img src="https://tblabonne.blob.core.windows.net:443/media/Default/Images/Download_on_the_Mac_App_Store_Badge_US-UK_RGB_blk_092917.svg" /&gt;&lt;/a&gt; &lt;span&gt;&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;From the App Store Description:&lt;/strong&gt;&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;Battle for good against an evil force in this unique word/RPG hybrid game!&amp;nbsp; Face off against countless enemies by mastering words, spells, weapons, and items.&amp;nbsp; Explore an ever-unfolding map with characters to meet, stories to tell, and quests to embark upon.&amp;nbsp; Earn gold and visit shops to upgrade your equipment and buy items.&amp;nbsp; Earn experience to level up and improve your character's fighting stats in combat.&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;In Shadow Codex, turn-based combat is accomplished by spelling words on a shared game board of letters.&amp;nbsp;&amp;nbsp; Pick a letter and chain it to an adjacent letter to form a valid word.&amp;nbsp; Each word you spell will earn a certain score.&amp;nbsp; This score is added to your "action points".&amp;nbsp; If you reach a certain amount as defined by your equipped weapon, you will gain a weapon attack to use.&amp;nbsp; Rare letters and longer words give big scores where you can potentially gain extra turns or numerous attacks!&amp;nbsp; Gems on letters will double the score!&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;In addition to word-spelling, you can also cast powerful spells.&amp;nbsp; These spells can change letters on the game board, heal you, damage your enemy, and can be learned by defeating foes and completing quests.&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;EXPERIENCE COMBAT&lt;/p&gt;
&lt;ul type="disc" style="margin-left: .375in; direction: ltr; unicode-bidi: embed; margin-top: 0in; margin-bottom: 0in;"&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Face off against over 45 characters and monsters w/ unique abilities!&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Earn gold to purchase new weapons with unique stats and abilities.&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Earn XP to level-up and improve your stats and magic power.&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Cast spells to gain an advantage or aid your word-spelling ability.&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Use items to heal yourself and win the battle!&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p style="margin: 0in; font-family: Calibri; font-size: 11.0pt;"&gt;PLAY THE MINI-GAMES&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;ul type="disc" style="margin-left: .375in; direction: ltr; unicode-bidi: embed; margin-top: 0in; margin-bottom: 0in;"&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;3 extra mini-games help you earn gold and experience!&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Test your spelling speed in the Endurance Trial game.&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Unlock chests by playing a word search-type game.&amp;nbsp; You never know what you'll find!&lt;/span&gt;&lt;/li&gt;
&lt;li style="margin-top: 0; margin-bottom: 0; vertical-align: middle;"&gt;&lt;span style="font-family: Calibri; font-size: 11.0pt;"&gt;Collect or harvest items quickly to aid your fellow citizens and earn rewards!&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;</description><pubDate>Thu, 07 Mar 2019 14:02:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/shadow-codex-available-for-pre-order</guid></item><item><title>RavenDB Survival Tip #3: Handling Polymorphism</title><link>http://timlabonne.com:80/2013/08/ravendb-survival-tip-3-handling-polymorphism/</link><description>&lt;p&gt;If you want to store objects in your database that are implementations of interfaces or base classes, you can do this pretty easily by alternating Raven&amp;rsquo;s JSON serializer settings so that when Raven serializes your object, it includes a special &amp;ldquo;$type&amp;rdquo; property in the JSON that records the full type name of the object.&lt;/p&gt;
&lt;p&gt;The documentation for RavenDB actually mentions this, but there&amp;rsquo;s a little change that I do to make it a little more efficient.&amp;nbsp; The docs say to use a TypeNameHandling convention of &amp;ldquo;All&amp;rdquo; but this will emit the $type property on &lt;em&gt;every single object&lt;/em&gt;.&amp;nbsp; This is a waste of space and creates a lot of clutter.&amp;nbsp; You should instead use TypeNameHandling.Auto.&amp;nbsp; This setting will only include the $type property if the type of the property does not match the actual type of the object.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s how you&amp;rsquo;d set this up (I&amp;rsquo;m assuming that you have a DocumentStore instance available).&amp;nbsp; You&amp;rsquo;d perform this setup only when initially creating the DocumentStore (once per app):&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;store.Conventions.CustomizeJsonSerializer = serializer =&amp;gt;
{
    serializer.TypeNameHandling = 
        Raven.Imports.Newtonsoft.Json.TypeNameHandling.Auto;
};
&lt;/pre&gt;</description><pubDate>Thu, 01 Aug 2013 15:00:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/08/ravendb-survival-tip-3-handling-polymorphism/</guid></item><item><title>Parsing a Time String with JavaScript</title><link>http://timlabonne.com:80/2013/07/parsing-a-time-string-with-javascript/</link><description>&lt;p&gt;Let’s say you are building a UI where you’d like a user to enter a time into a text box.&amp;nbsp; This time value they might enter needs to handle a lot of different formats, but we’d like it to end up as the same value either way:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;1pm  &lt;li&gt;1:00pm  &lt;li&gt;1:00p  &lt;li&gt;13:00&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Here’s a little JavaScript function to do this work.&amp;nbsp; Most of the interesting bits are the regular expression which helps handle of these various scenarios.&amp;nbsp; It takes a string representation of a time and attempts to parse it, setting the time on the specified date object sent to the function as the second parameter.&amp;nbsp; In the case where you do not provide a second parameter, the current date will be used.&lt;/p&gt;&lt;pre class="brush: js;"&gt;function parseTime(timeStr, dt) {
    if (!dt) {
        dt = new Date();
    }

    var time = timeStr.match(/(\d+)(?::(\d\d))?\s*(p?)/i);
    if (!time) {
        return NaN;
    }
    var hours = parseInt(time[1], 10);
    if (hours == 12 &amp;amp;&amp;amp; !time[3]) {
        hours = 0;
    }
    else {
        hours += (hours &amp;lt; 12 &amp;amp;&amp;amp; time[3]) ? 12 : 0;
    }

    dt.setHours(hours);
    dt.setMinutes(parseInt(time[2], 10) || 0);
    dt.setSeconds(0, 0);
    return dt;
}&lt;/pre&gt;
&lt;p&gt;This function will return NaN if it can’t parse the input at all.&amp;nbsp; The logic immediately following the match() call is to handle the noon/midnight case correctly.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Here’s a jsFiddle of this in action:&lt;/p&gt;

&lt;iframe width="100%" height="300" src="http://jsfiddle.net/xTn4Z/2/embedded/" allowfullscreen="allowfullscreen" frameborder="0"&gt;&lt;/iframe&gt;</description><pubDate>Wed, 31 Jul 2013 14:56:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/parsing-a-time-string-with-javascript/</guid></item><item><title>Fun with Statistics Calculations</title><link>http://timlabonne.com:80/2013/07/fun-with-statistics-calculations/</link><description>&lt;p&gt;A while back I was working on a system where we were going to score work items to measure risk of auditing.&amp;nbsp; Higher numbers would most likely result in an audit while lower numbers would pass.&amp;nbsp; The exact mechanism of measuring the risk is immaterial for this post, so we’ll treat it as a black box number.&amp;nbsp; Furthermore, we calculate the risk on all work items but only update our statistics (as described below) on work items that actually &lt;em&gt;did&lt;/em&gt; get audited.&lt;/p&gt; &lt;p&gt;I wanted to know whether the audit score for a particular work item was very far away from the mean or very under the mean.&amp;nbsp; If it was low, the audit risk should be low and vice versa.&amp;nbsp; What we are looking for here is a “sigma” level – or a number that indicates how far away from the mean something is.&amp;nbsp; If something has a sigma level of zero, it means it is equal to the mean.&amp;nbsp; If it has a sigma level of 1, it means it is 1 standard deviation above the mean.&amp;nbsp; -1 means that it is one standard deviation below the mean.&amp;nbsp; Lower levels of sigma are generally better than higher ones in this system.&amp;nbsp; In normalized data, we’d expect over two-thirds of the work items to score within +/- 1 sigma.&amp;nbsp; A sigma number of 6 or higher means that the score would be a very large outlier.&lt;/p&gt; &lt;p&gt;To calculate this sigma value, we need two primary pieces of data – the mean and the standard deviation of the population or sample (i.e. the audit risk scores).&amp;nbsp; I did not want to calculate these values over the entire set of data each time I wanted to compute the sigma level – I just wanted to add it to the previous mean and standard deviation to make calculations really fast.&lt;/p&gt; &lt;p&gt;Let’s start with the mean.&amp;nbsp; If we save the number of data points used (n) and the previous mean calculated (ca), we can derive the new mean given a new data point (x) with the following formula:&lt;/p&gt; &lt;p&gt;new_mean = (x + n * ca) / (n + 1)&lt;/p&gt; &lt;p&gt;Or in C#:&lt;/p&gt;&lt;pre class="brush: js;"&gt;public static double CalculateNewCumulativeAverage(int n, int x, double ca)
{
    return (x + n * ca) / (n + 1);
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The standard deviation calculation is a little harder.&amp;nbsp; The Wikipedia article at &lt;a title="http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods" href="http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods"&gt;http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods&lt;/a&gt; describes a method for rapid calculation that requires you to only provide the following variables to compute a new standard deviation given a new data point (x): n – the number of previous data points used, s1 – sum of all previous x’s, and s2 – sum of all previous x^2 (squared).&amp;nbsp; Here’s the formula in C#:&lt;/p&gt;&lt;pre class="brush: js;"&gt;public static double CalculateNewStandardDeviation(int n, int x, int s1, long s2)
{
    if (n == 0)
        return double.NaN;
    s1 += x;
    s2 += x * x;
    double num = (n + 1) * s2 - (s1 * s1);
    double denom = (n + 1) * n;
    return Math.Sqrt(num / denom);
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This will be a very fast way of calculating standard deviation because you simply don’t have to go over all data points (which also means not reading values out of a database).&lt;/p&gt;
&lt;p&gt;The sigma value I talked about earlier can then be calculated given the data point (x), cumulative mean (ca) and standard deviation (s):&lt;/p&gt;&lt;pre class="brush: js;"&gt;public static double CalculateSigma(int x, double ca, double s)
{
    return (x - ca) / s;
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;So all you will need to store in your database is the following scalar values to calculate these stats:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Total number of data points (n).&lt;/li&gt;
&lt;li&gt;Sum of all data points (s1).&lt;/li&gt;
&lt;li&gt;Sum of the squares of all data points (s2).&lt;/li&gt;
&lt;li&gt;Cumulative average or mean (ca).&lt;/li&gt;
&lt;li&gt;Current standard deviation (s).&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;To add a new data point (x) and update all variables to new values:&lt;/p&gt;&lt;pre class="brush: js;"&gt;public static void AddDataPoint(int x, ref int n, ref int s1, ref int s2, ref double ca, ref double s)
{
    ca = CalculateNewCumulativeAverage(n, x, ca);
    s = CalculateNewStandardDeviation(n, x, s1, s2);
    n += 1;
    s1 += x;
    s2 += x * x;
}
&lt;/pre&gt;</description><pubDate>Fri, 26 Jul 2013 17:47:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/fun-with-statistics-calculations/</guid></item><item><title>Improving on KoLite</title><link>http://timlabonne.com:80/2013/07/improving-on-kolite/</link><description>&lt;p&gt;In my posts on creating a dynamic menu system, I used KoLite commands to represent what gets invoked when clicking on a menu item.&amp;nbsp; KoLite adds a command abstraction to Knockout that cleanly encapsulates the execution of a command and the status of a command (with the canExecute() computed, you can disable UI widgets that cannot be executed in the current state).&lt;/p&gt; &lt;p&gt;There was just one thing missing from the command that I wanted: the ability to tell if a command is toggled or &lt;em&gt;latched&lt;/em&gt;.&amp;nbsp; Latching a command means that the command is “on” and all UI elements bound to this can update their state (for example, a menu item in a drop down menu typically has a checkmark or dot placed next to the item to convey that the item is on or toggled).&lt;/p&gt; &lt;p&gt;The concept of latching is very simple to implement.&amp;nbsp; In knockout.command.js, I added the following code to the ko.command constructor function:&lt;/p&gt;&lt;pre class="brush: js;"&gt;ko.command = function (options) {
    var self = ko.observable(),
        canExecuteDelegate = options.canExecute,
        executeDelegate = options.execute,
        latchedDelegate = options.isLatched; // new

    // new computed; everything else is the same
    self.isLatched = ko.computed(function () {
        return latchedDelegate ? latchedDelegate() : false;
    });
};
&lt;/pre&gt;
&lt;p&gt;This is really simple – it’s just adding a function that delegates to another function you supply when you setup the command.&amp;nbsp; This function you supply represents the logic required to tell if the command is in a latched state or not.&lt;/p&gt;
&lt;p&gt;Here’s an example of how this could be used:&lt;/p&gt;&lt;pre class="brush: js;"&gt;var showStatusBarCmd = ko.command({
    execute: function () {
        showStatusBar(!showStatusBar);
    },
    isLatched: function () {
        return showStatusBar() === true;
    }
});
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In this example, there’s an observable in the outer scope called showStatusBar that will be used to determine if the status bar in the app is visible.&amp;nbsp; If the user clicks on a menu item bound to this command, the execute() handler will fire toggling the showStatusBar observable.&amp;nbsp; The status bar’s visibility is then bound to this value.&amp;nbsp; Now for latching, the isLatched handler will test to see if showStatusBar is true and will return true if it is. &lt;/p&gt;
&lt;p&gt;Now, in the menu system you would probably wire up an element that would show a checkmark or a dot next to the menu item if the command’s latched state is on.&amp;nbsp; Note that you could have two different UI elements bound to the same command (like a menu item and a toolbar button) and both would be synchronized automatically to changes in the app’s state.&lt;/p&gt;</description><pubDate>Fri, 26 Jul 2013 17:06:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/improving-on-kolite/</guid></item><item><title>Getting Compile-on-Save to work for TypeScript in VS2012</title><link>http://timlabonne.com:80/2013/07/getting-compile-on-save-to-work-for-typescript-in-vs2012/</link><description>&lt;p&gt;I’m poking around with TypeScript and the word on the street was that a recent addition to the plugin for VS2012 (v. 0.8.x) added the ability to do compilation from TypeScript to JavaScript when saving.&amp;nbsp; I discovered it doesn’t actually work quite right out of the box.&amp;nbsp; There are two things you need to do:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Enable compile on save in the Tools –&amp;gt; Options menu.&lt;/li&gt; &lt;li&gt;Add a &amp;lt;PropertyGroup&amp;gt; to your .csproj file to configure the TypeScript compiler.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;To enable compile-on-save, do the following:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Navigate to Tools –&amp;gt; Options.&lt;/li&gt; &lt;li&gt;On the left side, expand Text Editor and find TypeScript, and then the Project sub-node.&lt;/li&gt; &lt;li&gt;Check the “Automatically compile TypeScript files which are part of a project”&lt;/li&gt; &lt;li&gt;Click OK to save changes.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;Next, you need to update your project that you are using to contain the appropriate properties to configure the build target for the TypeScript compiler.&amp;nbsp; Add this XML to your .csproj (first, unload the project and then edit the .csproj file manually):&lt;/p&gt;&lt;pre class="brush: xml;"&gt;&amp;lt;PropertyGroup Condition="'$(Configuration)' == 'Debug'"&amp;gt;
  &amp;lt;TypeScriptTarget&amp;gt;ES5&amp;lt;/TypeScriptTarget&amp;gt;
  &amp;lt;TypeScriptIncludeComments&amp;gt;true&amp;lt;/TypeScriptIncludeComments&amp;gt;
  &amp;lt;TypeScriptSourceMap&amp;gt;true&amp;lt;/TypeScriptSourceMap&amp;gt;
  &amp;lt;TypeScriptModuleKind&amp;gt;amd&amp;lt;/TypeScriptModuleKind&amp;gt;
&amp;lt;/PropertyGroup&amp;gt;
&amp;lt;PropertyGroup Condition="'$(Configuration)' == 'Release'"&amp;gt;
  &amp;lt;TypeScriptTarget&amp;gt;ES5&amp;lt;/TypeScriptTarget&amp;gt;
  &amp;lt;TypeScriptIncludeComments&amp;gt;false&amp;lt;/TypeScriptIncludeComments&amp;gt;
  &amp;lt;TypeScriptSourceMap&amp;gt;false&amp;lt;/TypeScriptSourceMap&amp;gt;
  &amp;lt;TypeScriptModuleKind&amp;gt;amd&amp;lt;/TypeScriptModuleKind&amp;gt;
&amp;lt;/PropertyGroup&amp;gt;
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Notice that you can set various compiler options here that you normally set as a command-line parameter when using the tsc compiler program.&amp;nbsp; In this case, I added the &amp;lt;TypeScriptModuleKind&amp;gt; element which tells the compiler how to generate the module requiring code.&amp;nbsp; Here, I’ve set mine up to use AMD rather than CommonJS (which is the default).&amp;nbsp; My Target is also “ES5” so it will target ECMAScript 5 rather than the default ECMAScript 3.&amp;nbsp; &lt;/p&gt;</description><pubDate>Fri, 19 Jul 2013 15:31:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/getting-compile-on-save-to-work-for-typescript-in-vs2012/</guid></item><item><title>Using C# Implicit Type Conversion</title><link>http://timlabonne.com:80/2013/07/using-c-implicit-type-conversion/</link><description>&lt;p&gt;I was recently required to connect to a SOAP-based web service that had a very nasty WSDL.&amp;nbsp; It contained tons of complex type definitions for objects that really didn’t need to exist (strings and decimals and integers would have been sufficient).&amp;nbsp; For example, here’s a snippet of a complex type defined in the WSDL that I needed to consume:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public partial class TOTAL_AMT_TypeShape : object, INotifyPropertyChanged 
{
    private decimal valueField;

    public decimal Value
    {
        get { return this.valueField; }
        set 
        {
            this.valueField = value;
            this.RaisePropertyChanged("Value");
        }
    }

    // snip...
}

&lt;/pre&gt;
&lt;p&gt;This class is created by Visual Studio and is the proxy for the TOTAL_AMT_TypeShape object.&amp;nbsp; As you can probably surmise, this is simply a complex type wrapping a number (a C# decimal to be exact).&amp;nbsp; The name is awful, and the whole premise of requiring a complex type for a simple number amount (a dollar amount in this case) makes the use of this type really awkward:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;decimal amount = 100000.0m;
TOTAL_AMT_TypeShape totalAmt = new TOTAL_AMT_TypeShape() { Value = amount };
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Now imagine this like times 100.&amp;nbsp; It can get really ugly, really fast.&lt;/p&gt;
&lt;p&gt;My solution was to rely on partial classes and implicit type conversion.&amp;nbsp; Implicit type conversion is a C# feature that allows you to convert between data types automatically by informing the compiler how to perform the conversion.&amp;nbsp; The conversion happens automatically and should only be used where the conversion will not result in any data loss or possibly throw an exception (if either of those scenarios exists, you should use an explicit cast conversion instead).&amp;nbsp; An example of an implicit conversion built into C# would be int to long conversion.&amp;nbsp; Since an int always fits inside a long, we can assign a long variable to an int without any special effort.&amp;nbsp; The opposite is not true, however, and we’d need to explicitly cast.&lt;/p&gt;
&lt;p&gt;Here’s my partial class with the implicit conversion operator added:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public partial class TOTAL_AMT_TypeShape
{
    public static implicit operator TOTAL_AMT_TypeShape(decimal value) 
    {
        return new TOTAL_AMT_TypeShape() { Value = value };
    }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The implicit conversion operator overload is defined for converting a decimal to a TOTAL_AMT_TypeShape (the output type is always the name of overload method).&amp;nbsp; We could also go the other way (convert a TOTAL_AMT_TypeShape into a decimal, but I didn’t need to in my case).&amp;nbsp; And because C# allows partial class definitions, if our proxy object definition changes because of a WSDL refresh, we keep our partial intact and the code for the implicit conversion won’t be overwritten.&lt;/p&gt;
&lt;p&gt;Here’s how we’d use it now:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;TOTAL_AMT_TypeShape totalAmt = 100000.0m;
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Nice and neat.&lt;/p&gt;</description><pubDate>Tue, 16 Jul 2013 18:19:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/using-c-implicit-type-conversion/</guid></item><item><title>Distributing Monetary Amounts in C#</title><link>http://timlabonne.com:80/2013/07/distributing-monetary-amounts-in-c/</link><description>&lt;p&gt;Many times in financial applications, you will be tasked with distributing or allocating monetary amounts across a set of ratios (say, a 50/50 split or maybe a 30/70 split).&amp;nbsp; This can be tricky getting the rounding right so that no pennies are lost in the allocation.&lt;/p&gt; &lt;p&gt;Here’s an example:&amp;nbsp; split $0.05 in a 30/70 ratio.&amp;nbsp; The 30% amount becomes $0.015 and the 70% will be $0.035.&amp;nbsp; Now in this case, they both add up to the original amount (which is an absolute requirement) but they must have a half penny each to accomplish this.&amp;nbsp; We can’t have half pennies in this situation, so something has to be done with the extra penny.&lt;/p&gt; &lt;p&gt;Now the specifics on where you allocate the extra penny are up to your business requirements, so the solution I present below may not be exactly what you need.&amp;nbsp; It should, however, give you an idea on how to do this split without losing the extra penny.&amp;nbsp; Here’s a static method that will take a single monetary amount (as a C# decimal) and an array of ratios.&amp;nbsp; These ratios are your allocation percentages.&amp;nbsp; They could be the set [0.30, 0.70] or even [30, 70].&amp;nbsp; They don’t even need to sum to 1 or 100, it doesn’t matter:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public static decimal[] DistributeAmount(decimal amount, decimal[] ratios)
{
    decimal total = 0;
    decimal[] results = new decimal[ratios.Length];

    // find the total of the ratios
    for (int index = 0; index &amp;lt; ratios.Length; index++)
        total += ratios[index];

    // convert amount to a fixed point value (no mantissa portion)
    amount = amount * 100;
    decimal remainder = amount;
    for (int index = 0; index &amp;lt; results.Length; index++)
    {
        results[index] = Math.Floor(amount * ratios[index] / total);
        remainder -= results[index];
    }

    // allocate remainder across all amounts
    for (int index = 0; index &amp;lt; remainder; index++)
        results[index]++;

    // convert back to decimal portion
    for (int index = 0; index &amp;lt; results.Length; index++)
        results[index] = results[index] / 100;

    return results;
}

&lt;/pre&gt;
&lt;p&gt;(Another thing here is that I am assuming pennies and dollars, or at least a currency system that divides their unit of currency into hundredths – notice the multiply by 100.&amp;nbsp; You can change that for universal currency systems to support any currency).&lt;/p&gt;
&lt;p&gt;This code works by converting amounts to a fixed point value with no mantissa.&amp;nbsp; So in our example, $0.05 turns into 5.&amp;nbsp; We then iterate over each ratio and compute the amount to distribute using a simple division.&amp;nbsp; The trick here is the Math.Floor().&amp;nbsp; We round all half pennies down.&amp;nbsp; The half-penny will stay in the remainder variable.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;At the end of the distribution, we then distribute all of the fractional pennies that have built up evenly across the distributed amounts.&amp;nbsp; If there are no remaining pennies to distribute, it simply ends.&amp;nbsp; So in this implementation, the first ratios in the set tend to get the extra pennies and the last one loses out.&amp;nbsp; You can change this behavior to be almost anything you like (such as random, even-odd, or something else).&lt;/p&gt;
&lt;p&gt;At the very end, we convert back to a decimal portion by dividing each amount by 100.&lt;/p&gt;
&lt;p&gt;The final results for $0.05 would be { 0.02, 0.03 }, which adds up to 0.05.&lt;/p&gt;</description><pubDate>Tue, 16 Jul 2013 17:42:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/distributing-monetary-amounts-in-c/</guid></item><item><title>Revisiting War of Words: Postmortem</title><link>http://timlabonne.com:80/2013/07/revisiting-war-of-words-postmortem/</link><description>&lt;p&gt;A postmortem usually happens within a small timeframe after release.&amp;nbsp; Well, I waited 3.5 years, lol.&amp;nbsp; Anyway, this is my take on what went right with design and development and what went wrong.&lt;/p&gt; &lt;h2&gt;What Went Right&lt;/h2&gt; &lt;p&gt;&lt;strong&gt;1.&amp;nbsp; Word Graphs and AI characters&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Implementing a word graph to store the word list was a great idea because it gave me so much flexibility in solving problems.&amp;nbsp; I was able to search the graph with the AI engine and find words very quickly.&amp;nbsp; I loved that the Game Studio Content Pipeline allowed me to create processors that could take lists of words and create a word graph structure out of them.&amp;nbsp; I saved off this structure to disk and loaded it very quickly at game startup.&amp;nbsp; I played other word games on the XBox Indie Games platform and many had long load times (probably because they were processing giant XML files or something).&lt;/p&gt; &lt;p&gt;The AI was also a pretty good implementation IMO.&amp;nbsp; It looked very natural, and it scaled up and down in difficulty nicely.&amp;nbsp; It wasn’t perfect, but extending it and tweaking it was pretty simple.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;2.&amp;nbsp; Overall Game Concept&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;The RPG/word game concept is a good idea and I think I executed it well enough when it came to the core game play features.&amp;nbsp; I’m pleased with it and would use it as a template for a sequel if I wanted to.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;3.&amp;nbsp; Getting an Artist to do the Artwork&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Obviously this is a no-brainer if you want something to look good.&amp;nbsp; I simply don’t have the artistic talent.&amp;nbsp; The take away here is that if you want something to be professional, you need to put the money up to get an artist.&lt;/p&gt; &lt;h2&gt;What Went Wrong&lt;/h2&gt; &lt;p&gt;&lt;strong&gt;1.&amp;nbsp; Some Graphics were not done by the Artist&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;I decided to do some of the graphics myself which was stupid and I think it led to it looking a little unprofessional at times.&amp;nbsp; I also think the box art could have been better but I didn’t do anything about it.&amp;nbsp; A lot of people judge a game by the box art.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;2.&amp;nbsp; The story made no sense and was bad&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;There’s not much to say here.&amp;nbsp; It wasn’t good.&amp;nbsp; It wasn’t interesting.&amp;nbsp; Maybe it was even laughable.&amp;nbsp; I’m not a writer and I don’t pretend to be one.&amp;nbsp; In the end, a lot of reviewers pointed this out but many would then positively point out that it didn’t matter if the story sucked because the game play was good.&amp;nbsp; The presentation of the story was low tech and uninteresting too.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;3.&amp;nbsp; The map was not implemented well and was not interesting&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;The map needed to be a little better drawn and more interesting IMO.&amp;nbsp; The controls on the map were not done very well.&amp;nbsp; I should’ve used a model where the cursor was more freely controllable by the player.&amp;nbsp; The icon stand-in for the player was stupid.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;4.&amp;nbsp; Random encounters were confusing&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;When you moved between locations on a map, you might randomly be attacked by an enemy.&amp;nbsp; At that point, you can either flee or fight.&amp;nbsp; If you fled, you incurred some HP damage.&amp;nbsp; If you fought, you could usually win the battle but it took too long.&amp;nbsp; This whole process was just not done very well and needed to be re-thought.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;5.&amp;nbsp; Shields were a dumb concept&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;In combat, you could earn shields by scoring big words.&amp;nbsp; The AI character also had shields.&amp;nbsp; If you were about to get attacked, you could tap a button and raise the shields for 5 seconds or so of 50% or better armor.&amp;nbsp; The problem was, however, that human players couldn’t quickly raise the shields and ended up getting hit and then raising them.&amp;nbsp; I bet this made them feel like an idiot.&amp;nbsp; The AI of course perfectly handled shields and it was very unfair.&amp;nbsp; The shield concept should go!&amp;nbsp; You already wear armor so I don’t know what I was thinking.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;6.&amp;nbsp; Quests were not interesting&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;A “Quest” in War of Words was just a scripted encounter (a single battle).&amp;nbsp; There were no other variations on this theme.&amp;nbsp; I should have went for more complicated quests that involved multiple encounters, travel, other game types, etc.&amp;nbsp; I have a lot of new ideas but they didn’t make it into the original and it got boring after a while.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;7.&amp;nbsp; Battles lasted too long&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Sometimes you’d spend 10 minutes or more on one character.&amp;nbsp; This isn’t good.&amp;nbsp; I did try to make this better at one point but still didn’t turn out as well as I had hoped.&amp;nbsp; If they were shorter, we could have had more of them or they could’ve been more interesting.&amp;nbsp; Another variation on this is that it might have been too difficult to beat.&amp;nbsp; If you got wasted at the last minute, you had to repeat the (long) encounter all over again.&amp;nbsp; I don’t know, I didn’t want the game to be too easy though.&amp;nbsp; It is really hard to judge the difficulty of your own game.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;There’s probably a lot more “wrongs” to write about, but I don’t want to beat up on myself too much here :).&amp;nbsp; I think the overall theme here is that polish was lacking in many areas and polish is what makes a game great.&amp;nbsp; &lt;/p&gt;</description><pubDate>Mon, 15 Jul 2013 12:00:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/revisiting-war-of-words-postmortem/</guid></item><item><title>Building a Dynamic Application Menu with Durandal.js, Knockout, and Bootstrap (Pt. 3)</title><link>http://timlabonne.com:80/2013/07/building-a-dynamic-application-menu-with-durandal-js-knockout-and-bootstrap-pt-3/</link><description>&lt;p&gt;In the last two posts of this series, we built a dynamic menu system.&amp;nbsp; Now it is time to wrap it up with a discussion on how to actually populate and use these menus.&lt;/p&gt; &lt;p&gt;One idea is to create the concept of a workspace which represents the UI that the user sees for the application.&amp;nbsp; The workspace is like a top-level window in a desktop application.&amp;nbsp; The following module defines a workspace that contains a list of menus and defines a routine to take arbitrary menu layout objects and convert them to Menu and MenuItem instances:&lt;/p&gt;&lt;pre class="brush: js;"&gt;define(function (require) {
    var Menu = require('ui/menu'),
        MenuItem = require('ui/menuItem'),
        menus = ko.observableArray([]);

    function setupWorkspace(cmds) {
        menus([]);

        var menus = {
            "File": [
                { text: "New", command: cmds.new },
                { text: "Open", command: cmds.open },
                { divider: true },
                { text: "Save", command: cmds.save },
                { text: "Save As", command: cmds.saveas },
                { divider: true },
                { text: "Sign out", command: cmds.signout }
            ],
            "Edit": [
                { text: "Cut", command: cmds.cut },
                { text: "Copy", command: cmds.copy },
                { text: "Paste", command: cmds.paste }
            ],
            "View": [
                { text: "View Mode", subItems: [
                    { text: "Simple", command: cmds.toggleSimpleView },
                    { text: "Advanced" command: cmds.toggleAdvancedView }
                ]}
            ],
            "Help": [
                { text: "Contents", command: cmds.helpcontents },
                { divider: true },
                { text: "About", command: cmds.about }
            ]
        };

        loadMenus(menus);
    }

    function loadMenus(menuDefinitions) {
        var menuText, menu;
        for (menuText in menuDefinitions) {
            menu = addMenu(menuText);
            addMenuItems(menu, menuDefinitions[menuText]);
        }
    }

    function addMenuItems(menuOrMenuItem, itemDefinitions) {
        for (var i = 0; i &amp;lt; itemDefinitions.length; i++) {
            var definitionItem = itemDefinitions[i];
            if (definitionItem.hasOwnProperty("divider")) {
                menuOrMenuItem.addDivider();
            }
            else {
                var menuItem = new MenuItem(definitionItem.text, definitionItem.command);
                menuOrMenuItem.addMenuItem(menuItem);
                if (definition.hasOwnProperty("subItems")) {
                    addMenuItems(menuItem, definitionItem.subItems);
                }
            }
        }
    }

    function addMenu(text, position) {
        var menu = new Menu(text);
        if (position) {
            menus.splice(position, 0, menu);
        }
        else {
            menus.push(menu);
        }

        return menu;
    }

    var workspace = {
        menus: menus,
        addMenu: addMenu,
        setupWorkspace: setupWorkspace
    };

    return workspace;
});

&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The main application shell should call the workspace singleton’s setupWorkspace() function and pass in an object that contains references to the desired ko.commands that will get attached to the menu items.&amp;nbsp; It can also use the menus property in its data-binding to automatically create the UI (as seen in part 2 of this series).&lt;/p&gt;
&lt;p&gt;The setupWorkspace() function creates a menu definition which is just an inline object literal.&amp;nbsp; The source for this could actually come from the server as JSON, or be in another file, or loaded by a plugin.&amp;nbsp; The point is that there is a definition format that gets fed into the loadMenus() function that builds the menus by converting the definition into real Menu and MenuItem instances and adding them to the collection.&lt;/p&gt;
&lt;p&gt;The workspace module also exports the addMenu() function which allows someone to add a menu to the menu bar after the initial setup has taken place.&amp;nbsp; I think more functions (like remove) could be added if you really want to make this robust as far as configuration of menus is concerned (I’m just demoing this to illustrate a point).&amp;nbsp; And obviously, the commands aren’t built and this is very demo-specific, but you can just swap that out for whatever you want.&amp;nbsp; You could even send the menu definitions to the setupWorkspace() function instead of embedding it directly in the function.&lt;/p&gt;
&lt;p&gt;You can view a live demo of this series at: &lt;a href="http://tblabonne.github.io/DynamicMenus/"&gt;http://tblabonne.github.io/DynamicMenus/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The complete source to the demo can be found at: &lt;a href="http://github.com/tblabonne/DynamicMenus"&gt;http://github.com/tblabonne/DynamicMenus&lt;/a&gt;&lt;/p&gt;</description><pubDate>Sun, 14 Jul 2013 17:10:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/building-a-dynamic-application-menu-with-durandal-js-knockout-and-bootstrap-pt-3/</guid></item><item><title>Revisiting War of Words</title><link>http://timlabonne.com:80/2013/07/revisiting-war-of-words/</link><description>&lt;p&gt;Back in March 2010, I released a game called &lt;a href="http://marketplace.xbox.com/en-US/Product/War-of-Words/66acd000-77fe-1000-9115-d80258550474"&gt;War of Words&lt;/a&gt; on the XBox 360 platform (Indie games).&amp;nbsp; This game was a hybrid RPG/Word game that used word spelling as the princaipal combat mechanism in the encounters.&amp;nbsp; It was very similar to Puzzle Quest in spirit, although the core game play mechanisms were quite different.&amp;nbsp; &lt;/p&gt; &lt;p&gt;I had a lot of fun working on that game (and a lot of frustrations too).&amp;nbsp; I had hoped that it would have done better in the marketplace than it did, but Indie Games was not promoted by Microsoft much and I think the game also lacked some polish that would have made it more professional like an Arcade title.&amp;nbsp; For example, some graphics weren’t so great (as they were created by me) and the storyline was not very interesting (my fault again, as I am not a good writer either).&amp;nbsp; I do think the game was better than the average Indie game.&amp;nbsp; It currently is rated as 3.5/5 stars on the XBox marketplace with 232 votes (hardly any Indie games score over 3 stars, and many Arcade and AAA titles struggle to get over 4 stars).&amp;nbsp; &lt;/p&gt; &lt;div style="padding-bottom: 0px; margin: 0px auto; padding-left: 0px; width: 425px; padding-right: 0px; display: block; float: none; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:36768a71-2444-4eb2-bc6e-2b4f4f0cdd70" class="wlWriterEditableSmartContent"&gt;&lt;div&gt;&lt;object width="425" height="355"&gt;&lt;param name="movie" value="http://www.youtube.com/v/aLbsUD6LkTs&amp;amp;hl=en"&gt;&lt;/param&gt;&lt;embed src="http://www.youtube.com/v/aLbsUD6LkTs&amp;amp;hl=en" type="application/x-shockwave-flash" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2&gt;&lt;/h2&gt; &lt;h2&gt;Economics&lt;/h2&gt; &lt;p&gt;This game cost me about $600 USD to make.&amp;nbsp; About $250 of it was for a few hours of an artist’s time to draw the majority of the graphics.&amp;nbsp; Another $200 was spent on audio/music licensing.&amp;nbsp; I also had a domain name and website (which has been taken down) which cost $100 for a year.&amp;nbsp; I bought a few misc. things like video capture software to take video for promotions.&lt;/p&gt; &lt;p&gt;As far as revenue, I can’t say exactly how much it made because the history of payment is long gone (most of the profits were made in the first 3 months of release and Microsoft does not keep more than about 18 months of history).&amp;nbsp; I started out selling the game for 400 points ($5 USD) but later dropped it to 240 points ($3 USD).&amp;nbsp; I make about 70% of that amount per game.&amp;nbsp; I do know that dropping the price increased the purchase to trial ratio to almost 25% which is quite excellent.&amp;nbsp; I think before the price drop, the ratio was between 10-12%, which is pretty good too.&amp;nbsp; &lt;/p&gt; &lt;p&gt;I can tell you that I did not become rich with this game, obviously.&amp;nbsp; The real reason was downloads.&amp;nbsp; If people downloaded the game, you were pretty certain that at least 1 in 10 would buy it.&amp;nbsp; If 100,000 people downloaded it, you’d make a decent amount ($30,000 - $50,000).&amp;nbsp; But I didn’t get download numbers like that.&amp;nbsp; I pretty much blame this on the fact that Indie games is not a great service if you want to get noticed.&amp;nbsp; There’s too many bad games and demos that squeeze out good titles.&amp;nbsp; Also, you have to think of the audience and I think a word game on a console is probably not optimal.&amp;nbsp; If your game wasn’t about farting or beer drinking, it would not make it to the top of the list.&amp;nbsp; If you got on the top downloaded or top rated lists, you were going to actually get noticed in the dashboard because of the promotion you received.&amp;nbsp; If you didn’t get in these lists (I was in the recent released list for about 1-2 weeks and then gone forever), you got buried in the dashboard.&amp;nbsp; Frankly, I’m surprised that any one finds it today (there’s still a few purchases a week).&amp;nbsp; I know I didn’t really market it too much, but how was I supposed to do that exactly?&lt;/p&gt; &lt;p&gt;I also could not translate the game to multiple languages (the fact that it is an English word game makes this doubly challenging than perhaps a simple shooter game).&amp;nbsp; I sold it in all XBox markets in the hopes that English speakers there would play it.&amp;nbsp; Foreign sales were pretty strong actually compared to what I thought.&lt;/p&gt; &lt;h2&gt;Sequel Plans&lt;/h2&gt; &lt;p&gt;I originally was very optimistic about a sequel even with low sales numbers.&amp;nbsp; I knew that I could take all of the money I made and the code/content I had and make a better sequel that would probably have made more money and taken less time to create.&amp;nbsp; But I lost interest.&lt;/p&gt; &lt;p&gt;I basically quit Indie Games because I felt that the peer review concept was not optimal.&amp;nbsp; In fact, I was pretty much correct as Microsoft has basically dumped the technology behind Indie Games (XNA) and has focused instead on DirectX 11 for Windows 8 and whatever XBox One has.&amp;nbsp; Their stance on Indie publishing on the XBox One makes it likely that Indie Games won’t even run on it let alone Game Studio being ported to it.&amp;nbsp; You could tell something was up when guys like Shawn Hargreaves started to leave the team.&lt;/p&gt; &lt;p&gt;I have a lot of design documents and ideas in my head for a sequel (including turning it into a turn-based game), but it will never happen with XNA, which is a real bummer to be honest.&amp;nbsp; I liked the platform and Game Studio was really cool.&lt;/p&gt; &lt;p&gt;I toyed with putting it on Windows Phone 7 for a while and even had a very small prototype but in the end, it just didn’t feel right on a phone (without major changes to its design) and WP7 has no users and so a very small market.&amp;nbsp; I could try iOS, but it’s flooded and I don’t like Apple and I’m not versed in any of their programming languages/platforms.&lt;/p&gt; &lt;p&gt;I think turning it into a HTML5 game would be interesting.&amp;nbsp; This type of game would be best for touch or mouse-clicking I think than using a controller.&amp;nbsp; But I’m pretty busy doing real paying work and being with family than doing this kind of thing.&lt;/p&gt; &lt;h2&gt;More to Come&lt;/h2&gt; &lt;p&gt;I’m planning on blogging about this game in more detail, especially with technical stuff like building directed acyclic word graphs (DAWGs), searching word graphs, building AIs that play games, character and RPG stats systems, etc.&lt;/p&gt;</description><pubDate>Fri, 12 Jul 2013 14:41:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/revisiting-war-of-words/</guid></item><item><title>RavenDB Survival Tip #2: Simulating select count(*)</title><link>http://timlabonne.com:80/2013/07/ravendb-survival-tip-2-simulating-select-count/</link><description>&lt;p&gt;A lot of the time a user will ask for a count of some business entity on a report so they can tell how many of something is happening.&amp;nbsp; With SQL, this is a very natural process with aggregate operations:&lt;/p&gt;&lt;pre class="brush: sql;"&gt;select count(*) from Users where IsAdmin = true
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;But with RavenDB, I found it difficult to wrap my mind around how you would do this with an Index.&amp;nbsp; Aggregate operations like this are implemented with map/reduce indexes.&amp;nbsp; Since the reduce step of the index needs to have the same output shape as the map, we can’t simply return a single numeric value as is the case with SELECT COUNT(*) in SQL.&amp;nbsp; We need to perform a LINQ group-by.&amp;nbsp; But in this case, I don’t really want to group by anything in a document, I just want a count.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;After a little thinking and digging around, I found a solution.&amp;nbsp; Maybe this is obvious to most, but I found that if we simply group by a constant, we can get a single numeric value for that constant the represents the total count.&lt;/p&gt;
&lt;p&gt;Here’s a sample Index definition that demonstrates this concept.&amp;nbsp; In the Index, I am trying to find all User documents that qualify as admins (IsAdmin = true).&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public class Users_AdminCounts : AbstractIndexCreationTask&amp;lt;User, Users_AdminCounts.ReduceResult&amp;gt;
{
    public class ReduceResult
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }

    public Users_AdminCounts()
    {
        // the Name parameter to the reduce function is dummy
        // to get it to aggregate to one single value
        Map = users =&amp;gt;
            from user in users
            where user.IsAdmin = true
            select new { Name = "Total", Count = 1 };

        Reduce = results =&amp;gt;
            from result in results
            group result by result.Name
            into g
            select new { Name = g.Key, Count = g.Sum(x =&amp;gt; x.Count) };
    }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;When you run the query and get the result (ReduceResult), you will get just one single result and the Count property will contain the count aggregate you are looking for.&lt;/p&gt;</description><pubDate>Wed, 10 Jul 2013 19:00:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/ravendb-survival-tip-2-simulating-select-count/</guid></item><item><title>Building a Dynamic Application Menu with Durandal.js, Knockout, and Bootstrap (Pt. 2)</title><link>http://timlabonne.com:80/2013/07/building-a-dynamic-application-menu-with-durandal-js-knockout-and-bootstrap-pt-2/</link><description>&lt;p&gt;In the previous post, I laid out a design for creating a dynamic menu system, specifically the object model that will be used in data binding.&amp;nbsp; In this post, we’ll look at the Knockout bindings and HTML structure to render the menus.&lt;/p&gt; &lt;p&gt;This will be pretty straightforward as far as taking our object model and applying markup to it, however, the one complicated part is dealing with sub-menus.&amp;nbsp; Because menu items can themselves contain other menu items, we need the ability to render a menu within a menu and so on.&amp;nbsp; We can do this with Durandal’s compose binding handler for KO.&amp;nbsp; It allows recursive composition that is perfect for hierarchical things like menus. &lt;/p&gt; &lt;p&gt;Here’s the contents of views/menu.html which is the view component for a single Menu rendering:&lt;/p&gt;&lt;pre class="brush: xml;"&gt;&amp;lt;ul class="dropdown-menu" data-bind="foreach: items"&amp;gt;
    &amp;lt;!-- ko if: $data.text !== undefined --&amp;gt;
    &amp;lt;li data-bind="css: { disabled: !command.canExecute(), 'dropdown-submenu': hasSubMenu }"&amp;gt;
        &amp;lt;!-- ko ifnot: $data.hasSubMenu --&amp;gt;
        &amp;lt;a href="#" tabindex="-1" data-bind="command: command"&amp;gt;
            &amp;lt;span data-bind="text: text"&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;/a&amp;gt;
        &amp;lt;!-- /ko --&amp;gt;
        &amp;lt;!-- ko if: $data.hasSubMenu --&amp;gt;
        &amp;lt;a tabindex="-1" data-bind="text: text"&amp;gt;&amp;lt;/a&amp;gt;
            &amp;lt;!-- ko compose: { view: 'views/menu.html', model: $data } --&amp;gt;
            &amp;lt;!-- /ko --&amp;gt;
        &amp;lt;!-- /ko --&amp;gt;
    &amp;lt;/li&amp;gt;
    &amp;lt;!-- /ko --&amp;gt;
    &amp;lt;!-- ko if: $data.divider !== undefined --&amp;gt;
    &amp;lt;li class="divider"&amp;gt;&amp;lt;/li&amp;gt;
    &amp;lt;!-- /ko --&amp;gt;
&amp;lt;/ul&amp;gt;
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This markup is a bit complicated so let’s go through it:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;In Bootstrap, applying the dropdown-menu class to a &amp;lt;ul&amp;gt; will style it as a drop down menu container.&amp;nbsp; The data-bind here is also set to loop over each item in the Menu object.&lt;/li&gt;
&lt;li&gt;Within the &amp;lt;ul&amp;gt;, we need to decide if the MenuItem is a text-based menu item or a divider.&amp;nbsp; We do this by detecting if the divider property exists and/or there is text to display.&amp;nbsp; If the MenuItem is a divider, the special divider class is applied to a &amp;lt;li&amp;gt; and Bootstrap renders it as a thin gray line.&lt;/li&gt;
&lt;li&gt;If the MenuItem is actually a text-based item, we style it appropriately in its &amp;lt;li&amp;gt; element.&amp;nbsp; Notice the binding to command.canExecute().&amp;nbsp; In KoLite, if you provide a canExecute() function on a command (with is a computed observable), it can determine if the command can be executed or not.&amp;nbsp; In this case, we want the UI to gray-out or disable if the command cannot execute.&amp;nbsp; Once the command can execute, it will immediately synchronize the UI element to be a clickable command.&lt;/li&gt;
&lt;li&gt;Inside the &amp;lt;li&amp;gt;, we check to see if the MenuItem is a sub-menu or not.&amp;nbsp; If it is not, we create an &amp;lt;a&amp;gt; element as desired by Bootstrap to create the link to click on, binding the appropriate command to it.&amp;nbsp; We also bind the text in a &amp;lt;span&amp;gt; element inside the &amp;lt;a&amp;gt;.&lt;/li&gt;
&lt;li&gt;If the MenuItem does have a sub-menu, we assume that the MenuItem can’t be clickable, but instead, simply groups other elements.&amp;nbsp; In that case, we call upon the Durandal compose binding handler to recursively call this view sending the MenuItem as the view model to bind to in that context.&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;Now, to render the top-level menu bar, in our main view we’d add the following markup (I’m using nav-pills in Bootstrap to represent the top-level menu items, but you don’t need to do that):&lt;/p&gt;&lt;pre class="brush: xml;"&gt;&amp;lt;ul class="nav nav-pills menu-bar" data-bind="foreach: menus"&amp;gt;
    &amp;lt;li class="dropdown"&amp;gt;
        &amp;lt;a class="dropdown-toggle" href="#" data-toggle="dropdown" role="button" data-bind="text: text"&amp;gt;&amp;lt;/a&amp;gt;
        &amp;lt;!-- ko compose: { view: 'views/menu.html', model: $data } --&amp;gt;
        &amp;lt;!-- /ko --&amp;gt;
    &amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;
&lt;/pre&gt;
&lt;p&gt;This assumes that the view model for the main view has a collection of Menu objects in an observableArray called menus.&lt;/p&gt;
&lt;p&gt;It renders a &amp;lt;li&amp;gt; element for each Menu giving it a dropdown class.&amp;nbsp; The &amp;lt;a&amp;gt; element will trigger Bootstrap to open the &amp;lt;ul&amp;gt; element that immediately follows the &amp;lt;a&amp;gt;.&amp;nbsp; That &amp;lt;ul&amp;gt; is generated by a compose binding calling onto the Menu view to render that one Menu and all of its children recursively.&lt;/p&gt;</description><pubDate>Wed, 10 Jul 2013 18:44:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/building-a-dynamic-application-menu-with-durandal-js-knockout-and-bootstrap-pt-2/</guid></item><item><title>Building a Dynamic Application Menu with Durandal.js, Knockout, and Bootstrap (Pt. 1)</title><link>http://timlabonne.com:80/2013/07/building-a-dynamic-application-menu-with-durandal-js-knockout-and-bootstrap-pt-1/</link><description>&lt;p&gt;I’m going to do a longer series here about how to create a dynamic menu bar system with &lt;a href="http://durandaljs.org"&gt;Durandal&lt;/a&gt;, &lt;a href="http://knockoutjs.com"&gt;Knockout&lt;/a&gt;, and Twitter Bootstrap.&amp;nbsp; This menu bar is going to emulate the traditional desktop application menu bar you find in apps (like the File, Edit, or View menus, for example).&amp;nbsp; The special thing here is that it will be 100% dynamic.&amp;nbsp; This will allow interesting scenarios such as dynamically altering the application menu when the application is in a different mode or allow something like plug-ins to alter the menu structure adding new commands.&lt;/p&gt; &lt;p&gt;We will use the following libraries/frameworks to perform this task:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;We’ll use Bootstrap to style the menus and get basic drop down menu support.&amp;nbsp; The menus in Bootstrap look very pretty and work very well using just one .js file for behavior and a little bit of markup.&lt;/li&gt; &lt;li&gt;We’ll use Durandal to structure the application and to take advantage of the composition engine it has.&amp;nbsp; I assume you know how to get a basic Durandal project up and running so I’m not going to spend a lot of time discussing how Durandal works.&lt;/li&gt; &lt;li&gt;We’ll use Knockout to do all of the data binding.&amp;nbsp; Our menu items will have observable properties in them so that menus will dynamically change when you change things about them in code.&lt;/li&gt; &lt;li&gt;We’ll also make use of &lt;a href="https://github.com/CodeSeven/kolite"&gt;KoLite&lt;/a&gt; by John Papa which provides a simple KO extension (the command) to abstract the idea of a UI command.&amp;nbsp; A single menu item will wrap a ko.command().&amp;nbsp; If a command does not allow execution, the corresponding menu item(s) will not allow it and will appear disabled.&amp;nbsp; Also, when clicking on a menu item, the command will execute.&amp;nbsp; This will all happen through data binding and will not &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;For this first part, let’s build the JavaScript object model for the menu system.&amp;nbsp; A Menu object (defined in ui/menu.js in my project) represents one menu on a menu bar (such as a File menu).&amp;nbsp; It will contain zero or more MenuItems which are the individual menu selections in the menu.&amp;nbsp; There is also a special menu item that acts as a divider or separator.&amp;nbsp; These dividers draw thin lines between menu items to help visually group commands.&amp;nbsp; They are not clickable.&lt;/p&gt; &lt;p&gt;Here’s the code for the MenuItem class (defined in ui/menuItem.js as a Durandal module):&lt;/p&gt;&lt;pre class="brush: js;"&gt;define(function (require) {
    var MenuItem = function (itemText, command, items) {
        this.text = ko.observable(itemText);
        this.command = command || ko.command({ execute: function () { } });
        this.items = ko.observableArray(items || []);
        this.hasSubMenu = ko.computed(function () {
            return this.items().length &amp;gt; 0;
        }, this);
    };

    MenuItem.prototype.addMenuItem = function (menuItem, position) {
        if (position) {
            this.items.splice(position, 0, menuItem);
        }
        else {
            this.items.push(menuItem);
        }
    };

    MenuItem.prototype.addDivider = function (position) {
        var item = { divider: true };
        if (position) {
            this.items.splice(position, 0, item);
        }
        else {
            this.items.push(item);
        }
    };

    return MenuItem;
});
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;A menu item takes a menu item text (the text to appear in the menu), an optional KoLite command, and an optional set of child sub-items.&amp;nbsp; The sub-items are used for when the menu item is actually a menu within a menu and will be rendered with a an arrow to the right of the menu item using Bootstrap.&lt;/p&gt;
&lt;p&gt;A Menu class also exists as a top-level container for MenuItems.&amp;nbsp; Think of this as the File menu or Edit menu.&amp;nbsp; It is defined in ui/menu.js as a Durandal module:&lt;/p&gt;&lt;pre class="brush: js;"&gt;define(function (require) {
    var MenuItem = require('ui/menuItem');

    var Menu = function (text, items) {
        this.text = ko.observable(text);
        this.items = ko.observableArray(items || []);
    };

    Menu.prototype.addMenuItem = function (menuItem, position) {
        if (position) {
            this.items.splice(position, 0, menuItem);
        }
        else {
            this.items.push(menuItem);
        }

        return menuItem;
    };

    return Menu;
});
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This class takes the text of the menu item (“File”) and the collection of MenuItems to add to the menu.&amp;nbsp; You can call addMenuItem() to add a menu item after the initial creation of the menu.&amp;nbsp; The position parameter will add the menu in the specified position.&amp;nbsp; If you don’t specify a position, it will be added to the end of the menu.&lt;/p&gt;
&lt;p&gt;In the next part of the series, we’ll look at the HTML and KO data-bindings that will render the menus.&lt;/p&gt;</description><pubDate>Wed, 10 Jul 2013 18:19:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/building-a-dynamic-application-menu-with-durandal-js-knockout-and-bootstrap-pt-1/</guid></item><item><title>Tree Traversals with JavaScript</title><link>http://timlabonne.com:80/2013/07/tree-traversals-with-javascript/</link><description>&lt;p&gt;Let’s do this one more time – this time with JS.&amp;nbsp; Here is a constructor function for a generic tree node that has one parent and possibly N children:&lt;/p&gt;&lt;pre class="brush: js;"&gt;var TreeNode = function (data) {
    this.parent = data.parent || null;
    this.children = data.children || [];
};

TreeNode.prototype.isLeaf = function () {
    return this.children.length == 0;
};

TreeNode.prototype.isRoot = function () {
    return this.parent == null;
};
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here is how we’d traverse the tree with a depth-first search (note that I’m using the &lt;a href="http://underscorejs.org"&gt;underscore.js&lt;/a&gt; library for the each() function – you could also use ES5’s Array.forEach() if you do not want to support older browsers – or use a polyfill):&lt;/p&gt;&lt;pre class="brush: js;"&gt;function visitDfs(node, func) {
    if (func) {
        func(node);
    }

    _.each(node.children, function (child) {
        visitDfs(child, func);
    });
}&lt;/pre&gt;
&lt;p&gt;Doing a breadth-first traversal is also straightforward thanks to JavaScript’s Array class and its queue/stack-like functionality:&lt;/p&gt;&lt;pre class="brush: js;"&gt;function visitBfs(node, func) {
    var q = [node];
    while (q.length &amp;gt; 0) {
        node = q.shift();
        if (func) {
            func(node);
        }

        _.each(node.children, function (child) {
            q.push(child);
        });
    }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Finally, let’s do something tangible with a depth-first traversal.&amp;nbsp; In the next code snippet, the prune() function will prune out nodes that are single children to their parents in order to collapse the tree into a simpler structure.&amp;nbsp; This will eliminate groupings of nodes that aren’t really grouping anything because their branching factor is 1:&lt;/p&gt;&lt;pre class="brush: js;"&gt;function prune(root) {
    visitDfs(root, function (node) {
        if (node.isRoot()) {
            return; // do not process roots
        }
        if (node.children.length == 1 &amp;amp;&amp;amp; !node.children[0].isLeaf()) {
            var child = node.children[0],
                index = _.indexOf(node.parent.children, node);
            node.parent.children[index] = child;
            child.parent = node.parent;
        }
    });
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This code works by doing a DFS and calling a function on each node.&amp;nbsp; That function examines the node to see if it has exactly one child and that the one child node is not a leaf (we don’t want to prune out leaves or roots).&amp;nbsp; If it is, the child node is extracted out and assigned to the node’s parent’s children and then the child’s parent is reassigned to the node’s parent.&amp;nbsp; This effectively eliminates (prunes) the node out of the tree collapsing it into a simpler structure.&lt;/p&gt;</description><pubDate>Wed, 03 Jul 2013 12:36:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/tree-traversals-with-javascript/</guid></item><item><title>Another Technique for Tree Traversals</title><link>http://timlabonne.com:80/2013/07/another-technique-for-tree-traversals/</link><description>&lt;p&gt;In the previous post, I talked about doing a DFS on a rooted tree using the C# foreach loop/iterator concept.&amp;nbsp; In this post, I will discuss a different technique that is more function-based.&lt;/p&gt; &lt;p&gt;A common task on a tree is to traverse it in some defined order – pre-order, level-order, post-order, etc.&amp;nbsp; When we visit a node, we’d like to perform some action on it.&amp;nbsp; We can use delegates in C# (reference to a function) and lambdas to make this really compact and elegant:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public static void VisitDfs(TreeNode node, Action&amp;lt;TreeNode&amp;gt; func)
{
    if (func != null)
        func(node);
    foreach (TreeNode child in Children)
    {
        VisitDfs(child, func);
    }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If you pass in the root node to this method, you can call the function you send in on each node in that order.&amp;nbsp; You can apply this concept for other traversal patterns too:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public static void VisitBfs(TreeNode node, Action&amp;lt;TreeNode&amp;gt; func)
{
    Queue&amp;lt;TreeNode&amp;gt; q = new Queue&amp;lt;TreeNode&amp;gt;();
    q.Enqueue(node);
    while (q.Count &amp;gt; 0) 
    {
        node = q.Dequeue();
        if (func != null)
            func(node);
        foreach (TreeNode child in Children)
        {
            q.Enqueue(child);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This performs a breadth-first traversal (also called a ‘level order’ traversal with trees), calling the specified function at each node visit.&lt;/p&gt;
&lt;p&gt;Here’s a sample usage of the DFS to count the number of leaves in a tree:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public static int CountLeaves(TreeNode root)
{
    int leafCount = 0;
    VisitDfs(root, node =&amp;gt; {
        if (node.Children.Count == 0) {
            leafCount++;
        }
    });

    return leafCount;
}
&lt;/pre&gt;</description><pubDate>Tue, 02 Jul 2013 14:28:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/another-technique-for-tree-traversals/</guid></item><item><title>Performing a DFS over a Rooted Tree with a C# foreach Loop</title><link>http://timlabonne.com:80/2013/07/performing-a-dfs-over-a-rooted-tree-with-a-c-foreach-loop/</link><description>&lt;div id="codeSnippetWrapper"&gt;I’ve been working with trees a lot lately and one thing that occurs quite frequently in my problem space is the action of performing a depth-first search (DFS) or a 'pre-order traversal’.&amp;nbsp; In a DFS, you visit the root first and then search deeper into the tree visiting each node and then the node’s children.&lt;/div&gt; &lt;div&gt;&amp;nbsp;&lt;/div&gt; &lt;p&gt;Since this is so common, I’d like a routine that helps me do that very simply.&amp;nbsp; What I’d really like to do is simply do a foreach loop over the tree and with each iteration pull out the next node that would satisfy a DFS.&amp;nbsp; This is where the C# yield keyword comes into play.&lt;/p&gt; &lt;p&gt;The following snippet presents a TreeNode class which is just a generic node in a tree that has N children:&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;public class TreeNode
{
    public TreeNode()
    {
        Children = new List&amp;lt;TreeNode&amp;gt;();
    }

    public TreeNode Parent { get; set; }
    public List&amp;lt;TreeNode&amp;gt; Children { get; private set; }
    public bool IsLeaf { get { return Children.Count == 0; } }
    public bool IsRoot { get { return Parent == null; } }

    public IEnumerator&amp;lt;TreeNode&amp;gt; GetEnumerator()
    {
        yield return this;
        foreach (TreeNode child in Children)
        {
            IEnumerator&amp;lt;TreeNode&amp;gt; childEnumerator = child.GetEnumerator();
            while (childEnumerator.MoveNext())
                yield return childEnumerator.Current;
        }
    }
}
&lt;/pre&gt;
&lt;div&gt;&lt;br&gt;&amp;nbsp;&lt;/div&gt;
&lt;p&gt;Most of the functionality is in the GetEnumerator() method.&amp;nbsp; When a class in C# has a method called GetEnumerator() that returns a type IEnumerator or IEnumerator&amp;lt;T&amp;gt;, you’ll be able to use that type in a foreach loop.&amp;nbsp; Also notice that the type returned by my method does not return IEnumerator&amp;lt;TreeNode&amp;gt; but rather just TreeNode.&amp;nbsp; The C# compiler will fill in the proper details automatically.&lt;/p&gt;
&lt;p&gt;In order to do a DFS, we first visit the node itself by returning it (this) in a yield statement.&amp;nbsp; When the iterator executes the next loop, the GetEnumerator() method remembers the execution state of the method and picks up right where it left off.&amp;nbsp; At that point, we enter into a loop over the Children collection.&amp;nbsp; We basically repeat the enumerator process over this collection manually by doing a while loop where we exit the loop if no more children exist.&amp;nbsp; In the body of this while loop, we execute another return within a yield, returning each child node.&lt;/p&gt;
&lt;p&gt;To use this enumerator to perform a DFS, you’d foreach over the root node of your tree (I’m assuming a singly rooted-tree here):&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;foreach (TreeNode node in root)
{
  // perform action on node in DFS order here
}
&lt;/pre&gt;</description><pubDate>Tue, 02 Jul 2013 13:28:00 GMT</pubDate><guid isPermaLink="true">http://timlabonne.com:80/2013/07/performing-a-dfs-over-a-rooted-tree-with-a-c-foreach-loop/</guid></item></channel></rss>