Pirates, Ninjas, and C++

Last night, in the C++ course that I teach at a local community college, we worked through a code sample that was a little more interesting than what I’ve done in past semesters.  I like choosing fun examples (i.e. class SushiChef : Person) and generally see good results- the class is engaged in conversation and the code and most students end up learning something new.  Yesterday I decided to try a new example and it went so well that I thought I’d post it here.

The course is more of an introduction to Object Oriented Programming than a strict C++ syntax seminar.  The three big tenants of OOP that we learn in this course are encapsulation, inheritance, and polymorphism.  In my day there was a fourth: data-hiding.  But it’s whatever.  We’re very early in the semester right now so the class is still coming to grips with encapsulation.

To demonstrate a decent use of encapsulation, which is the aggregation of multiple pieces of data and even behaviors into a single entity or “class,” while also showing how encapsulated ideas can work together, I usually set up a Request-Processor-Response pattern of sorts.  One boring example that I did one was a BankAccount (request) gets passed to an AccountValidator.Validate method (processor) and hands back a ValidationResult (response).  Once I did a SushiOrder getting passed to a SushiChef.Prepare method and returning a SushiPlate.  I think you get the idea.

Well the new idea I wanted to try, in the interest of garnering more class engagement, was a Pirates Vs. Ninjas theme.  The idea is that Pirates are bad, and we want to kill them.  We do this by hiring their natural enemy, Ninjas, to destroy them.  And we gauge the resulting attack with a FightResult object.

To explicitly conform to our pattern of Request-Processor-Response, we are saying that:

  • Request = Pirate
  • Processor = Ninja
  • Result = FightResult

There is something fun about the idea of a processor being a Ninja.

Anyway, to keep things simple, we decided that both the Pirate and the Ninja classes should each contain a SkillLevel (int) and that conflict is resolved by checking if the Ninja’s skill level is equal-to or greater-than the target Pirate’s SkillLevel.

I had already decided on throwing a fun wrench into this equation later on by having an IsTurtle property on the Ninja, since we do have 4 precedents of ninjas being turtles, and that any Ninja that IsTurtle will get a 5 point boost on his/her skill level when fighting a pirate.

That was really the only spin I put on the thing, and with hardly any prompting my students came up with some wonderful ideas for extending the example.  Some of them we added to the code, but most we didn’t.  The reason being is that I would like for them to download the source that I wrote last night and implement their ideas.

Before I even had a chance to get to my IsTurtle idea, one of my students raised his hand with the very same notion!  Another student said that the Pirate class should have a boolean for IsDrunk, and I think that might be my favorite line of code I’ve ever written.  Another student wanted to add a boolean HasParrot to the pirate.  Yet another student wanted the Ninja to have a WasSeen flag, which brings up the idea of having style points factor into the equation.  And yet another student had the brilliant idea the if the Pirate.HasParrot then the Ninja.WasSeen!  And if the Ninja is detected then the Pirate gets an advantage- that is one handy parrot!

Again, the code that I demonstrated is very simple and only really the starting point for a much more deep and complex example.  This is deliberate, so that the students (and yourself!) can download it and start tinkering and extending it.  One student pointed out that we had practically come up with a Pokemon game and I hope he takes the code in that direction and finishes it!

So, let’s take a look at the code!  All of this is compiled using Visual Studio 2010, as a 32-bit console app.

First up, here is our Pirate class- this is only the .h file.  The corresponding implementation (.cpp) file is unnecessary as all funtionality here is inline:

#pragma once
#include <string>

using namespace std;

class Pirate
{
public:

    string Name;
    int SkillLevel;
    string Weapon;
    bool IsDrunk;
    bool HasParrot;

    Pirate() { Name = "Black Beard"; SkillLevel = 5; Weapon = "Musket"; IsDrunk = true; HasParrot = true; }
    ~Pirate(void);
};

Next up is our FightResult class- again, all that is needed is the .h file:

#pragma once
#include <string>

using namespace std;

class FightResult
{
public:

    bool Success;
    string Message;

    FightResult(void) { Success = false; Message = ""; }
    ~FightResult(void);
};

Now let’s take a look at the Ninja class, both the .h file and the relevant piece of the .cpp are presented here:

#pragma once
#include <string>
#include "FightResult.h"
#include "Pirate.h"

using namespace std;

class Ninja
{
public:

    int SkillLevel;
    string Weapon;
    float HitFee;
    bool WasSeen;
    bool IsTurtle;

    FightResult Attack(Pirate p);

    Ninja(void) { SkillLevel = 5; Weapon = "Katana"; HitFee = 200.0; WasSeen = false; IsTurtle = false;}
    ~Ninja(void);
};

FightResult Ninja::Attack(Pirate p)
{
    FightResult result;

    int bonus = 0;
    if(IsTurtle)
    {
        bonus = 5;
    }

    if((bonus + SkillLevel) >= p.SkillLevel)
    {
        result.Success = true;
        result.Message = "The Ninja we hired successfully destroyed " + p.Name + " with his " + Weapon + "!";
    }
    else
    {
        result.Success = false;
        result.Message = p.Name + " has killed the Ninja we hired!  Yaarrrrrr!";
    }

    return result;
}

Here is a sample of the test main that we wrote to put these classes to work:

#include "stdafx.h"

#include <iostream>

#include "Ninja.h"

#include "Pirate.h"

#include "FightResult.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

    Pirate pete;

    pete.Name = "Pete";

    pete.IsDrunk = true;

    pete.HasParrot = true;

    pete.SkillLevel = 7;

   
    Ninja leonardo;

    leonardo.IsTurtle = true;

   
    FightResult result;

    result = leonardo.Attack(pete);

    cout << result.Message << endl;

    system("pause");

    return 0;

}

And that’s it!  It’s not fancy, but its some straight-forward, basic OOP.  I’ve never seen my class so energized and alive and willing to participate in a code example!

A Year of Launching Later

A Year ago today I released my LaunchLater project into the wild as open source software.  This has been one of the most fun adventures in my career as a software developer.

Since its initial launch, it has gone through several versions.  There have been bug fixes, new features, and improved user interface design.  It has been mentioned on blogs in the U.S., Russia, Brazil, Italy, Slovakia, Japan, Turkey, and even shown up in a video blog from Spain.

It has included code written by one of my coworkers, who added one of my most desired features to the app: the ability to import existing Windows startup items.  Another coworker has forked the project to play with his own ideas of where the app could go.

The app itself has been downloaded over 4,500 times as of this writing, and its source code has been downloaded by over 70 developers.

I’ve gotten to receive and respond to feedback via Twitter, blog comments, Reddit, messages over Codeplex, and conversations with friends and coworkers.

Most importantly though- it does its job well for me.  My Windows-based computers boot faster because of it, and I love that.

Happy Birthday, LaunchLater!

I’m So Happy You Found A Bug In My Code

Over the weekend I had a POSITIVE EXPERIENCE AS A PROGRAMMER.  So positive that it put me in a chipper mood all weekend- so chipper in fact that several days later I’m still using words like “chipper.”  What could have happened to make me so happy?  Someone told me that I had a bug in my code.

Last year I released the open source application LaunchLater.  You might have heard me blog/tweet/facebook/yell about it.  It has collected over 3800 downloads as of the time of this writing, though I haven’t received a lot of feedback.

The feedback I have received has come in a handful of forms.  First there has been the immediate feedback of friends and coworkers who have used it.  That has been infinitely helpful.  Second, I gave a talk on it at a local .Net User Group meeting last fall and got some wonderful questions and suggestions.  Third, every few weeks or so a blogger or tech site picks up on LaunchLater and decides to put up a post about it.  Sometimes they will leave comments open and I get to see what people are saying about my software on their site.  That has actually led to a couple of current features in the app.

But the feedback I had never received until last Friday was direct feedback from a stranger right on the Codeplex page itself, under the Discussions tab.  A gentleman left me a message to say that so far the app is useless to him, due to a bug that prevents it from launching.  He provided me an error message that had some vague details, and he informed me of his OS and architecture type.   This was a WONDERFUL start.  I wrote back, thanking him for notifying me, and asking him for more info from his Event Log.  He got the info to me in a timely fashion, and by Saturday I had patched the code and provided him with a custom build.  Through further communication he confirmed for me that the bug was squashed, so I released LaunchLater 2.1 to the public!

He further explained why he is using LaunchLater, so that he can more precisely control the execution of the XBMC software on his media center PC.  I’ve never heard from anyone else using the app for that purpose so it was great to hear that my software helped him engineer a better user experience.

The full conversation is open for all to read on the site here.

I have no way to know right now how many others, of those 3800+ downloads, were users who experienced the same issue as this gentleman and simply uninstalled the app and didn’t say a word to me about it.  Maybe none of them, who knows.  But since this one user let me know about it, no one else will experience this bug.

The moral of this story is: when you have feedback for an open source developer, give it to them!  You just might make them so happy that they blog about it!

Suck it, Apple! I’m goin Android!

I grew up playing with PC’s- building them, writing text adventures in QBasic, knowing DOS well enough to remove the “win” line from my autoexec.bat, and customizing boot disks for every game I owned.  That was all at home, where my real education was happening.  Meanwhile, while I was at school, I was reduced to working on nothing but Macs.  I’m normally pretty good about separating the notion of “I’m not used to this yet” from “I don’t like this.”  But it didn’t take long for me to decide that I hated Macs, and therefore Apple as well.  Being all presumptuous and removing the floppy drive, building the monitor into the tower so it’s just one unit, hard to upgrade any single piece without replacing the whole thing (back then anyway).  Hatred doesn’t begin to describe how I felt about Apple.

They’ve changed though.  Thank god.  I recognize that their OS is just based on top of BSD.  And the company itself rests firmly on top of its iPod, iPhone, and iPad lines rather than its computers.  So two years ago, when I deemed it time to get a smart phone, I bought an iPhone.  I even wrote about it, here.  At the time of purchase, it was THE smart phone to own.  There wasn’t another competitor that offered anything even close.  But that’s changed now.

For two years I carried that phone- eventually jailbroke it.  I swallowed a lot of pride the day I bought it, and last Thursday, I spit that pride right back out.  Damn, that felt good.

I bought a Motorola Atrix 4G.  It’s AT&T’s top of the line Android-based phone as of the time of this writing.  It’s the first (and time will tell if it is the only) phone to dock with a laptop-shell and launch into a webtop OS that runs full Firefox.  It’s dual core, has a gig of ram, and it knows the last digit of pi. 

Why do I like it better than the iPhone?  Besides the power itself:

  • It can run Flash, which means I can read Shacknews AND watch the videos.
  • I can develop for it FROM ANY OPERATING SYSTEM using Java, a language I already know, as opposed to buying a Mac and learning Objective C.
  • I can download and install apps that aren’t necessarily in the app store, legally and without jailbreaking.
  • Google makes free apps that I like better than the free apps on the iPhone- like Google Goggles and Google Sky.
  • I can browse the file system of the phone without jailbreaking.
  • I can use widgets all over the place, and even code new ones, without jailbreaking.
  • There are console emulators in the freaking app store.

There are more, but I feel like I’ve established my point. 

Over the weekend, I picked up this book on Android development, and I’ve already started development on a little app to help manage Codeplex-based open source projects.  More to come on that.

I can’t wait to see what I can do next on Android.  Whatever it is, I bet it’ll be really easy and won’t require any jailbreaking.

LaunchLater 2.0 Released

That’s right- finally released the new LaunchLater!

This release embodies my original vision of what the application should be.  With help from partner programmer Jabrown85, you can now import your existing Windows startup applications directly into LaunchLater.  This makes initial configuration a cinch for any user.  image

A few aesthetic improvements have been made, including a new LaunchLater icon inspired by some graphics work that my wife put together for me.  She’s awesome.

image

So, if you’re looking to optimize your Windows experience, grab a copy of LaunchLater and plot a better boot process.

Java’s Awesome Anonymous Inner Class

My day job has recently forced me to rejoin the Java world.  I prefer C# for many reasons (LINQ!) but I like Java well enough and it’s fun to get all nerdy in a language I don’t spend much time in traditionally.  On the side, I decided to keep the nerdness going with a foray into Android development.  Let it be known: I don’t own an Android device, but I hope to soon.

While I was working on setting up a button in my UI, I googled for some code on setting up the click event-handler.  What I found was this gem:

viewClockButton.setOnClickListener(new OnClickListener() {
            @Override 
            public void onClick(View v) {
                //do something cool 
            }
        });

What we have here is a smooth use of a handy Java feature, combined with some syntactical coolness.  First off, on the button object, we call the setOnClickListener() method which accepts a parameter of any type that implements the OnClickListener interface.  I have already defined a class of the same name with this code:

public class OnClickListener implements android.view.View.OnClickListener {

    public void onClick(View arg0) {

        // TODO Auto-generated method stub

   
}

}

In the original call to setOnClickListener(), I instantiate a new object of type OnClickListener, but then I do something special.  I open up squiggly braces and then override the onClick() method with custom behavior just for this button’s click event.

What this looks like: It looks like I’m creating a new object, and then dynamically injecting custom behavior into one of it’s methods, so that THIS instance of class OnClickListener will have different behavior from other instances.  This is somewhat common in dynamic languages like Ruby and Javascript.

What is actually happening:  When I open the squiggly brace after instantiating the object, I’m actually creating a new anonymous inner class, which inherits from OnClickListener, and then overrides the behavior of the onClick() method.

This is pretty cool.  I would love to be able to use similar syntax to pull off this type of thing in C#, but then again in C# I have full access to lambdas, delegates, Func<>’s, and all sorts of ways to achieve the same ultimate desired behavior.  Still, I can’t help but like this, both for it’s syntax and it’s under-the-hood power.

Original source: http://www.connorgarvey.com/blog/?p=93

Converting a Nullable Type to a Byte Array in C# .Net

This past week I found myself in need of retrieving a byte array (byte[]) representation of a nullable long (long?) in C#. I was trying to serialize an anchor being passed around by MS Sync Framework and we’d chosen long ago to use long?’s to accomplish our anchoring.

When converting any primitive type to a byte array, you can easily make use of the System.BitConverter class.  It’s pretty great, really.  But for non-primitives, which includes nullable versions of primitives, you must get a little more technical in your approach.

The following code worked for me:

   1: long? l = 84839; 

   2:  

   3: System.IO.MemoryStream mem = new System.IO.MemoryStream(); 

   4: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = 

   5:     new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 

   6:          

   7: formatter.Serialize(mem, l);

   8:  

   9: byte[] bytes = mem.ToArray();

  10:  

Basically, you create a memory stream and a binary formatter, then pass your object to the stream and ask the formatter to serialize it.  Calling the ToArray() method at the end will return you a nice, crisp byte array of your object, which you can pretty much do anything with.

Happy coding!

A Nifty Build Version Incrementer for Visual Studio

Need a quick and simple way to auto-increment builds of assemblies in Visual Studio 2005, 2008, or 2010?  Try this.

While working on my LaunchLater project’s installer application, I ran into trouble with an installer not necessarily updating the app to the new version.  Even though I had configured the project where RemovePreviousVersions was set to true, it would compare more than just the product version of the installer, it would compare each assembly and only update if the assembly had a newer version number.

Visual Studio, despite its clear superiority over other IDE’s, still does not have the capability to auto-increment assembly versions.  Fortunately, the open source project linked to here, known as Build Version Increment Add-in Visual Studio, works excellently.

I configured every assembly in my project to auto increment such that the major and minor versions wouldn’t change, but the 3rd and 4th designated version place holders would.  The 3rd position would increment by 1’s and the 4th would be a timestamp.  This allows for versions to go from 1.2.4.3839 to 1.2.5.9928.  This also allowed my installer to always update previous installs correctly, since the newly built assemblies are versioned accordingly and automatically.

Many thanks to the devs on the project!

Want to Earn A Nerd Merit Badge?

Have you ever heard of Nerd Merit Badges?  If have haven’t I highly recommend checking out their site.

The first badge they ever produced and sold was the Open Source badge.  It is earned by making an accepted commit to any open source software project, and subsequently purchasing it for a sum of $5.99 plus shipping.

With my recent release of LaunchLater, I fulfilled the first half of these requirements.  So I bought myself one!  It’s pretty great!  It’s so great, in fact, that I bought a second one!  See?

opensourcebadge

Why did I buy a second one?  Well, in all honesty, I bought it for you!

That is, assuming that you, the current reader, is the person who is first to download the LaunchLater source code and add a feature or bug fix!

You read correctly:  if you go download the source at http://launchlater.codeplex.com/ and make a productive change, I will give you this badge!  You don’t even have to pay $5.99 or shipping!

The badge itself is Velcro-backed and has an image of the Github mascot, Octocat.  Pretty stylin’, if I do say so myself.

Please contact me if you are interested in being added as a registered developer within the CodePlex LaunchLater project.

Thanks, and good luck!

LaunchLater Has Officially Launched

My previous blog post, written just over a month ago, described the idea that I had for an open source handy little Windows tool.  I named it LaunchLater and I had hoped to deliver a beta within two weeks.  I missed my two week window, by almost three weeks, but tonight I can proudly say that Version 1.0 is ready.

It has a long way to go.  There are one or two known bugs.  I don’t have any custom graphics or icons done yet.  I have some skeleton code in place for several features that don’t yet exist.  It has dependencies that could potentially be factored out.

But it works.

At least within the initial scope of the application, it works.  As described in my previous post, it allows you to create a schedule of apps to defer execution of at startup.  The app that has been my prime candidate for deferred launch is Dropbox and by deferring its launch my laptop boots much faster.  And I know that my hard disk is allowed to get the boot process out of the way before starting that index.

Application Overview

LaunchLater consists of two executables.  The first is the process that actually interprets the schedule of apps to run at login.  I call this app the LaunchPad.  Its user interface is currently nothing more than an icon in the notification area that messages you when it is launching another app.

The second app is the configuration tool (pictured below).  It allows you to add, edit, and remove applications from the launch schedule.  All of the LaunchLater code is written in C# 4.0, but this app is specifically written using Windows Presentation Foundation 4.0 (WPF).  The reason I chose WPF is that it allows for a much more graphically enhanced user experience.  If you’ve never experienced WPF or Silverlight, I suggest looking into it.  It is sort of like all of the pretty good ideas behind web development coupled with the fun of managed .Net code.  My only real problem with it is its reliance on eXtensible Application Markup Language (XAML), simply because I hate all things that look like XML.  Once you dig into it though, it’s not that bad, and Visual Studio 2010 (along with the Community Preview of Blend 4) does a lot of the heavy lifting for you.

LLManagerLLManager2

I have made the application installer along with all source code available on CodePlex (http://launchlater.codeplex.com).  It is released under the GNU General Public License.  I have put a lot more time and thought into my decision on software licensing than I expected to, and to my surprise it has been quite interesting.

Licensing (A Moral Quandary)

This license appealed to me for two reasons.  The first is simple: it grants everyone in the world the right to download, use, modify, and redistribute my software at no cost.  Open source software has saved my neck many times and I feel wonderful about releasing my own. 

The second reason is a bit more complicated.  There is a difference between general free software and what is referred to as “copyleft”ed software.  If my code were completely free, it would allow someone to develop a spin off of the application, and then sell it for potentially millions of dollars (I flatter myself to dream that this application could be worth as much).  I really don’t feel that I have a problem with this.  If someone finds a way to make money off of this, I honestly respond with, “more power to you, sir!”  That person clearly took the time and effort to put a business plan behind my code, and I haven’t.  Not with this software anyway.

But copyleft prevents users from doing this.  It restricts all future child applications of this app to use the exact same license, ensuring that every derivative application is also free to use, modify, and redistribute.

This is quite a moral dilemma.  On the one hand, I don’t want to limit anyone’s freedoms, include that of profiting off a modified version of my code.  On the other hand, by ensuring that future versions of the software are free I am benefiting the community by making sure that software is available to everyone.

I settled on the latter.  Copyleft benefits everyone, where as allowing a future copyright, even with credit to me in the license, only benefits the one who sells it.  I feel bad about putting a restriction on free software, but the restriction is what will keep it free.

Give It A Try

If you would like to give LaunchLater a shot, you can do so by downloading the installer on this page.

If you would like the source code, go here and click the “Download” link on the left hand side.

Please comment and offer any suggestions or critiques.  I appreciate all of it.

So as I said last time, stay tuned. 

I have a plan.

Follow

Get every new post delivered to your Inbox.