Showing posts with label Applications. Show all posts
Showing posts with label Applications. Show all posts

Sunday, October 19, 2008

A Simple Clock In Silverlight

Hi friends,
Friday one of my friends (Manasa) send me some unusual clocks developed in flash. That gave me the idea of making one of them (the easiest one) in Silverlight.
I made it like the following



Brief Explanation

The root canvas contains 7 canvases. Each of them holds seconds, minutes, hours and other texts and digits. Each of the canvas is wide enough to hold all the digits or text. The root canvas clips it to show only 450 pixel. The child canvases move right to left so it appears moving to the user.

Now lets see seconds panel. Others will be similar.

Seconds panel has 9 digits visible at any time. Total seconds panel contains all the digits and clipped by the root to show only 9 digits.
Seconds panel has got 69 digits 0 1 2 3.......58 59 0 1 2 3 4 5 6 7 8. Last 9 digits are added because when we shift the panel from right to left at time the viewable part will be 59 0 1 2 3 4 5 6 7 8.(half of 59 and half of 8) Then it will be again 0 1 2 3 4 5 6 7 8 and this time we can repeat the animation without letting user see any discontinuity.

Seconds, minutes and hours panels are been shifted through animations. Days, dates are updated once in an hour. Months are updated once in a day and years are once in a month. (Seeing it update will keep you open your browser at least a month though !!!)

When the application starts it updates so the red line shows current values.

You can find the complete code here.

Thursday, October 16, 2008

Fractal Images -- Mathematics With Silverlight Again

Hi all,
When I first seen fractal images I was really impressed and wanted a bit try for making one myself. I have made a simple application that will generate some kool images based on fractal algorithms. This program is not for describing fractals, this is just to make some pretty images totally by complex mathematics.

here is one image that uses (Z * Z * Z + C) / (Z * Z * Z - C) formula and C=0.45 here. (C and Z are complex numbers)



You can make lots of images using different equation and different values of C.


How the Images are created.....

The image is actually a collection of 1 x 1 pixel ellipse different color. These ellipses are placed in a 500 x 600 Canvas. fractal algorithm determines how to color the ellipses and that is the only magic.

Algorithm.....

int iteration = 0;
do
{
R = (Z * Z * Z + C) / (Z * Z * Z - C);
Z = R;
iteration++;
} while (iteration < 100 && (R.Real * R.Real + R.Imaginary * R.Imaginary) < 4);

For coloring the ellipse


Random r = new Random(iteration);
byte red = (byte)r.Next(255);
byte green = (byte)r.Next(255);
byte blue = (byte)r.Next(255);
Plot(x, y, Color.FromArgb(255, red, green, blue));

Though it is using random number for same iteration value the color will be same as iteration is been used as seed for the random number. This is the beauty of pseudo numbers.

Here you can download the complete source code.

You can see the application running here.

One caution:- The code involve too many computation and placing 300000 ellipses. So it takes about 20 seconds to complete and might hang your browser during this time.

Here and here you can see details about fractals and algorithms.

I have updated some of my applications and posts in last few days. I will complete it as soon as I can.

Thursday, September 11, 2008

A Simple Wave Generator In Silverlight

[ Updated for Silverlight 2 ]

Hi,
I was building a simple waveform generator that will generate waveform for an equation containing sin, cos and tan. It will choose random color when drawing the curve and can draw one curve over another. The application in run looks like the following.



I cannot put it here as it wont fit in this width. See it here.

What is going inside......

The curve is actually a collection of ellipses of height and width 5. You can see it better if you draw a curve like tan() x sin().

I am trying to explain it from a top level (less detail) it step by step

1. We will have a stack named EqunList that will put the equation in string elements. For example it will store " sin" if you click sin button and then if you click + it will push "+" in the stack above sin.

2. Now when we click draw button the equation list will be converted from infix to postfix notation so that it eliminates the brackets and let us calculate the values of the equation easily.

3. It then chooses a random color for drawing the curve. Then it starts a timer that will put one ellipse every 15 milliseconds so that it seems the curve is been drawn slowly. We will talk about setting x and y coordinates (Canvas.Left and Canvas.Top respectively) of the ellipses shortly.

4. There will be a counter that will be incremented and after reaching a certain value (width of the drawing plane in pixels) will stop the timer.

5. Now the x value of the ellipse (Canvas.Left) will be incremented by 1 in each timer tick (It can be made higher but then the curve might not look very good). The Y value of the ellipse will be determined by evaluating the equation for an angle that will vary from 0 to 2*PI. Here the angle will be increased by 2 * Math.PI / 200 each time. ( It will actually creates a complete cycle in 200 pixels. Also the resultant value will be multiplied by 100. The reason of the multiplier is because otherwise the curve will have height of only 2 pixel in case of a sine wave. The curve will be drawn not from the top but from the middle of the canvas to take account the negetive values as well as positive values.

There are some minor tasks like disabling the buttons while one curve is drawn or clearing the equation after the curve is been drawn.

Here is the complete source code for it.

Please leave a comment if you have any doubt and also how to improve it. I am still inexperienced in programming field and have lots to know from you...
Thanks....

PS: BTW if you love music check out Madonna's new album Hard Candy. I am listening to the songs right now and they are excellent :)

Friday, July 18, 2008

Mahjong! My favorite game

[ Updated for Silverlight 2]

Mahjong has been my favorite game since the days I started using Linux (SUSE 10.2). I just tried and made "Something" (Play it full screen. F11). So I can play my favorite game in my off time. Of course it was again with Silverlight. Now here is the explanation and logic used to make this game.






Design

Page:

Page has 4 grids each with 15x9 dimension. So ultimately it gives the impression of a 3D stack. Each cell (total 15x9x4 cells) can be filled with a tile or left empty. The grids are been filled with tiles such a way it looks like a nice structure. In this structure 4th grid (I am calling as 4th rank) is empty. There are total 144 tiles. There are 12 types of tiles.

Tiles:

Each Tile is a user control. It has two canvases with rounded corner rectangles to make the nice 3D effect.

On the top canvas there are two rectangles. One for holding the tile image, another one to have mouse over effect.(Yellow one).

Each tile has 4 types of animations associated with it. (ClickAnimation, ClickOutAnimation, MouseOverAnimation, NotMatch). Click out animation will happen if user clicks the same tile twice. Not mach animation will happen when user tries to match wrong set of tiles.

Each tile has one TileNumber that determines the image to be put in the tile and it also helps in finding match.

Algorithm and code

Tile:

Each tile is having four variables associated with it.

TileNumber- Used to find match.

TilePosition- Gives rank, row and column in a 3 dimensional structure.

ParentPage- A reference to the Page class so it can call its methods.

IsClicked- Tells if the tile has already been clicked

Before starting any animation it will call its ParentPage method CheckIfFree to see if the tile is free.

On click of the tile after confirming it is free It will again call another parent page method TileClicked. This method will try to match this current tile with the previous tile clicked. If it matches It will destroy two tiles or it will show the NotMatch animation.

The constructor of this user control takes a random number from Page and set the tile image accordingly.

Main Page and logic:

In the Page there are 4 grids (4th one is empty in this tile structure I am now using).

First I am making the look of the board with a 3 dimensional array. Each element of that array represents empty or occupied state in boolean.

After making the grid structure I am adding tiles which are marked occupied.

In making the tiles for each tile GetTileNumber method returns one random number between 0 to 11 and it returns such a way that every number will be for 12 times making total 144 tiles.

This is the tile number used generally and I am also using for my game.

int[] TileTypeCount;
TileTypeCount = new int[12];

private int GetTileNumber()
{
int tileNo;
do
{
tileNo = rnd.Next(12);
} while (TileTypeCount[tileNo] >= 12);

TileTypeCount[tileNo]++;
return tileNo;
}


Filling tiles for the fast grid. Lowest level


// for set 1 rank 0
for (int row = MaxRow - 1; row >= 0; row--)
{
for (int col = 0; col < MaxCol; col++)
{
if (TileGridStructure[0, row, col]) continue;
TileStructure tile = new TileStructure(GetTileNumber(), this, new Position(0, row, col));
Grid.SetRow(tile, row);
Grid.SetColumn(tile, col);
Set1.Children.Add(tile);
TileCollection[0, row, col] = tile;
}
}



TileGridStructure tells if this place is to be filled with a tile or not.

Here you will find the complete source code.

Bye for now. Please leave a comment if you have any doubt or correction.

Experimenting with DeepZoom

A new feature in silverlight is DeepZoom. Its extreamly popular in the Silverlight community and looks kool. I never touched it before. Today I installed DeepZoom Composer and started building "Something". It was easier than I thought. I used 50 images (Hi-resolution upto 7432 X 4168 ). All collected from wikipedia featured pictures to avoid licencing issues. I shaped it over like a G. It goes well. But I was trying to make something like DeepZoomObama. Last I saw the blog that describes Making of DeepZoomObama project. All that is need to make a mosaic with lots of images. I collected more (more than 350) Images from wikipedia and started building it. It took only around 2 to 3 hours to build this.



The software that used for this is andreamosaic and Silverlight Deep Zoom composer. Two softwares are extremely easy to use.

Eight Queen Code

[Updated for Silverlight 2]

I blogged previously about the N-Queen problem. Here I am going to explain how I did it.

The Board and the Queen
I used a StackPanel to hold the Board and the button. The board is a 8x 8 Grid. And empty at design time. Also have a event handler for the button Click.
The Queen is a user control having just a Image with a white Background.
Now adding one Canvas for each square and painting it with blackish or whitish gradient brush already created as a resource

Repeating this for 64 squares.


Canvas c = new Canvas();

if ((row + col) % 2 == 0)

{

c.Background = (LinearGradientBrush)Resources["BlackBrush"];

}

else

{

c.Background = (LinearGradientBrush)Resources["WhiteBrush"];

}

Also having a blue hidden rectangle in each square that shows up when that square is being traversed and creates a nice animation. Also having a global variable for storing the squares and blue rectangles as we need them later.

For adding and removing the Queen I am using this code.

Sqare[row, col].Children.Add(new Queen());

Sqare[row, col].Children.RemoveAt(0);

The Animation

The animation for the blue rectangle is like the following.


<Storyboard x:Name="AnimSquare" Storyboard.TargetProperty="Opacity" Duration="0:0:0.2">

<DoubleAnimationUsingKeyFrames BeginTime="00:00:00">

<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>

<SplineDoubleKeyFrame KeyTime="00:00:00.1" Value="1"/>

<SplineDoubleKeyFrame KeyTime="00:00:00.13" Value="0"/>

</DoubleAnimationUsingKeyFrames>

</Storyboard>


See there is no target name defined for the storyboard as we will be applying different square (The blue rectangle over the square exactly) as target.


AnimSquare.Stop();

Storyboard.SetTarget(AnimSquare, SquareMask[Grow, Gcol]);

AnimSquare.Begin();

The Algorithm

The algorithm is as follows.

As there will be 8 Queens for 8 rows there will be one at each row.

Start from the left top square.

Put a Queen if that does not captured by other queens.

Jump to the next row and try it for 8 squares in that row.

If unsuccessful then go to previous row and remove the previous Queen placed there and try another square that have not been tried for that row.

If that also unsuccessful go to lower rows until you find a new square to put the queen in that row.

This can be achieved with a recursion.


private void PlaceQueen(int row, int col)

{

if (row == NoOFQueen) return; //Get out of recursion

CheckedCol[row] = col;

if (IsSafe(row, col))

{

if (!flag)

{

PutQueen(row, col);

row++;

col = 0;

}

else

{

CheckedCol[row] = 0;

row--;

RemoveQueen(row, CheckedCol[row]);

col = CheckedCol[row] + 1;

}

}

else

{

if (col == (NoOFQueen - 1)) // No where to place queen in the row

{

CheckedCol[row] = 0;

row--;

RemoveQueen(row, CheckedCol[row]);

}

else

{

col++;

}

}

//Grow = row; Gcol = col;

PlaceQueen(row, col);

}

Now the methods used here are self explanatory and simple. There is only one tricky part in this recursion. That is the boolean flag. It keeps the track if the queen from the last column has been removed. So next there wont be any queen placed on that column even if the square is safe. It will go farther one level down and so. The flag is set false whenever a new queen is placed on the board.

There I did a little change in this method. Instead of calling the same method from PlaceQueen it has been called from a Tick event of a timer to enable animation. (see the commented Grow and Gcol. G for global ).

This version of my program is still yet needs optimization and some code cleanup. It does not check if something unexpected happens. It doesnt even have a safecounter for getting out of recursion in case 8 Queens can not be placed at all.

Here is the demo.

And you can download the complete source from here.

for any clarification or modification please leave a comment.

N-Queen Problem using Backtrack Recursion

[ Updated for Silverlight 2 ]

Hi,
For last two days I am trying to build a Silverlight Program that will solve n-queen (here I am using 8 ) problem and show it step by step to the user. After messing up with the logic finally managed to get it work. The algorithm still needs some improvements. I have uploaded the application in live streaming .





Those don't know about the 8-Queen Puzzle it is to place 8 queens in a chess board so no queen can capture others.

Here is the complete code for it. I will look up the code and clean it. I will explain it in my next post. For now I am listening to Celine Dion. There are lots of things happening today to make me happy :)