My Resume | Contact Me | RSS Feed | Follow Me on Twitter

Code Capers

The Ninja Coding Dojo
RSS Feed Twitter Email

Asteriods Clone in Silverlight

clock December 23, 2009 by author Michael Ceranski

When each year comes to an end people tend to reflect on the past year and their accomplishments. For a programmer this often results in a look through the previous years source code. Of all the projects that I did last year my favorite project was the asteriods silverlight clone that I built. The asteroids clone was my first attempt at a Silverlight game and it was really fun to build. The project was developed over the course of a weekend and it helped me to get acquainted with Silverlight. I will go through some of the source code in case you are considering building something similar and need some tips to on how to get started.

Getting Started

Like most games, you need to have a main loop where you can draw and redraw sprites based on some variables. This is accomplished by created a DispatcherTimer that invokes a drawing routine at a predefined interval. The drawing routine is responsible for looping through all the objects on the canvas and updating their positions. For example, when an asteroid appears on the screen, it already has been assigned a random angle, speed, and X, Y coordinates. When the timer ticks, the asteroid's X, Y values are recalculated using some basic math formulas. Here is an example:

public Page() {
    InitializeComponent(); 

    //create the timer used as the main loop

    _mainLoop.Stop();
    _mainLoop.Interval = TimeSpan.Zero;

    //wire up the events
    _mainLoop.Tick += new EventHandler(mainLoop_Tick);

    StartGame();
}

Looking at the code snippet above, you can see that there is a private variable named _mainLoop. The _mainLoop is just like any standard .NET timer object. It has a Start() and Stop() method, and it also has an event named Tick. In order to redraw the objects on the screen, I wire an event handler to the Tick event.

In order for this game to function, I had to develop code to redraw the asteroids, stars, and an occasional UFO. Also, we have to redraw the ship and its bullets. To simplify things, I stored each object category in a separate object list. This way, I could create separate methods like DrawAsteroids which could enumerate through the asteroids object list and update their positions.

The DrawAsteroids method is shown below. As you can see, I am iterating over an object list and calling the MoveForward method of the Asteroid class. Also, within the loop, I am checking to see if the asteroid has moved off of the screen. If it does, I adjust the X or Y coordinate to make it re-appear on the exact opposite side of the screen. This is how the original asteroids game works.

void DrawAsteriods() {
   for(int i = _asteroids.Count - 1; i >= 0; i--) {
     Asteroid a = _asteroids[i];
     a.MoveForward();
     if(a.X >= (this.Width - a.Width))
       a.X = 1;
     else if(a.X <= 0)
       a.X = this.Width - a.Width;
     if(a.Y >= (this.Height - a.Height))
       a.Y = 1;
     else if(a.Y <= 0)
       a.Y = this.Height - a.Height;
   }
}

The MoveForward method of the asteroid is very simple. It brings back wonderful memories of my high school math class! Basically, the first step is to convert degrees to radians. Then, I update the X coordinate using the Sin method which takes the radian value as an input parameter. Then, I multiply the result by a speed constant. The Y coordinate is calculated the same way, except we use the Cos method.

public void MoveForward()
{
   double radians = Math.PI * _angle / 180.0;
   X += Math.Sin(radians) * SPEED;
   Y -= Math.Cos(radians) * SPEED;
}

Handling Key Events

One of the problems I ran into while developing this game was the key event handling. I found out early on that I could not just rely on the standard KeyDown event because it was not firing properly. A game like this needs to be very responsive to the user pressing a key. The out of the box event handling simply did not cut the mustard. Luckily, after doing some Googling, I found others that had the same problem. At some point, I discovered the KeyState class. The KeyState class is a static class which basically is responsible for handling all the key up and key down events in the game. It stores the state of the keys that were pressed, and provides a much more responsive gaming experience. To check if a key was pressed, you call the GetKeyState method. In order to wire up the KeyState class, you just need to call the HookEvents method. Here is some code which is responsible for making the ship move around on the screen.

if(KeyState.GetKeyState(Key.Up) == true) {
   ship.Thrust();
} 
else {
   ship.Drift();
}

In the snippet above, I check to see if the user pressed the up arrow on the keyboard. If they did, I call the Thrust method. The Thrust method is similar to the Asteroid's MoveForward method except that it displays a little flame behind the ship which gives the illusion of the rocket engine being ignited.

Dynamic XAML

In the original asteroids game, there are three different sized asteroids. I really did not want to have a separate class for a small, medium, and large asteroid, so I figured out a way to dynamically create the XAML at runtime. Unfortunately, it seems like Silverlight is not really designed well for this scenario, but nonetheless, I figured out a way to make it work.

Basically, the concept here is to dynamically build an asteroid by populating the Data attribute of the Path element. The Data attribute defines how to draw the asteroid by using a path markup syntax. It is basically a mini language which can be used to describe geometric paths. Explaining the Path Markup Syntax is not easily done. In my opinion, it is about as cryptic as Regular Expressions, but some good tutorials can be found on MSDN.

In order to facilitate the three different size asteroids, I created a constructor which takes the size as a parameter.

public Asteroid(AsteroidSize size, Canvas parent ) 

Now that the size is defined, I can use that as a guideline when creating the path data. Now, it is a simple case of using some random number generation to draw the lines and create the asteroid.

public string GetPathData()
{
   int radius = (int)_size * BASE_RADIUS; 
   string pathData = String.Empty;
   for (int i = 0; i < 18; i++)
   {
      float degrees = i * 20;
      Point pt = CreatePointFromAngle(degrees, 
                   radius * (rand.Next(70,99) * .01));
      if (degrees == 0) {
         pathData += string.Format("M{0},{1} L", 
                       (int)pt.X + radius, (int)pt.Y + radius);
      }
      else{
         pathData += string.Format("{0},{1} ", 
                       (int)pt.X + radius, (int)pt.Y + radius);
      }
   }
   pathData += "z";
   return String.Format("<Path xmlns='http://schemas.microsoft.com/" + 
                        "winfx/2006/xaml/presentation' xmlns:x='http://schemas." + 
                        "microsoft.com/winfx/2006/xaml\' Data='{0}'/>", 
                        pathData); 
}

Collision Detection

The biggest challenge of this game was the collision detection. Fortunately, the tutorials at bluerosegames.com were very detailed, and gave me an excellent starting point. However, I did find that collision detection was largely dependent on how fast the client machine could repaint the screen. For example, if you are redrawing the screen too often, you can get in a situation where the client is not able to process the data fast enough and the collisions are not properly detected. Therefore, I ended up doing a lot of testing on different speed machines until I found a happy medium. In any case, collision detection works, but it is still far from perfect.

The theory behind the CheckCollision method is that it does a two pass test. First, it checks to see if the outer rectangle around object A intersects with object B. It helps if you visualize that each element is contained within a square box or rectangle. As a matter of fact, during some of my debugging, I actually modified my asteroids code so they all had a bright yellow border around them. This helped me to visualize what was actually going on.

If the outer rectangles of the objects intersect, then a second, more accurate check is done. Now, the individual detailed paths of those objects are checked to see if the individual pixels overlap. If they do, then we have a collision.

There may be more elegant or foolproof ways to do collision detection. If so, I would be happy to hear your ideas. This is my first attempt at a Silverlight game, so please be kind!

public static bool CheckCollision(FrameworkElement control1, 
              FrameworkElement controlElem1, FrameworkElement control2, 
              FrameworkElement controlElem2) {
   // first see if sprite rectangles collide
   Rect rect1 = UserControlBounds(control1);
   Rect rect2 = UserControlBounds(control2);
   rect1.Intersect(rect2);

   if(rect1 == Rect.Empty) {
      // no collision - GET OUT!
      return false;
   } else {
     bool bCollision = false;
     Point ptCheck = new Point();
     // now we do a more accurate pixel hit test
     for(int x = Convert.ToInt32(rect1.X); x < 
         Convert.ToInt32(rect1.X + rect1.Width); x++) {
        for(int y = Convert.ToInt32(rect1.Y); y < 
            Convert.ToInt32(rect1.Y + rect1.Height); y++) {
           ptCheck.X = x;
           ptCheck.Y = y;
           List<UIElement> hits = (List<UIElement>)
             System.Windows.Media.VisualTreeHelper.
             FindElementsInHostCoordinates(ptCheck, control1);
           if(hits.Contains(controlElem1)) {
              // we have a hit on the first control elem,
              // now see if the second elem has a similar hit
              List<UIElement> hits2 = (List<UIElement>)
                System.Windows.Media.VisualTreeHelper.
                FindElementsInHostCoordinates(ptCheck, control2);
              if(hits2.Contains(controlElem2)) {
                 bCollision = true;
                 break;
              }
     }
   }
   if(bCollision)
     break;
   }
   return bCollision;
  }
}

The one thing that I noticed about Silverlight and XAML is that it really does not lend itself to things like inheritance and polymorphism. Therefore, I had to repeat blocks of code in many of my classes because I could not figure out how to make things reusable. Some of the problems are probably due to the fact that this is my first Silverlight app and that I haven't figured out all of the kinks yet.


Honorable mention goes to Andy Beaulieu who built a similar type of game which I ended up modeling some parts of my game after. I stole his XAML for his space ship, because I am completely illiterate when it comes to graphic design.

Finally, this same article with source code was posted on the codeproject earlier this year. If you are interested in trying this app out then please feel free to Download the source code from codeproject.



Migrating From Blogger to BlogEngine.Net

clock December 20, 2009 by author Michael Ceranski

Update: After moving to BlogEngine I started getting a large amount of spam comments. I went through the trouble of implementing captcha and I outlined the steps here.

I recently went throught he painstaking process of migrating my blog from Blogger.com to BlogEngine.NET. Here is a brief walkthrough of the process:

  1. Export the blogger site to BlogML using Aaron Lerch's Poweshell Script. The powershell script produces an XML file which you can use to import all of your posts into BlogEngine.NET through the settings page.
  2. The BlogEngine.NET uses a concept called SLUG which is a relative URL. So if you write an article named "The Chistmas Story" it will produce a relative url of ~/post/the-christmas-story.aspx . Unfortunately the Blogger engine works differently. It removes certain words and punctuations from the URL string. In Blogger the same article would have a relative url of /2009/12/christmas-story.html. You will notice a few main differences here, Blogger uses the year and month as the initial part of the URL whereas BlogEngine.NET uses the path ~/post. Also Blogger removes certain words like "the" and has an html extension instead of an aspx extension. Therefore, after the migration you will want to repair your links so people can still find your articles using the old URLs. The best way to do this is to add some custom code to your error404.aspx.cs page. Basically, when someone tries to access a post on your site using the old Blogger style URLs they will get redirected to the error page. The code in the Page_Load of the error page will then attempt to re-translate the url into a BlogEngine.NET path. In my case, I used a regular expression to find any requests that were looking for 2009 blog posts (because this is the timeframe that I had a Blogger site):
    protected void Page_Load(object sender, EventArgs e)
    {

    string pattern = @"/2009/\d{2}/(?<oldPath>.+).html";
    Match m = Regex.Match(Request.Url.ToString(), pattern);
    if( m.Success) {
    Response.Redirect("~/post/" + m.Groups["oldPath"].Value + ".aspx" );
       }
    ...

    I also did a lot of manual updates to the articles making sure the SLUGs were correct. So if the old URL was /2009/12/christmas-story.html the proper slug for the BlogEngine would be christmas-story. For this part of the project I leveraged google and did a search for all articles on my site using the search string "site:codecapers.com". This produced a list of all the articles previously posted on my site. I then went through each search result, and updated the SLUG to match the old Blogger URLs.
  3. For some reason the powershell script did not maintain my Tags, so I had to go through my articles are re-tag them. I also used this as an opportunity to clean up some HTML and to replace some images that I did not like.


The whole process took about 2 days. If I had more than one year of articles I probably would have taken the time to expand on Aaron's powershell script. However, the overall process was not too bad and I am extremely happy with the end result. I am truly impressed with BlogEngine.NET and since I am a .NET developer it is really easy for me to make changes and customize everything to my hearts content.



Blogging - Lessons Learned

clock December 17, 2009 by author Michael Ceranski

UPDATE: I have made the switch to BlogEngine.NET. Thanks for the recommendation from Elijah Manor. Yes, it supports live writer and no database is required!

Lessons LearnedI am reaching the end of my first year of blogging. I really learned a lot in my first year and I wanted to share my experience with you. Like most people, I started out with three major questions:

1. What service or blog engine should I use?

This is a difficult question because there are quite a few free blogging sites out there. For example Wordpress and Blogger will allow you to sign up and start blogging for free. In the end it really comes down to personal preference. I am currently using blogger but I am less than enthused with the way the whole engine works. The themes are driven by XML templates which makes customizations a real pain. However, there is a large offering of widgets which makes things like adding a tag cloud a breeze.

Since I am a .NET developer, and I want to make extensive customizations to my site without dealing with hokey XML templates, I will probably switch over to using DasBlog or BlogEngine sometime next year. Unfortunately, this means I will have to pay for custom hosting. However, DasBlog and BlogEngine do not require a database so that makes the hosting a lot more affordable.

If you are not a developer and just want to write articles without knowing a lick of HTML then Wordpress and Blogger coupled with Windows Live Writer is the way to go. Just create your site and use Live Writer to develop your articles. Live Writer will take care of converting your text to HTML, uploading your images and everything else that goes with it. I have been using Live Writer for over 8 months now and I honestly will not even consider a blog engine unless it supports Live Writer.

2. How can I get people to read my blog?

The obvious answer is to pay for advertising by placing ads on a major search engine. However, there are other ways to get people to read your blog.

  • Tweet about you new blog post on twitter. Use Tags to make sure your tweet gets read by people who are interested in your topics. For example when I write a new article I will create a tweet that looks like this
    blogged: <URL> : My First Year of Blogging #Blogging #WebLog #HowTo
  • Add your website URL to your email signature and forum posts
  • Utilize the ping feature in Live Writer to promote your articles on sites like Technorati

3. Can I make money from blogging?

Absolutely, You can sign up with programs like Adsense, Adbrite or The Lounge . If you use blogger it is easy to integrate Adsense ads because both products are owned by Google. However, Adbrite and The Lounge are excellent alternatives. I have recently applied as a published with The Lounge. Hopefully they will accept my application! They came highly recommended from a few friends who also blog about programming and information technology.

You can make a lot of money from blogging. However, it takes time to build up content and to develop a following. In order to make money you need to post often and write articles that are appealing to a large mass of people. Don't expect to start making a ton of money in your first year. Right now I average a measly $2-3 a month.


If you are really passionate about a topic then blogging is the perfect creative outlet. Writing new articles and seeing other people's positive responses to them is very rewarding. As a positive side effect, blogging feeds the brain. When you have to explain something to someone in writing you end up gaining a better understanding of the topic. You typically will need to do a little research before you can start and that is how you learn.



Generating Dynamic HTML Tables with jQuery From an In-Memory DataTable

clock December 11, 2009 by author Michael Ceranski

By nature, web applications are stateless so you have to work a little harder to make them produce an user experience equivalent to that of a traditional windows application.

In this article, I will go over the process for how to load an HTML table to a web page using Ajax and jQuery. The process will require you to execute an asynchronous query in SQL Server, load it into a DataTable and return it to the browser as JSON (JavaScript Object Notation). Finally the JSON string can be consumed by jQuery and rendered as an HTML table on the browser.

Lets start out by looking at this traditional snippet of ADO.NET code:

System.Data.DataTable tbl = new System.Data.DataTable();

try {
using (SqlConnection conn = new SqlConnection(connectString)) {
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(tbl);
}
}
catch {
//do something
}

The code simply loads a query result into a DataTable. This is something that most .NET developers have probably done a million times before. Therefore I will just move forward onto the next step which is serializing the DataTable as JSON.

After a bit of experimenting, I determined that a collection of Dictionary objects would be a perfect candidate for serializing the DataTable as a JavaScript object. I originally tried just converting the DataTable by calling Json(tbl). However, the conversion was not sufficient for my needs. By using a collection of Dictionary objects, each row in the DataTable would map to a Dictionary object. Here is the code that I ended up with:

using System.Web.Script.Serialization;
...
public static string GetJson(DataTable table) {
JavaScriptSerializer jss = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;

foreach (DataRow dr in table.Rows) {
row = new Dictionary<string, object>();
foreach( DataColumn col in table.Columns ) {
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return jss.Serialize(rows);
}

To clarify the code, lets consider the following table:

ID NAME
1 Foo
2 Bar

This table would produce a list with two objects. The row with the ID of 1 would be represented as a dictionary object that has a Key equal to 1 and a Value equal to "Foo". The row with the ID of 2 would be represented as a dictionary object that has a Key equal to 2 and a Value equal to "Bar". When converted to a JSON string the entire table would look something like this:

[ { "ID" = 1, "NAME" = "Foo" }, { "ID" = 2, "NAME" = "Bar" } ]

For those of you who can interpret JSON, this is simply an array with two objects.

So now I have two parts of the puzzle completed. First, I executed the query and populated a DataTable. Secondly, I serialized the DataTable into JSON. Now I need to add the code to my webpage to make the asynchronous JavaScript call and format the results as an HTML table. Luckily for us, jQuery makes AJAX calls simple by using the post method:

   1:  $.post("/Utils/GetData", 
   2:      { orderBy: ord, keyword: key },
   3:      function(data) {
   4:         buildTable(data);
   5:      }
   6:  );

The first parameter in the post method is the URL of the method we are invoking on the web server. The second part consists of the parameters you are passing to the method. In my case, the method took 2 strings, one named orderBy and another named keyword. The variables ord and key were initialized earlier in the code by reading the values of two textboxes on the page. On line 3, we have the callback function that is invoked when the results are returned from the web server. The variable named data, is the JSON representation of the DataTable we created using the GetJson method. The only thing left to do now, is render the JSON results as a table.

To render the dynamic table I started by adding a placeholder to my web page which will hold the results:

<table id="grid"></table>  

Since there are no rows initially in my table it does not appear on the page. However, if you wanted to hide it you could easily do so by calling $("#grid").hide() or setting the initial style to display:none. And finally, here is the javascript that converts the serialized DataTable into HTML:

function buildTable(tableData) {    
var table = $("#grid");
table.html(""); //clear out the table if it was previously populated
eval("var data = " + tableData); //load the data variable as an object array

table.append('<thead><tr></tr></thead>');
var thead = $('thead tr', table);

//create the table headers
for (var propertyName in $(data)[0]) {
thead.append('<th>' + propertyName + '</th>');
}

//add the table rows
$(data).each(function(key, val) {
table.append('<tr></tr>');
var tr = $('tr:last', table);
for (var propertyName in val) {
tr.append('<td>' + val[propertyName] + '</td>');
}
});
}

In my application, I used this code to create a web page that allows a user to constantly modify the parameters for a query and dynamically update the results of a table without refreshing the page. jQuery and Ajax really make the web application feel "state-ful" Not to mention, it drastically improves the user experience within the application.



Introducing Microsoft Pivot

clock December 7, 2009 by author Michael Ceranski

Pivot is being developed as a way to connect data from different sources on the internet and aggregate each individual item into "collections" based on its metadata. The pivot website really sums it up nicely...At the heart of Pivot are "Collections." They combine large groups of similar items on the Internet, so we can begin viewing the relationships between individual pieces of information in a new way. By visualizing hidden patterns, Pivot enables users to discover new insights while interacting with thousands of things at once.

Pivot could be very useful for research purposes. Typically when I am learning about something new I will Google it, read the most promising results in the list first, then I will try use the new terminology I learned to create additional searches to "fill in the gaps". With Pivot, it seems that you can search for something with generalized terms and allow the collection engine to find other relevant information based on patterns it derives in the metadata. Right now the project is in beta but the idea behind it seems very powerful. For more information check out this video...

Get Microsoft Silverlight



About the author

MikeMy name is Michael Ceranski. I am a software developer from Buffalo NY. I have been writing code for over 10 years starting with Borland Delphi and later migrating to the .NET stack. I enjoy blogging about .NET, MVC and jQuery and I hope to spread my enthusiasm for technology by sharing my thoughts and ideas with you.

View my resume

Cumulus

This will be shown to users with no Flash or Javascript.

Sign in