Showing posts with label silverlight. Show all posts
Showing posts with label silverlight. Show all posts

Friday, June 18, 2010

Returning a string array to Javascript from Sliverlight

This took a lot of trial and error, but I finally figured out how to return to Javascript a string array. There where many different examples out on the web to call Javascript, passing a string array. But, no examples had Javascript calling a Silverlight function with a string array as the return value.

I first tried the direct approach:

javascript:
function TalkToSilverlight(data) {
var control = document.getElementById("silverlightControl");
var myStringArray = control.Content.Page.ReturningStringArray();
alert('length = ' + myStringArray.length + " : Value of First Element = " + myStringArray[0]);
}


Silverlight C#
public App()
{
HtmlPage.RegisterScriptableObject("Page", this);
//The rest I've elided
}

[ScriptableMember]
public string[] ReturningStringArray()
{
return new [] { "e", "i", "e", "i", "o" };
}


Well to make a long story short, a small little mention of the IList interface on MSDN was the key, all I "needed" to do (as opposed to all the changes I tried) was change the return value from string[] to IList.

Monday, November 30, 2009

How to create your own Silverlight Cube Control similar to Telerik's Cube

Well, as part of our lastest project, I needed to figure a way how to spin a widget.

So, how do you rotate widgets in an Asp.Net application? Well that question is fairly simple to answer - Silverlight!

The next question is much harder: Buy or Build?

After some searches I found two controls for sale: The Telerik Cube control and the ComponentOne C1Cube control.

So, first stop, download each and put them through the paces. I found a deal breaker for each control.

We need to be able to minimize our widgets but both controls had problems with that:
- The Telerik control would resize but would apply a transform to 'Squash' the widget and according to the Telerik website FAQ, this behaviour can not be overridden.
- The Component one control 'Must' be in the shape of a cube. Ok, I know that sounds like a 'duh' point, but like I said, we need to minimize our widgets. But when I altered the height of the control to just the height of the header, the cubes' width was also adjusted.

So, that left build - but there did not seem to be any examples of how to rotate a cube from side to side, on demand. I did find an example of a continuously spinning cube. With this example to decompose, I slowly taught myself the parameters and transformations that were needed to create the appearance of a cube spinning from one face to another.

So, here is my demo of a rotating six sided cube. If you do not need to rotate to the top and the bottom, you can have sides of any height, as long as all the sides are of the same height. Plus, my example is not limited to four or six sides. This example allows for an unlimited number of sides!

Now, there a couple of things that the professional controls do that my demo cannot. My code cannot free rotate and it also does not twist as it rotates to properly show a side. If you need these properties, you may want to go with the professional controls.

Here is the Visual Studio 2008/Silverlight 3 project.

Wednesday, August 19, 2009

The easiest way to convert vector graphics to XAML

Wow, this is sooooo simple. I've been converting WMF, EMF, CDX, CDR, AI, EPS, PDF and SVG to XAML all day. This is actually fun!

First get a vector graphic and a program that can open it. I've used Adobe Illustrator, CorelDraw, Inkscape and even Windows Picture and Fax Viewer.

Next get a vector graphic that your program can open.

Finally get the Microsoft XPS printer driver if it is not already installed.

Now open the file in your program of choice and print it to the XPS printer driver.

Now rename the resultant XPS file to ZIP.

Open the ZIP file and inside the Documents/1/Pages folder is a file named 1.fpage.

Extract the file and rename it to .XAML.

Now you have a XAML file that will open in Internet Explorer, but if you want to have a XAML file that will open kaxaml or for use in a WPF or a Silverlight application, open the file in notepad and replace the FixedPage tag with the Canvas tag.

Here is a XAML graphic I converted from my Corel Gallery. (Either open link in IE7/IE8 or download the XAML file and open it in your XAML viewer of choice)

Older posts from other blogs tell you to use Inkscape and print to PDF and then open the PDF in Adobe PDF Viewer. Fron the Adobe PDF Viewer you can then print to the XPS printer driver. The reason was that Inkscape converted the file to a raster image. Then and only then could you retrieve the 1.fpage file. This was because Inkscape sent the graphic to the printer as a raster image, not a vector image.

Well, since those blog posts were written, there have been updates to Inkscape, and now Inkscape prints a vector image as a vector, so there is now no need for converting it to an intermediate format (PDF).

Saturday, July 11, 2009

Risk Map in Silverlight 2

As I mentioned in a previous post, I have reworked the USA map project to represent the map in the game of Risk.



The above image shows how the XAML is defined. The XAML is based on the SVG file found here. Once the project is ran, each country (both its inner and outer polygons) are entered into a data graph, similar to the one I used for the USA Map, with just a few improvements.

This demo, when ran, assigns each country to a player and assumes that you are the Green player. If you click on a country that is bordered with bright green, its border will turn black and all enemy held countries' borders will turn white. This shows what nations are available to attack.



If a programmer had a risk game play engine, this silverlight front-end will work quite well for you. The complete project can be downloaded here.

Thursday, April 2, 2009

How to get a Silverlight Application to work at 1and1

Just a quick little post to tell everyone what they need to get a Silverlight Application up and running at 1and1.

You only need to make two quick changes.
1- Rename the XAP file to ZIP
2- Change the call in the TestPage.html file to reference the ZIP file instead of the XAP file.

Saturday, March 28, 2009

How to make Asymmetrical Board Game maps in Silverlight

Or, how I spent my evenings at MIX09 in Las Vegas.

Last year, I began looking into writing board games with an asymmetrical map boards. I started with Awful Green Things from Outer Space (AGTFOS), a classic beer and pretzels game by Tom Wham. I started with an alternate game board graphic I downloaded from boardgamegeeks.com.



But, since the map is asymmetrical, there is no simple math function that, given an X,Y coordinate, would tell me what room in the spaceship I clicked on.

After a lot of googling, I found that boardgame programmers use a 2D array where every every element in the array corresponds to a pixel in the map image. Then set al the array elements to values that equal what room that pixel is in. This worked great, but it has a problem - No scaling. I could not scale the graphic and still know what room I was in.

WPF and Silverlight to the rescue!

So, as a proof of concept, I took a states map of the USA in SVG from Wikipedia and used ZamlTune to convert the SVG to XAML. Since all the elements in WPF are scalable and clickable, I was able to, with just a few lines of code, make the map aware of what element I was clicking and change its fill color.

That solved half of the problem of a asymmetrical board game map. The other issue is for movement and conflict. We need to know what states directly border the selected state. For this we need to go back to Comp Sci 350 - Data Structures. We need a graph.

Graphs have Vertexes and Edges. A vertex can be thought of as a location and the Edges as the roads to and from these locations. So, if we had a Graph with a vertex for each State and an edge to each bordering State, we could easily find out what States border each other.

Unlike previous silverlight examples I've posted, this one cannot be embeded since it needs to resize, so you need to open the link to run my example USA map. If we wanted to play Risk on a USA map, this would be a large positive step towards that goal.

As, you can see in the image the selected State is in Blue and the bordering States are in Light Blue. (Click on Image to Open The Silverlight Application)


Unfortunately the Graph object I wrote for this proof of concept is not nearly as full featured a Graph object as per my previous post.

And here is a zip file containing the entire Visual Studio 2008 Project.

Sunday, March 1, 2009

Sudoku in Silverlight

You know how it is, you learn a skill (Programming in my case) because you see the results of others. Looking at the fruits of their labors, you say, "wow! I want to be able to do that." So you start learning, take some classes, read some books, maybe like me you enroll in the Computer Science program. If you get good, you may even get a job using your new found skill. But, did the learning of this skill lead you to the place you wanted to be, all those long years ago?

When I first started programming, it was to automate the games I was already playing. Then I moved into trying to replicate the types of games that I had played before on the computer. But as it usually happens, the real world got in the way. Instead of learning how to animate sprites, I had to learn how to connect to a database. Instead of graphics, I had to learn about algorithms.

Now, I'm not knocking my job and the work I do. I rarely go to "Work" since I get to indulge in my passion for programming every day. But, I feel this need to give more than lip service to the original reason that I got into the "Biz" in the first place.

Believe me, in 25 years the landscape of game programming has changed so much that I hardly recognize it! And, I've tried to keep my feet wet in the technology the entire time. The time when the ability to draw a digital stick figure and write a great game around it (Lode Runner) is long gone. When I first made up my mind to bite the bullet and truly try to learn game programming, in depth, the technology seemed so complicated that I almost quit.

But Rome was not built in a day and neither were any of my favorite games. Like I tell all of my junior programmers, "Start at the beginning, then just program each little piece until it is done”, I decided to start with the smallest bite I could “chew” and then just keep going. The first "Game" I wrote was a Sudoku generator with a Javascript back end. I Wrapped a website around it and launched it a couple of years ago.

Well, here is the thing about games, the are not all created equal. Sure Sudoku is a "Game" per se, but not really related to my true love, boardgames. So http://www.freedailygames.net languished for a few years without any upkeep. I even thought of just shutting it down, but according to Google analytics, I have a few very loyal customers. And, now with the new technology of Silverlight, I thought that updating my site with a Silverlight implementation of Sudoku would help me build my skills and give freedailygames.net a tech boost.

Well, here is my take on Sudoku in Silverlight.



And here is a zip file containing the entire Visual Studio 2008 Project.

Sunday, February 8, 2009

Fancy fonts in XAML (Silverlight and WPF)

Outline, Shadow, Embossed and Engraved text in XAML.

Here are a few quick and easy ways to spice of your text in XAML.

To use these tricks, you need to have the ability to exactly place the text. For that you need to use a Canvas Layout control.


<UserControl x:Class="SilverlightApplication2.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="320" Height="200">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions >
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="2" Canvas.Left="10">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="2" Canvas.Left="12">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="10">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="12">Outline</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="3" Canvas.Left="11"
Foreground="White">Outline</TextBlock>
</Canvas>
</Button>
<Button Grid.Column="0" Grid.Row="1" Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="5" Canvas.Left="4"
Foreground="Black">Shadow</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="3" Canvas.Left="2"
Foreground="Gray">Shadow</TextBlock>
</Canvas>
</Button>
<Button Grid.Column="1" Grid.Row="0" Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="3" Canvas.Left="0"
Foreground="Gray">Engrave</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="5" Canvas.Left="2"
Foreground="White">Engrave</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="1"
Foreground="Black">Engrave</TextBlock>
</Canvas>
</Button>
<Button Grid.Column="1" Grid.Row="1" Margin="3">
<Canvas Width="800" Height="60">
<TextBlock FontSize="36"
Canvas.Top="5" Canvas.Left="3"
Foreground="Gray">Emboss</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="2" Canvas.Left="2"
Foreground="White">Emboss</TextBlock>
<TextBlock FontSize="36"
Canvas.Top="4" Canvas.Left="4"
Foreground="Black">Emboss</TextBlock>
</Canvas>
</Button>
</Grid>
</UserControl>

Wednesday, January 21, 2009

Tic Tac Toe in Silverlight

When I first started looking Silverlight, I looked around for tutorials that focused on topics I find interesting. I have found that I typically learn better if I'm applying learning to topics for which I have a passion.

I love games and one of the simplest is Tic Tac Toe. I thought if I could find a tutorial on implementing Tic Tac Toe in Silverlight, it would not only teach the basics of Silverlight development but would also teach how to interact with graphics. Unfortunately I could not find such a tutorial.

I eventually waded my way through much less entertaining tutorials and got my programming feet wet with Silverlight. As a test of my learning I wrote a two player Tic Tac Toe game.

After finishing my first AI post on Rock/Paper/Scissors I started looking for my next AI project. Well I had that two player Silverlight game laying around, how about I write an AI opponent for it?

What could be easier?

Well a lot of things could be easier, like "Hello World", but once I get my teeth into a project I see it to the end. Well, first things first, how have others designed AI opponents for Tic Tac Toe? A quick google search proved that I was definitely not blazing an new trails here. I found tons of examples for just about every type of AI for Tic Tac Toe.

But this webpage gives a simple set of patterns for matching. Best of all, they could be implemented using Regular Expressions!

So, here is my Silverlight AI Tic Tac Toe game where the pattern matching AI is implemented using Regular Expressions.



And here is a zip file containing the entire Visual Studio 2008 Project.

Saturday, December 6, 2008

Switcheroo - An old "Magazine" game in Silverlight, Part 1

In a previous post, I described the game Switcheroo. In this first post we will create a the start splash screen, the game board and the end splash screen.

The splash screen for a very visual game should be striking. Unfortunately, I am not a graphic artist, so the best I could come up with is the name switcheroo rendered using WordArt in Word.

We need to display the splash screen along with a start button. When the start button is clicked, we can then hide the splash screen and display the game board.

If you remember from that previous post, players can either place a piece on the 5x5 gameboard or rotate a row to the left or right, or rotate a column up or down. So, not only do we need a 5x5 checkerboard but we also need a mechanism to allow the players to rotate the columns and rows.

To accomplish this I added an extra column at the start and the end of the gameboard and an extra row to the top and the bottom of the gameboard. I added small golden arrows.

Once the game has been one or lost, on the placement of the winning move, we need to hide the gameboard and show the splash screen again. This time with a button declaring their win or loss and asking if they wish to play again.

The only problem with this is from a aesthetic point. When we place the winning piece, rotate the winning piece into place or our opponents move defeats us, we do not want to immediately flash to the splash page. The player may not have been able to even see that the move was a winning move or what their opponent even did to win, so we need to include a delay upon determining that the game is in fact over.

In the code for this first part, the both splash screens will work as they are supposed to, but since we have not created any game logic yet, we will consider any click on the gameboard to be the winning move and after our short delay the "You lose" version of the splash screen will display.

If you click on the button, the gameboard will display again and the whole process will start again, but the code will rotate between the "You win" and "You lose" messages to verify that both code paths work.

As you can see, instead of a lot of repetitive XAML, the only hardcoded XAML sets up the grid that will contain the gameboard and the elements for the splash screen.
<UserControl x:Class="Switcheroo.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="300" Height="300">
<Grid x:Name="LayoutRoot"
Tag="Bob">
<Grid.ColumnDefinitions>
<ColumnDefinition Width='25' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='50' />
<ColumnDefinition Width='25' />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='25' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='50' />
<RowDefinition Height='25' />
</Grid.RowDefinitions>
<Image x:Name="XamlBoard"
Grid.RowSpan='7'
Grid.ColumnSpan='7'
Source='Splash.png' />
<StackPanel VerticalAlignment="Center"
HorizontalAlignment="Center"
Grid.RowSpan="7"
Grid.ColumnSpan="7">
<Button Click="Start_Click"
Content="Start"></Button>
</StackPanel>
</Grid>
</UserControl>

The XAML code also available here!

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Switcheroo
{
public partial class Page
{
private class MyColors
{
public static Color Aliceblue { get { return GenerateColorStruct(0xFFF0F8FF); } }
public static Color Cyan { get { return GenerateColorStruct(0xFF00FFFF); } }
public static Color Darkcyan { get { return GenerateColorStruct(0xFF008B8B); } }
public static Color Darkgoldenrod { get { return GenerateColorStruct(0xFFB8860B); } }
public static Color Gold { get { return GenerateColorStruct(0xFFFFD700); } }

private static Color GenerateColorStruct(uint color)
{
var mask = 0x000000FF;

var returnval = new Color
{
A = ((byte)((color >> 24) & mask)),
R = ((byte)((color >> 16) & mask)),
G = ((byte)((color >> 8) & mask)),
B = ((byte)((color) & mask))
};

return returnval;
}
}

private class GameBoard
{
internal readonly int[,] Board = new int[5, 5];

public GameBoard()
{
for (var i = 0; i < 5; i++)
{
for (var j = 0; j < 5; j++)
{
Board[i, j] = -1;
}
}
}
}

readonly DispatcherTimer dt = new DispatcherTimer();

private bool GameOver;
private int GameWinner = -1;
private GameBoard Switcheroo = new GameBoard();

public Page()
{
InitializeComponent();
}

private void Start_Click(object sender, RoutedEventArgs e)
{
Switcheroo = new GameBoard();
LayoutRoot.Children.Clear();
CreateGameBoard();
GameOver = false;
}

private void dt_Tick(object sender, EventArgs e)
{
dt.Stop();
DisplayGameOverSplash();
}

private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
GameOver = true;

GameWinner = GameWinner == 0 ? 1 : 0;

if (GameOver)
{
dt.Interval = new TimeSpan(0, 0, 0, 0, 500); // 500 Milliseconds
dt.Tick += dt_Tick;
dt.Start();
}
}

private void CreateGameBoard()
{
var CellColor = false;
Canvas c;

for (var i = 0; i < 7; i++)
{
for (var j = 0; j < 7; j++)
{
if (i != 0 && i != 6 && j != 0 && j != 6)
{
c = new Canvas
{
Tag = (i + ":" + j),
Background =
(CellColor
? new SolidColorBrush(MyColors.Aliceblue)
: new SolidColorBrush(MyColors.Darkcyan))
};
}
else
{
c = new Canvas
{
Tag = (i + ":" + j),
Background = new SolidColorBrush(MyColors.Cyan)
};


if (j == 6 && i != 0 && i != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(10, 5));
p.Points.Add(new Point(40, 5));
p.Points.Add(new Point(25, 15));

c.Children.Add(p);
}
else if (j == 0 && i != 0 && i != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(10, 20));
p.Points.Add(new Point(40, 20));
p.Points.Add(new Point(25, 10));

c.Children.Add(p);

}
else if (i == 6 && j != 0 && j != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(5, 10));
p.Points.Add(new Point(5, 40));
p.Points.Add(new Point(15, 25));

c.Children.Add(p);

}
else if (i == 0 && j != 0 && j != 6)
{
var p = new Polygon
{
Fill = new SolidColorBrush(MyColors.Gold),
Stroke = new SolidColorBrush(MyColors.Darkgoldenrod)
};

p.Points.Add(new Point(20, 10));
p.Points.Add(new Point(20, 40));
p.Points.Add(new Point(10, 25));

c.Children.Add(p);

}
}

c.MouseLeftButtonDown += Canvas_MouseLeftButtonDown;
Grid.SetColumn(c, i);
Grid.SetRow(c, j);

LayoutRoot.Children.Add(c);

CellColor = !CellColor;
}
}
}

private void DisplayGameOverSplash()
{
string ButtonText = GameWinner != 0 ? "You Win! Play Again?" : "You Loose! Play Again?";

const string Splash = "<Image xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' " +
"x:Name='XamlBoard' Grid.RowSpan='7' Grid.ColumnSpan='7' Source='Splash.png' /> ";

const string Stack = "<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' VerticalAlignment='Center' " +
"HorizontalAlignment='Center' Grid.RowSpan='7' Grid.ColumnSpan='7' />";

string Button = "<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Content='" + ButtonText + "'></Button>";

LayoutRoot.Children.Clear();
LayoutRoot.Children.Add((Image)XamlReader.Load(Splash));
LayoutRoot.Children.Add((StackPanel)XamlReader.Load(Stack));
((StackPanel)LayoutRoot.Children[1]).Children.Add((Button)XamlReader.Load(Button));
((Button)((StackPanel)LayoutRoot.Children[1]).Children[0]).Click += Start_Click;
}
}
}

The C# code also available here!

Tuesday, November 11, 2008

Dynamically adding XAML strings from C#

In designing the screen for my silverlight game Switcheroo, I wanted to be able to dynamically add XAML chunks that represent the pieces (Ellipse). True, I could have just created the graphic elements property by property, but since the only difference between all the game pieces is if they are black or red, I thought that if it only took one or two lines of code, it would be a more elegant solution.

I wanted to separate the internal representation of the gameboard in the gaming object from the XAML front end. Then I could just clear the gameboard and recreate all the pieces after the gameboard object was updated. The question was, how?

Well I googled high and low but though I found many "solutions" to my problem, none of them worked. After trying different combinations of the aforementioned solutions, I got closer. This is my first try that made any headway:

const string red =
"<Ellipse Stroke='Black' Fill='Red' Height='30' Width='30' Margin='10,10,10,10' />";

LayoutRoot.Children.Add((Ellipse)XamlReader.Load(red));


But the error I got back was:

AG_E_PARSER_MISSING_DEFAULT_NAMESPACE [Line: 0 Position: 0]

Not a very helpful error message! Well, googling this error I found others that were getting the same error and a simple answer - the element must contain the same namespace. The only namespace is the one at the beginning of the XAML document thought. Well, I thought, it's worth a shot. So I added the namespace lines from the beginning of the element. Our code now looked like this:

const string red =
"<Ellipse xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Stroke='Black' Fill='Red' Height='30' Width='30' Margin='10,10,10,10' />";

LayoutRoot.Children.Add((Ellipse)XamlReader.Load(red));


And low and behold! It worked!

So when you have lots of repetitious XAML or elements like named colors that cannot be easily replicated in code, just use the XAML string!

Thursday, October 23, 2008

Where have all the colors gone?

If you are programming in Silverlight, you probably have seen all the colors available in the XAML. Want a line that is AliceBlue, no problem, but if you want to create the same line programatically in C#, good luck.

The Colors class is just a small subset of all the HTML named colors, so the only way to add AliceBlue is to use Color.FromArgb, so you go out to a website that lists all the colors' RGB values. AliceBlue is #F0F8FF, so you paste the RGB value into Color.FromArgb.

But wait! Color.FromArgb expects 4 bytes, not a single number (The first byte is the Alpha value - i.e. the transparentcy of the color, hence the A in front of the RGB) and our color is only 3 bytes. We can add #FF in front of #F0F8FF but Color.FromArgb expects them to be separate values separated by a comma.

Color.FromArgb(#FF, #F0, #F8, #FF) will not work because C# does not recognize them as numbers. The key to having C# recognize them as hex numbers is to replace the hash(#) with 0x. So AliceBlue is now Color.FromArgb(0xFF, 0xF0, 0xF8, 0xFF).

Too much work you say? I agree. I just want to use my named colors. So, I created my own Color class that in Silverlight will output named colors!

The code looks like this:


private class MyColors
{
    public static Color Aliceblue
    {
        get
        {
            return GenerateColorStruct(0xFFF0F8FF);
        }
    }

    .
    .
    .

    private static Color GenerateColorStruct
                                    (uint color)
    {
        var mask = 0x000000FF;
        var returnval = new Color
        {
            A = ((byte)((color >> 24) & mask)),
            R = ((byte)((color >> 16) & mask)),
            G = ((byte)((color >> 8) & mask)),
            B = ((byte)((color) & mask))
        };

        return returnval;
    }
}


The entire .cs file can be found here. Since this is a private class that you can add to any Silverlight page.cs file that needs named colors , you can also add your own named colors that you want to use all the time!

You can also compile it to its own dll, but I like it better in the page.cs file. For size of outputs sake, right before you publish you can remove all the unused colors.

Wednesday, October 22, 2008

Old Games In Silverlight

It continually amazes me how many great games were published in the 80's and 90's in hobby programming magazines. Sure, they are not the type of games that a company like Electronic Arts would be interested in and are definitely not up to the standards of today's games on the PC, but casual gaming on the web and mobile devices has possibly created a new home for these games.

In one of my old programming magazines (Compute's! Gazette, June 1986 - Issue 36, Vol. 4, No. 6) described a game called Switcheroo, by Kevin Mykytyn and Mark Tuttle. A simple connect 5 on a 5x5 grid (horizontally or vertically, no diagonals) with a twist. The player can place a piece of his color on an empty space or he may shift a column up or down, or shift a row left or right. Any pieces that are removed from the board by the shift are places in at the end of the column or row in the newly vacant space.

I think that this game would be a great coding test for Silverlight, so I will be posting a multi-part blog entry on writing Switcheroo in Silverlight2.0.

Unfortunately, all the games published in Compute's! Gazette were in a version of Machine Language called "MLX", so the effort would be heroic to try to adjust the code to a more modern platform such as Silverlight. And, with the fact that there was no AI (It was a 2 player game) and we will want to play against the computer, we will be starting from scratch.