using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace SilverlightHelloWorld
{
public partial class Page : UserControl
{
// private Storyboard _timer = new Storyboard();
private DispatcherTimer _timer;
private List<Cell> cells = new List<Cell>(); // list of all cells
private int _xSize = 26; // width of the grid, in number of cells
private int _ySize = 7; // height of the grid
private int _numCells; // total number of cells
private int _cellIdx = 0;
/// <summary>Represents a cell on the grid</summary>
private class Cell
{
public double X; // x-coordinate of cell
public double Y; // y-coordinate
public bool On; // True if cell is "on"
public double Order; // Display order
}
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
// Assign a random value to each cell
Random rnd = new Random(Environment.TickCount);
_numCells = (int)(_xSize * _ySize);
string template = " "
+ " x x xxxx x x xx "
+ " x x x x x x x "
+ " xxxx xxxx x x x x "
+ " x x x x x x x "
+ " x x xxxx xxxx xxxx xx "
+ " ";
for (int y = 0; y < _ySize; y++)
{
for (int x = 0; x < _xSize; x++)
{
Cell cell = new Cell();
cell.X = x * (this.Width / _xSize);
cell.Y = y * (this.Height / _ySize);
cell.Order = rnd.NextDouble();
cells.Add(cell);
}
}
for (int i = 0; i < template.Length; i++)
{
cells[i].On = template[i] == 'x';
}
// Sort the cells by the random values
cells.Sort(
delegate(Cell c0, Cell c1)
{
return c0.Order.CompareTo(c1.Order);
}
);
_timer = new System.Windows.Threading.DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(1);
_timer.Tick += new EventHandler(timer_Completed);
_timer.Start();
}
void timer_Completed(object sender, EventArgs e)
{
if (_cellIdx < _numCells)
{
// Get the next cell
Cell cell = cells[_cellIdx];
// Draw the cell
Rectangle r = new Rectangle();
r.Stroke = new SolidColorBrush(Colors.DarkGray);
if (cell.On)
{
r.Fill = new SolidColorBrush(Colors.Red);
}
else
{
r.Fill = new SolidColorBrush(Colors.LightGray);
}
r.Width = this.Width / _xSize;
r.Height = this.Height / _ySize;
r.SetValue(Canvas.LeftProperty, cell.X);
r.SetValue(Canvas.TopProperty, cell.Y);
MyCanvas.Children.Add(r);
_cellIdx++;
}
else
{
_timer.Stop();
}
}
}
}