XAML Playground
about XAML and other Amenities

The Reactive Snake for Windows Phone 7

2011-05-04T22:57:43+01:00 by codeblock

CaptureContinuing my experiments with Reactive Extension I put together a small example that show an alternative use of the library to create a little game. The game is the widely known Snake that many of us have played on his own Nokia when it is the sole game in the ancient models. Please take note that the game I wrote is not complete since it is first of all an example of the use of a technology and how it can simplify the development of a slightly complex logic like the one that is behind this game.

The core of the game is based on two separate uses of the Reactive Extensions. From one side I have a main loop that is based on a frequent timeout that in a complete version of the game could be used to change the game speed. In this version it is set to 75 milliseconds. Every time the timeout is elapsed I move forward the Snake of one position saved in two variables XDirection and YDirection. This variable can assume the values of 1 or -1 if the snake is moving along the direction and 0 if the snake is moving along the opposite direction.

Using this variables the GenerateWithTime method of the RX generate a stream of points that are the positions where the Snake have passed during its move. The length of the snake is determined by the TrailWhile method that evaluate the length using a third variable that is incremented every time the Snake eats a gem.

The other use of the RX is to handle the Manipulation events that are used to detect if the user touches the screen basing on this touches the XDirection and YDirection are updated to reflect the touch. As an example if when the snake is moving along the y axis like the screenshot the touch on the right side of the screen make change the direction to right and the touch on the left to left.

Here is the code of the main game loop:

Observable.GenerateWithTime(
    new Point(0, 0),
    p => this.IsRunning,
    p => p,
    p => TimeSpan.FromMilliseconds(75),
    p => this.NewPoint(p))
    .ObserveOnDispatcher()
    .TrailWhile(o => o > this.Length)
    .Subscribe(this.EvaluateAndDrawSnake);
 
private Point NewPoint(Point point)
{
    double x = point.X + XDirection;
    double y = point.Y + YDirection;
 
    if (x < 0) x = 22;
    if (x > 22) x = 0;
    if (y < 0) y = 36;
    if (y > 36) y = 0;
 
    return new Point(x, y);
}

The method EvaluateAndDraw is the part of the code that check when the snake eats itself to end the game and then redraw the snake on the screen. Here is the management of the screen:

Observable.FromEvent<ManipulationStartedEventArgs>(
    ev => this.ManipulationStarted += ev,
    ev => this.ManipulationStarted -= ev)
    .Select(
    o =>
    {
        return new
        { 
            X = Math.Sign(o.EventArgs.ManipulationOrigin.X - 240), 
            Y = Math.Sign(o.EventArgs.ManipulationOrigin.Y - 400) 
        };
    })
    .Subscribe(
    o =>
    {
        if (this.XDirection != 0 && this.YDirection == 0)
        {
            this.XDirection = 0;
            this.YDirection = o.Y != 0 ? o.Y : this.YDirection;
        }
        else if (this.XDirection == 0 && this.YDirection != 0)
        {
            this.XDirection = o.X != 0 ? o.X : this.XDirection;
            this.YDirection = 0;
        }
    });

The following link lets you download the complete source of the example. My highest score is 510. Have a good game.

Download: SLPG.ReactiveSnake.zip (140kb)

Taking advantage of combining different streams using Reactive Extension's:

2011-04-04T16:18:45+01:00 by Andrea Boschin

One interesting feature of Reactive Extensions is the combining of Observables. There are a number of extension methods made to combine two or more streams; Amb, Concat, SelectMany, Merge, Zip, CombineLatest, all these methods are made to take, multiple and non necessarily omogeneous, streams and combine them in a unique resulting stream based on different rules. Here a brief resume of the rules applied from every method

Amb returns the stream that start providing values by first
Concat chain two streams one to the end of the other and create a single output
SelectMany Returns every value from the second stream for each value from the first
Merge returns the two streams merged basing of when each source returns its value
Zip returns values from one stream paired with values from another, only when a couple is available.
CombineLatest Combine two streams returning always the latest from both, for each occurrence of a value.

 

Understanding the meaning of each method is really difficult if you do not make some simple experiment, but this is out of the scope of this post. Now I would like to show the meaning of "combining two streams" with a real example that show how a little change in the previous mouse trail example can give a great difference in terms of functions.

In my last example I used the TrailWithCount and TrailWithTime methods to catch MouseMove events to draw a polyline on the plugin that il the trail of the mouse pointer. In the example you have seen the trail shortens while the mouse was moving but when the mouse stops also the trail stops. Now I want to change the example to let the trail shorten to zero length when the mouse stops moving.

To achieve this result I need to have a timer that continues to record the current position for the mouse when it stops. For this purpose I can use the static method Obsevable.Interval(timespan) that is able to generate a stream of events at the given interval of time. Here is the two lines I have to add to the previous example.

   1: Observable.FromEvent<MouseEventHandler, MouseEventArgs>(
   2:     ev => new MouseEventHandler(ev),
   3:     ev => this.LayoutRoot.MouseMove += ev,
   4:     ev => this.LayoutRoot.MouseMove -= ev)
   5:     .CombineLatest(Observable.Interval(TimeSpan.FromMilliseconds(25)), (a, b) => a)
   6:     .ObserveOnDispatcher()
   7:     .Select(o => o.EventArgs.GetPosition(this.LayoutRoot))
   8:     .TrailWithCount(100)
   9:     .Subscribe(DrawLine);

the CombineLatest method gets events from the mouse and from the time interval (this regularly every 25 milliseconds) and using the selector lambda it takes from the combined stream only the mouse events. Every time an interval expire the combined value will contain an integer (the number of intervals from the start) and the latest mouse event. When the mouse stops moving the stream from the MouseMove also stops to provide values but the CombineLatest method will replicate the latest value taken for every interval elapsed. So the trail will be feeded with the latest position and the visual effect will be the shorten of the trail until it reaches the current position of the mouse pointer.

The ObserveOnDispatched method is required because the Observable.Interval method implies the use of a separate thread so when we get the values we are in this thread and we need to marshall back to the UI thread. This method does the trick. Here is the result:

Get Microsoft Silverlight

Demo from Italy Remix 2010

2010-07-01T22:44:49+01:00 by Andrea Boschin

Last June 23 I had the pleasure of presenting an introductive session about Silverlight at . During the presentation, included in the “jump start” track, I’ve illustrated the basic capabilities of Silverlight using a simple application that consume a RSS feed from the . The feed give news about all the Earthquakes happening on the world surface and all them are geo tagged.

So, during the session, I’ve showed the application growing from a simple reader to a complex and effective tool to display the earthquakes on a map, using the Silverlight control for Bing Maps. The people was impressed by the application, so I decided to publish the sample on my blog, hoping it can become a good starting point for people wants to approach the Silverlight development.

The application is really simple, without any surprise for skilled people, but it show the main points, from where someone must start. You can see layout, shapes, brushes, animations, projections, network access, syndication and data binding, but also show the power of an Out of browser application and the customization of the window chrome. I hope you enjoy the sample.

Download: code | live demo

Silverlight 4.0 beta released

2009-11-18T18:22:15+01:00 by Andrea Boschin

Download Sample Code: SilverlightPlayground.SL4BetaTestConsole.zip (89K)

 

During the Keynote of the PDC 2009 a new beta of Silverlight has been announced and made available. I think very few people did expect the early release of the version 4.0, and if you think in terms of number of new features compared with the time passed since the RTW of Silverlight 3.0 - only four months - you understand the big work made by one of the most prolific teams of Microsoft.

In the latest month I could play with the beta bits, and I've compiled a collection of the most important features coming in this release, to understand how them works and to release some working code to let people easily learn them. This collection is linked at the end of this post in the form of a self-explaining navigation application. The application contains eleven samples that show the features I list below:

Full Trust in Out of Browser: While detaching an application to out of browser now it is possible to give full trust to the installed application. This enable huge improvements: no need of cross domain policies, access to file system, no user-initiated dialogs. You can also use COM interoperability.

WebCam: Silverlight 4.0 introduce some new API to handle video and audio capture. This sample shows how to use the CaptureSource class to detect video devices and to capture live stream and snapshots from it. The same pattern can be used to capture audio sources

WebBrowser: This new control has been added to the Silverlight bits to enable the use of html hosting into Silverlight applications. The WebBrowser control is available only when the application is running out of browser so before running the sample you need to install the application

RichTextArea: Another new control let the user enter formatted code. The RichTextArea behave like a TextBox but it can host fonts, weights, styles, and entering graphic elements and links like you can do with a text editor. The sample show also how to read the content of the RichTextArea you can populate with XAML markup.

HTML Brush: Like using a media element to publish a video on a brush with the HtmlBrush it is possible to use the output of a WebBrowser control to render the brush. The use of this feature has some limits but the code works fine.

PrintDocument: In the development of Line of Business applications, sending documents to the printer is an useful feature. Silverlight 4.0 introduce a new PrintDocument that enable sending elements of the Visual Tree to the printer.

Righ Mouse Button: In the previous releases the context menu of Silverlight prevent the use of the Right mouse button. In this release you can intercept this button and attach the logic you need. In the sample you can use left and right buttons to change the size of the circle. If you click outside the circle the normal context menu will be displayed.

DataBinding to DependencyObject: In the current version the DataBinding between elements is available only when the target inherits from FrameworkElement. This limit prevent, as an example, to bind multiple a RotateTransform to a single Slider. In Silverlight 4.0 this limit has been overcome and now it is possible to bind DependencyObjects. This is a great step in the compatibility with WPF.

Improvements to Binding: The binding markup extension has been enriched with a new set of properties which simplify the development. This include StringFormat, FallbackValue and TargetNullValue.

Commands: The controls inheriting from ButtonBase has acquired two new properties, Command and CommandParameter. It is a tiny step in the direction of MVVM programming.

Drag & Drop: With this release it is possible to detect dragging of elements on the application surface. The sample read the filename, la last access date and the size of the stream.

Notification Window: Desktop application can show a popup in the tray bar of Windows. This now is available also in Silverlight out of browser applications.

These are a huge set of features for the short period of time where they were developed. I hope many of you will find useful the code I've linked to this post. If you need help to understand the samples feel free to contact me through the contact form.

Download: SilverlightPlayground.SL4BetaTestConsole.zip (89K)

Categories:   News | Demo
Actions:   E-mail | del.icio.us | Permalink | Comments (1) | Comment RSSRSS comment feed

My Model-View-ViewModel exercise

2009-11-13T01:32:04+01:00 by Andrea Boschin

Senza-titolo-1 Some weeks ago I've worked on an exercise originally started to try writing a complete application with full Model-View-ViewModel pattern. I've created the application with Visual Studio 2008, Prism to integrate missing features and Ria Services July CTP to get access to a SQL Server 2008 Database.

The application is a little time tracker, and I've decided to attach it to this post because it was very useful to me to understand problems and missing things about the MVVM pattern.

In the next days I will write some words about these problems I found, but for now I only want to undisclose the application to let something download it and give me some comments about it.

If you decide to try the application remember to attach the database mdf in the zip file, to set the connection strings in the web.config and the credentials for reporting services if you want to setup it and finally enter "tracker" as username and p@ssw0rd as password.

I'm currently learning this pattern and I do not want to consider my implementation complete, perfect and without any error. So please let me know what do you think and how can I improve it. Thanks in advance.

Download: Elite.TimeTracker.zip (~820 Kb)

Categories:   Prism | Demo
Actions:   E-mail | del.icio.us | Permalink | Comments (2) | Comment RSSRSS comment feed

C64 Emulator Video

2009-03-23T09:37:03+01:00 by Andrea Boschin

Pete Brown has written an interesting C64 emulator that show what Silverlight 3.0 can do. The C64 Emulator he shows during the MIX09 is a generated MediaStreamSource continuously updated by the emulator runtime. This grant a very amazing fluid result. In this article a more .

Link:

Categories:   Demo
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

MIX09 Keynote Demo Available

2009-03-22T08:21:49+01:00 by Andrea Boschin

The source code of the demo showed by Scott Guthrie during the Keynote of the MIX 2009 last week has been made available by Henry Hahn. It is a very amazing demonstration on how it is possible to do with the new features of Silverlight 3.0.

The demo derive from a similar project crated the last year for MIX 08 about WPF.

ripple

| | Download Project

Categories:   Demo | Animations | Effects
Actions:   E-mail | del.icio.us | Permalink | Comments (1) | Comment RSSRSS comment feed