Creating chess GUI in WPF - wpf

Firstly: apologies if this is a duplicate post. Things got a bit confusing as I'm trying to post/register at same time.
I started investigating running UCI chess engines from a simple WPF window, got the hang of having the chess engine running onf a different thread to the interface, and have created a reasonably servcieable text-based front end.
I'm getting a bit more ambitious now, and would like to start building a GUI with chess pieces on it that will feed the player's moves to the chess engine, and represent the engine's moves on the board as well. I'm aiming for draggable pieces rather than clicking squares.
My current attempts involve using draggable user controls for the pieces on a <canvas> element. I'd be really interested to hear how other, more experienced WPF/.NET programmers would approach this, as I'm not entirely convinced I'm on the right track.
For example: would it be better to use a uniform grid and drag piece data between child elements? Should I create an abstract 'piece' class from which pieces such as pawns could derive? That kind of thing.
Any thoughts? This isn't a homework assignment or anything, just something I'm noodling around with in my spare time as an exercise.

I have implemented a chess board for my Silverlight Online Chess system.
Here is how I did it.
I made a seperate user control for the chess board
I added a grid 8x8 onto the control
I then added 64 Borders shading each one a different color (dark squares and light squares) Make sure to name each one. Each of the borders were placed on the grid using the Grid.Row and Grid.Col properties.
Within each Border I added an Image that will hold the chess piece image.
You will have to code some methods around setting the image to the correct chess piece based on your current game state.
Each of the Images received the same event (this is important), all 64 call the same piece of code:
MouseLeftButtonDown="Image_MouseLeftButtonDown"
MouseMove="Image_MouseMove"
MouseLeftButtonUp="Image_MouseLeftButtonUp"
The idea behind these 3 events is that we record when I click on the image (MouseLeftButtonDown) that gets me the origin of the click, then I call the event as the mouse is moving, that allows me to update the screen as the piece is moving, and the last event I record when I let go of the mouse button (MouseLeftButtonUp), this allows me to get the destination and send the move to my chess engine. Once the move is recorded by the chess engine I just redraw the chess board.
private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Image image = (Image)sender;
Border border = (Border)image.Parent;
image.CaptureMouse();
isMouseCapture = true;
mouseXOffset = e.GetPosition(border).X;
mouseYOffset = e.GetPosition(border).Y;
var chessPiece = (Image) sender;
var chessSquare = (Border) chessPiece.Parent;
var row = (byte) (Grid.GetRow(chessSquare));
var column = (byte) (Grid.GetColumn(chessSquare) - 1);
if (engine.HumanPlayer == ChessPieceColor.White)
{
SelectionChanged(row, column, false);
}
else
{
SelectionChanged((byte)(7 - row), (byte)(7 - column), false);
}
}
SelectionChanged is my own method for recording what source square the user selected.
isMouseCapture is also my own variable for recording when the user started draging the piece.
private void Image_MouseMove(object sender, MouseEventArgs e)
{
Image image = (Image)sender;
Border border = (Border)image.Parent;
if (!currentSource.Selected)
{
image.ReleaseMouseCapture();
isMouseCapture = false;
translateTransform = new TranslateTransform();
translateTransform.X = 0;
translateTransform.Y = 0;
mouseXOffset = 0;
mouseYOffset = 0;
}
if (isMouseCapture)
{
translateTransform = new TranslateTransform();
translateTransform.X = e.GetPosition(border).X - mouseXOffset;
translateTransform.Y = e.GetPosition(border).Y - mouseYOffset;
image.RenderTransform = translateTransform;
CalculateSquareSelected((int)translateTransform.X, (int)translateTransform.Y, false);
}
}
In the above CalculareSquareSelected converts the pixels moved to where I think the piece is moving to in the 8x8 chess board. For example say I moved 100 pixels and the chess board square is only 50 pixels than I moved 2 chess board squares.
private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (translateTransform == null)
{
return;
}
Image image = (Image)sender;
image.ReleaseMouseCapture();
isMouseCapture = false;
if (translateTransform.X > 10 || translateTransform.Y > 10 || translateTransform.X < -10 || translateTransform.Y < -10)
{
CalculateSquareSelected((int)translateTransform.X, (int)translateTransform.Y, true);
}
translateTransform = new TranslateTransform();
translateTransform.X = 0;
translateTransform.Y = 0;
mouseXOffset = 0;
mouseYOffset = 0;
image.RenderTransform = translateTransform;
}
If you have any questions feel free to contact me.

Related

WPF, rendering a million polygons, nVidia Quardro K2200

I need to display more than a million polygons on a usercontrol to display CAD inquiry. Because I need to be able to zoom in to view the polygons, they can't be drawn onto a bitmap. So in the OnRender override, I use StreamGeometry, StreamGeometryContext to generate polygon geometry. I was surprised how little WPF takes advantages of the powerful nVidia GPU. On the nVidia Control Panel, Workstation, Manage GPU Utilization, I can monitor how many % the GPU has been tapped. During rendering, it routinely uses less than 30% during the OnRender call. After the end of the OnRender, no GPU has been use and the CPU is still clunking away data in the background trying to display. After the polygons are drawn, it becomes impossible to scroll (the control is in a ScrollViewer), change opacity, etc. These operations do not tap into any of the GPU resources either. My only solution so far is set the usercontrol's CacheMode = new BitmapCache(8).
How can I let WPF uses the GPU in this case?
for (int j = 0; j < Data.Count; j++)
{
StreamGeometry geometry = new StreamGeometry();
geometry.FillRule = FillRule.Nonzero;
using (StreamGeometryContext context = geometry.Open())
{
...
{
Point startPoint = new Point(aPolygon[0].X, aPolygon[0].Y);
List<Point> points = new List<Point>();
//draw polygons
bool isPolygonViewAble = false;
if (viewingRect.Contains(startPoint)) isPolygonViewAble = true;
for (int i = 1; i < aPolygon.Count; i++) //foreach (CADGlobal.aPoint pt in polygon)
{
Point apoint = new Point(aPolygon[i].X, aPolygon[i].Y);
if (viewingRect.Contains(apoint)) isPolygonViewAble = true;
points.Add(apoint);
}
if (isPolygonViewAble)
{
context.BeginFigure(startPoint, true, true);
context.PolyLineTo(points, true, false);
}
}
}
geometry.Freeze();
dc.DrawGeometry(null, pen, geometry); //place null with a brush to fill

Snapping a SurfaceListBox

I'm looking to create a scrolling surfacelistbox which automatically snaps into a position after a drag is finished so that the center item on the screen is centered itself in the viewport.
I've gotten the center item, but now as usual the way that WPF deals with sizes, screen positions, and offsets has me perplexed.
At the moment I've chosen to subscribe to the SurfaceScrollViewer's ManipulationCompleted event, as that seems to consistently fire after I've finished a scroll gesture (whereas the ScrollChanged event tends to fire early).
void ManipCompleted(object sender, ManipulationCompletedEventArgs e)
{
FocusTaker.Focus(); //reset focus to a dummy element
List<FrameworkElement> visibleElements = new List<FrameworkElement>();
for (int i = 0; i < List.Items.Count; i++)
{
SurfaceListBoxItem item = List.ItemContainerGenerator.ContainerFromIndex(i) as SurfaceListBoxItem;
if (ViewportHelper.IsInViewport(item) && (List.Items[i] as string != "Dummy"))
{
FrameworkElement el = item as FrameworkElement;
visibleElements.Add(el);
}
}
int centerItemIdx = visibleElements.Count / 2;
FrameworkElement centerItem = visibleElements[centerItemIdx];
double center = ss.ViewportWidth / 2;
//ss is the SurfaceScrollViewer
Point itemPosition = centerItem.TransformToAncestor(ss).Transform(new Point(0, 0));
double desiredOffset = ss.HorizontalOffset + (center - itemPosition.X);
ss.ScrollToHorizontalOffset(desiredOffset);
centerItem.Focus(); //this also doesn't seem to work, but whatever.
}
The list snaps, but where it snaps seems to be somewhat chaotic. I have a line down the center of the screen, and sometimes it looks right down the middle of the item, but other times it's off to the side or even between items. Can't quite nail it down, but it seems that the first and fourth quartile of the list work well, but the second and third are progressively more off toward the center.
Just looking for some help on how to use positioning in WPF. All of the relativity and the difference between percentage-based coordinates and 'screen-unit' coordinates has me somewhat confused at this point.
After a lot of trial and error I ended up with this:
void ManipCompleted(object sender, ManipulationCompletedEventArgs e)
{
FocusTaker.Focus(); //reset focus
List<FrameworkElement> visibleElements = new List<FrameworkElement>();
for (int i = 0; i < List.Items.Count; i++)
{
SurfaceListBoxItem item = List.ItemContainerGenerator.ContainerFromIndex(i) as SurfaceListBoxItem;
if (ViewportHelper.IsInViewport(item))
{
FrameworkElement el = item as FrameworkElement;
visibleElements.Add(el);
}
}
Window window = Window.GetWindow(this);
double center = ss.ViewportWidth / 2;
double closestCenterOffset = double.MaxValue;
FrameworkElement centerItem = visibleElements[0];
foreach (FrameworkElement el in visibleElements)
{
double centerOffset = Math.Abs(el.TransformToAncestor(window).Transform(new Point(0, 0)).X + (el.ActualWidth / 2) - center);
if (centerOffset < closestCenterOffset)
{
closestCenterOffset = centerOffset;
centerItem = el;
}
}
Point itemPosition = centerItem.TransformToAncestor(window).Transform(new Point(0, 0));
double desiredOffset = ss.HorizontalOffset - (center - itemPosition.X) + (centerItem.ActualWidth / 2);
ss.ScrollToHorizontalOffset(desiredOffset);
centerItem.Focus();
}
This block of code effectively determines which visible list element is overlapping the center line of the list and snaps that element to the exact center position. The snapping is a little abrupt, so I'll have to look into some kind of animation, but otherwise I'm fairly happy with it! I'll probably use something from here for animations: http://blogs.msdn.com/b/delay/archive/2009/08/04/scrolling-so-smooth-like-the-butter-on-a-muffin-how-to-animate-the-horizontal-verticaloffset-properties-of-a-scrollviewer.aspx
Edit: Well that didn't take long. I expanded the ScrollViewerOffsetMediator to include HorizontalOffset and then simply created the animation as suggested in the above post. Works like a charm. Hope this helps someone eventually.
Edit2: Here's the full code for SnapList:
SnapList.xaml
SnapList.xaml.cs
Note that I got pretty lazy as this project went on an hard-coded some of it. Some discretion will be needed to determine what you do and don't want from this code. Still, I think this should work pretty well as a starting point for anyone who wants this functionality.
The code has also changed from what I pasted above; I found that using Windows.GetWindow gave bad results when the list was housed in a control that could move. I made it so you can assign a control for your movement to be relative to (recommended that be the control just above your list in the hierarchy). I think a few other things changed as well; I've added a lot of customization options including being able to define a custom focal point for the list.

Custom panel layout doesn't work as expected when animating (WPF)

I've got a custom (and getting complex) TabControl. It's a gathering of many sources, plus my own wanted features. In it is a custom Panel to show the headers of the TabControl. Its features are to compress the size of the TabItems until they reached their minimum, and then activates scrolling features (in the Panel, again). There is also another custom panel to hold a single button, that renders on the right of the TabItems (it's a "new tab" button).
It all works great, until I try to animate the scrolling.
Here are some relevant snippets :
In the CustomTabPanel (C#, overriding Panel and implementing IScrollInfo):
private readonly TranslateTransform _translateTransform = new TranslateTransform();
public void LineLeft()
{
FirstVisibleIndex++;
var offset = HorizontalOffset + _childRects[0].Width;
if (offset < 0 || _viewPort.Width >= _extent.Width)
offset = 0;
else
{
if (offset + _viewPort.Width > _extent.Width)
offset = _extent.Width - _viewPort.Width;
}
_offset.X = offset;
if (_scrollOwner != null)
_scrollOwner.InvalidateScrollInfo();
//Animate the new offset
var aScrollAnimation = new DoubleAnimation(_translateTransform.X, -offset,
new Duration(this.AnimationTimeSpan), FillBehavior.HoldEnd) { AccelerationRatio = 0.5, DecelerationRatio = 0.5 };
aScrollAnimation.Completed += ScrollAnimationCompleted;
_translateTransform.BeginAnimation(TranslateTransform.XProperty, aScrollAnimation , HandoffBehavior.SnapshotAndReplace);
//End of animation
// These lines are the only ones needed if we remove the animation
//_translateTransform.X = -offset;
//InvalidateMeasure();
}
void ScrollAnimationCompleted(object sender, EventArgs e)
{
InvalidateMeasure();
}
the _translateTransform is initialized in the constructor :
base.RenderTransform = _translateTransform;
Again, everything is fine if I remove the animation part and just replace it with the commented out lines at the end.
I must also point out that the problem is NOT with the animation itself. That part works out well. The problem is about when I remove some tab items : all the layout then screws up. The TranslateTransformation seems to hold on some wrong value, or something.
Thanks in advance.
Well. As it's often the case, I kept working on the thing, and... answered myself.
Could still be useful for other people, so here was the catch. In the line :
var aScrollAnimation = new DoubleAnimation(_translateTransform.X, -offset, new Duration(this.AnimationTimeSpan), FillBehavior.HoldEnd)
{ AccelerationRatio = 0.5, DecelerationRatio = 0.5 };
the FillBehavior should have been FillBehavior.Stop.
As easy as that!

Creating a Chess Board using Windows Forms

What is the best way to create chess board using Windows Forms?
I am still new to graphics coding in winforms and I am not sure, which control to use for that?
The user should be able to put chess pieces into the board.
I am trying to write Chess Diagram Editor.
Thank you
There are a lot of ways. Here's an alternative that gets you started with some WinForms concepts:
(It uses a 2D grid of Panel controls to create a chessboard. To extend it you might change the background picture of each Panel to show chess pieces. The game play is up to you to define.)
// class member array of Panels to track chessboard tiles
private Panel[,] _chessBoardPanels;
// event handler of Form Load... init things here
private void Form_Load(object sender, EventArgs e)
{
const int tileSize = 40;
const int gridSize = 12;
var clr1 = Color.DarkGray;
var clr2 = Color.White;
// initialize the "chess board"
_chessBoardPanels = new Panel[gridSize, gridSize];
// double for loop to handle all rows and columns
for (var n = 0; n < gridSize; n++)
{
for (var m = 0; m < gridSize; m++)
{
// create new Panel control which will be one
// chess board tile
var newPanel = new Panel
{
Size = new Size(tileSize, tileSize),
Location = new Point(tileSize * n, tileSize * m)
};
// add to Form's Controls so that they show up
Controls.Add(newPanel);
// add to our 2d array of panels for future use
_chessBoardPanels[n, m] = newPanel;
// color the backgrounds
if (n % 2 == 0)
newPanel.BackColor = m % 2 != 0 ? clr1 : clr2;
else
newPanel.BackColor = m % 2 != 0 ? clr2 : clr1;
}
}
}
Best way is to use a 'chess starter kit': http://www.chessbin.com/page/Chess-Game-Starer-Kit.aspx (alternative project: http://www.codeproject.com/KB/game/SrcChess.aspx)
Nowadays a lot of things have starter kits (for C#) which gives you a sample to get started on.
In the controls OnPaint eventhandler, you start out by drawing the chessboard pattern either implicitly using the formula (floor(x * 8) mod 2) = (floor(y * 8) mod 2) or by just drawing the squares with Graphics.FillRectangle. The second step would be to draw the pieces on top with Graphics.DrawImage.
I don't know what you want to do with this chess board, but if it's only a background to display after pieces, your best shot is to set a background image.

Selecting an object on a WPF Canvas?

I have a WPF Canvas with some Ellipse objects on it (displayed as circles). Each circle is from a collection class instance which is actually a custom hole pattern class. Each pattern has a certain number of circles, and each circle then gets added to the canvas using an iteration over the collection using the code below.
So, the canvas is populated with a bunch of circles and each circle belongs to a certain pattern instance. You can see a screenshot here: http://twitpic.com/1f2ci/full
Now I want to add the ability to click on a circle on the canvas, and be able to determine the collection it belongs to, so that I can then do some more work on the selected pattern to which that circle belongs.
public void DrawHoles()
{
// Iterate over each HolePattern in the HolePatterns collection...
foreach (HolePattern HolePattern in HolePatterns)
{
// Now iterate over each Hole in the HoleList of the current HolePattern...
// This code adds the HoleEntity, HoleDecorator, and HoleLabel to the canvas
foreach (Hole Hole in HolePattern.HoleList)
{
Hole.CanvasX = SketchX0 + (Hole.AbsX * _ZoomScale);
Hole.CanvasY = SketchY0 - (Hole.AbsY * _ZoomScale);
canvas1.Children.Add(Hole.HoleEntity);
}
}
}
All FrameworkElements have a Tag property which is of type object that can be used to hold arbitrary information. You could assign the HolePattern to the Tag property and easily use that later to get the associated collection.
i.e.:
...
Hole.HoleEntity.Tag = HolePattern as object;
canvas1.Children.Add(Hole.HoleEntity);
later on in the click event:
event(object sender,....)
{
Ellipse e = sender as Ellipse;
HolePattern hp = e.Tag as HolePattern;
...
}
So you probably already read my reply where I said I had it working. And it does work perfectly, (except that it requires great precision with the mouse), but I want to ask this: is it really smart to add an event handler to EVERY ellipse that gets added to a canvas? Now I don't know what kind of memory bog that could be, or maybe it is a piece of cake for WPF and Windows to handle.
In a practical case, I guess there would be not more that 30-50 holes even on a screen that had multiple patterns, but still; FIFTY event handlers? It just seems scary. And actually, each "Hole" is visually represented by two concentric circles and a text label (see the screenshow here: http://twitpic.com/1f2ci/full ), and I know the user would expect to be able to click on any one of those elements to select a hole. That means an event handler on 3 elements for every hole. Now we could be talking about 100 or more event handlers.
It seems like there should be a solution where you could have just one event handler on the Canvas and read the element reference under the mouse, then work off of that to get the .Tag property of that elment, and so on.
I thought I'd post my final and more refined solution in case it helps anyone else.
void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
int ClickMargin = 2;// Adjust here as desired. Span is in both directions of selected point.
var ClickMarginPointList = new Collection<Point>();
Point ClickedPoint = e.GetPosition(canvas1);
Point ClickMarginPoint=new Point();
for (int x = -1 * ClickMargin; x <= ClickMargin; x++)
{
for (int y = -1 * ClickMargin; y <= ClickMargin; y++)
{
ClickMarginPoint.X = ClickedPoint.X + x;
ClickMarginPoint.Y = ClickedPoint.Y + y;
ClickMarginPointList.Add(ClickMarginPoint);
}
}
foreach (Point p in ClickMarginPointList)
{
HitTestResult SelectedCanvasItem = System.Windows.Media.VisualTreeHelper.HitTest(canvas1, p);
if (SelectedCanvasItem.VisualHit.GetType().BaseType == typeof(Shape))
{
var SelectedShapeTag = SelectedCanvasItem.VisualHit.GetValue(Shape.TagProperty);
if (SelectedShapeTag!=null && SelectedShapeTag.GetType().BaseType == typeof(Hole))
{
Hole SelectedHole = (Hole)SelectedShapeTag;
SetActivePattern(SelectedHole.ParentPattern);
SelectedHole.ParentPattern.CurrentHole = SelectedHole;
return; //Get out, we're done.
}
}
}
}

Resources