Click here to Skip to main content
15,881,455 members
Articles / Web Development / ASP.NET

Silverlight Alien Sokoban

Rate me:
Please Sign up or sign in to vote.
4.88/5 (59 votes)
11 Nov 200717 min read 133.6K   1K   138  
A fun Silverlight implementation of the game Sokoban. Contrasting Silverlight 1.1 and WPF, while showcasing some new features of C# 3.0, Expression Design, Expression Blend, and Visual Studio 2008.
/*	<File>
		<Author Name="Daniel Vaughan" Email="dbvaughan NOSPAM at NOSPAM gmail NOSPAM dot NOSPAM com"/>
		<CreationDate>2007/11/5 12:10</CreationDate>
		<LastSubmissionDate>$Date: $</LastSubmissionDate>
		<Version>$Revision: $</Version>
		<License>
Copyright © 2007, Daniel Vaughan
All rights reserved.
http://www.orpius.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither Daniel Vaughan, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written 
permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
		</License>
	</File>
*/

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Orpius.Sokoban.Controls
{
	/// <summary>
	/// Displays a <see cref="Orpius.Sokoban.Cell"/> 
	/// and any <see cref="Orpius.Sokoban.Cell"/> that the cell has.
	/// </summary>
	public class CellControl : Control
	{
		readonly Cell cell;
		readonly FrameworkElement root;
		readonly Canvas rootCanvas;
		readonly Canvas wallCell;
		readonly Canvas floorCell;
		readonly Canvas floorCellHighlight;
		readonly Canvas goalActiveCellContent;
		readonly Canvas goalCellContent;
		readonly Canvas playerCellContent;
		readonly Canvas treasureCellContent;
		readonly ScaleTransform scale;

		/// <summary>
		/// Gets the cell that this control displays.
		/// </summary>
		/// <value>The cell.</value>
		public Cell Cell
		{
			get
			{
				return cell;
			}
		}

		/// <summary>
		/// Gets or sets the distance from left 
		/// of the enclosing canvas.
		/// </summary>
		/// <value>The left.</value>
		public double Left
		{
			get
			{
				return (double)GetValue(Canvas.LeftProperty);
			}
			set
			{
				SetValue(Canvas.LeftProperty, value);
			}
		}

		/// <summary>
		/// Gets the distance from the top 
		/// of the enclosing canvas.
		/// </summary>
		/// <value>The top.</value>
		public double Top
		{
			get
			{
				return (double)GetValue(Canvas.TopProperty);
			}
			set
			{
				SetValue(Canvas.TopProperty, value);
			}
		}

		public new double Width
		{
			get
			{
				return base.Width;
			}
		}

		/// <summary>
		/// Gets the height of the control.
		/// </summary>
		/// <value>The height.</value>
		public new double Height
		{
			get
			{
				return base.Height;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="CellControl"/> class.
		/// </summary>
		/// <param name="cell">The associated game cell.</param>
		/// <exception cref="ArgumentNullException">If cell is null.</exception>
		public CellControl(Cell cell)
		{
			if (cell == null)
			{
				throw new ArgumentNullException("cell");
			}

			this.cell = cell;

			System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("Orpius.Sokoban.Controls.CellControl.xaml");
			root = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());
			
			scale = new ScaleTransform() { ScaleX = 1, ScaleY = 1 };
			rootCanvas = (Canvas)root.FindName("Cell_design");
			rootCanvas.RenderTransform = scale;

			/* Assign the canvas items. */
			wallCell = (Canvas)root.FindName("WallCellBrush");
			floorCell = (Canvas)root.FindName("FloorCellBrush");
			floorCellHighlight = (Canvas)root.FindName("FloorCellHighlightBrush");
			goalActiveCellContent = (Canvas)root.FindName("GoalActiveCellContentBrush");
			goalCellContent = (Canvas)root.FindName("GoalCellContentBrush");
			playerCellContent = (Canvas)root.FindName("PlayerCellContentBrush");
			treasureCellContent = (Canvas)root.FindName("TreasureCellContentBrush");

			wallCell.Visibility = floorCell.Visibility = goalActiveCellContent.Visibility
				= goalCellContent.Visibility = treasureCellContent.Visibility = Visibility.Collapsed;

			/* The dimensions of the root canvas are undefined
			 in the Expression Design export. Thus we set them here
			 so that we may scale the control. 800 / .05 = 40 
			 */
			rootCanvas.Width = rootCanvas.Height = 800;
			scale.ScaleX = .05;
			scale.ScaleY = .05;

			base.Width = base.Height = 40;


			cell.PropertyChanged += new PropertyChangedEventHandler(cell_PropertyChanged);
			MouseLeftButtonUp += new MouseEventHandler(CellControl_MouseLeftButtonUp);
			MouseEnter += new MouseEventHandler(CellControl_MouseEnter);
			MouseLeave += new EventHandler(CellControl_MouseLeave);
			
			UpdateDisplay();
		}

		void CellControl_MouseLeftButtonUp(object sender, MouseEventArgs e)
		{
			OnClick(e);
		}

		void cell_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "CellContents":
//					if (cell.CellContents == null)
//					{
//						goalActiveCellContent.Visibility =
//							goalActiveCellContent.Visibility =
//							goalActiveCellContent.Visibility = Visibility.Collapsed;
//					}
					UpdateDisplay();
					break;
			}
		}

		void Resize()
		{
			/* Set the scale using the base width and the rootCanvas width.
			 The rootCanvas width doesn't change, but the base.Width and Height does. */
			double scaleWidth = base.Width / rootCanvas.Width;
			double scaleHeight = base.Height / rootCanvas.Height;
			double scaleAmount = scaleWidth > scaleHeight ? scaleHeight : scaleWidth;
			scale.ScaleX = scale.ScaleY = scaleAmount;
		}

		/// <summary>
		/// Sets the size of the control.
		/// This is used rather than setting the Width and Height
		/// individually because a single change would require 
		/// an assumption to retain the aspect ration.
		/// </summary>
		/// <param name="size">The size.</param>
		public void SetSize(Size size)
		{
			base.Width = size.Width;
			base.Height = size.Height;
			Resize();
		}

		/// <summary>
		/// Shows and hides canvases depending on the cell 
		/// and the cell's contents' state.
		/// </summary>
		void UpdateDisplay()
		{
			wallCell.Visibility = cell is WallCell
				? Visibility.Visible : Visibility.Collapsed;

			floorCellHighlight.Visibility = hasMouse && (cell is FloorCell || cell is GoalCell)
				? Visibility.Visible : Visibility.Collapsed;

			floorCell.Visibility = cell is FloorCell
				? Visibility.Visible : Visibility.Collapsed;

			treasureCellContent.Visibility = cell.CellContents is Treasure
				? Visibility.Visible : Visibility.Collapsed;

			playerCellContent.Visibility = cell.CellContents is Actor
				? Visibility.Visible : Visibility.Collapsed;

			goalCellContent.Visibility = cell is GoalCell && !(cell.CellContents is Treasure) 
				? Visibility.Visible : Visibility.Collapsed;

			goalActiveCellContent.Visibility = cell is GoalCell && cell.CellContents is Treasure
				? Visibility.Visible : Visibility.Collapsed;
		}
		
		bool hasMouse;

		void CellControl_MouseLeave(object sender, EventArgs e)
		{
			hasMouse = false;
			UpdateDisplay();
		}

		void CellControl_MouseEnter(object sender, MouseEventArgs e)
		{
			hasMouse = true;
			UpdateDisplay();
		}

		#region Click event
		event MouseEventHandler click;

		/// <summary>
		/// Occurs when the cell is clicked.
		/// </summary>
		public event MouseEventHandler Click
		{
			add
			{
				click += value;
			}
			remove
			{
				click -= value;
			}
		}

		/// <summary>
		/// Raises the <see cref="E:Click"/> event.
		/// </summary>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		protected void OnClick(MouseEventArgs e)
		{
			if (click != null)
			{
				click(this, e);
			}
		}
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Engineer
Switzerland Switzerland
Daniel is a former senior engineer in Technology and Research at the Office of the CTO at Microsoft, working on next generation systems.

Previously Daniel was a nine-time Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company.

Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.

Daniel is the developer behind several acclaimed mobile apps including Surfy Browser for Android and Windows Phone. Daniel is the creator of a number of popular open-source projects, most notably Codon.

Would you like Daniel to bring value to your organisation? Please contact

Blog | Twitter


Xamarin Experts
Windows 10 Experts

Comments and Discussions