I must say WPF is a cool thing! Have you played sometime a Fifteen Puzzle Game?
Check out this Fifteen Puzzle Game as example of WPF Animation.
So what we have here. In the MainWindow.xaml we have simple canvas:
P.S. You may also find interesting this post WPF Animation (Tower of Hanoi), which I posted earlier.
Check out this Fifteen Puzzle Game as example of WPF Animation.
So what we have here. In the MainWindow.xaml we have simple canvas:
<Grid> <Canvas Name="cnBoard" Width="240" Height="240" Background="Black" /> </Grid>And we have UserControl in ItemCntr.xaml file which we use as template for our rectangles:
<UserControl x:Class="Game15.ItemCntr" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" x:Name="c"> <UserControl.Resources> <LinearGradientBrush x:Key="discBrush" EndPoint="0,.5" SpreadMethod="Reflect"> <GradientStop Color="Wheat" Offset="0" /> <GradientStop Color="White" Offset="1" /> </LinearGradientBrush> </UserControl.Resources> <Grid> <Rectangle Stroke="Green" StrokeThickness="2" Fill="{StaticResource discBrush}" RadiusX="0" RadiusY="0" /> <TextBlock FontStyle="Normal" FontSize="20" HorizontalAlignment="Center" Name="tbVal" VerticalAlignment="Center" /> </Grid> </UserControl>The main logic is in MainWindow.cs:
private void DrawBord() { cnBoard.Children.Clear(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (Board[i, j] > 0) { ItemCntr cnv = new ItemCntr { IntVal = Board[i, j], Width = cnBoard.Width / 4, Height = cnBoard.Height / 4, I = i, J = j }; Canvas.SetTop(cnv, i * cnBoard.Width / 4); Canvas.SetLeft(cnv, j * cnBoard.Width / 4); cnBoard.Children.Add(cnv); cnv.MouseLeftButtonUp += new MouseButtonEventHandler(cnv_MouseLeftButtonUp); } } } } private void MoveItem(ItemCntr it, int i, int j) { Board[i, j] = Board[it.I, it.J]; Board[it.I, it.J] = 0; Storyboard sb = new Storyboard(); DoubleAnimation da = new DoubleAnimation(); if (i == it.I) { da.From = it.J * it.Width; da.By = j * it.Width - da.From; } else { da.From = it.I * it.Height; da.By = i * it.Height - da.From; } da.Duration = new Duration(TimeSpan.FromSeconds(.2)); sb.Children.Add(da); object prop = it.I == i ? Canvas.LeftProperty : Canvas.TopProperty; Storyboard.SetTargetProperty(da, new PropertyPath(prop)); sb.Begin(it, true); sb.Completed += new EventHandler(sb_Completed); it.I = i; it.J = j; }Download the code source (Visual Studio 2010 Project).
P.S. You may also find interesting this post WPF Animation (Tower of Hanoi), which I posted earlier.
No comments:
Post a Comment