tags:

views:

334

answers:

1
+1  Q: 

Chess Logic in XNA

So I've created a 2D chess game board with all the pieces on it using the XNA library and all. However I don't know how to make the pieces move if I click them. This is what I have for the logic of one of the knight pieces.

if(mouse.LeftButton == ButtonState.Pressed 
      && mouse.X == wknight1.position.X 
      && mouse.Y == wknight1.position.Y)
{
}

How do I select the piece then allow it to move?

+3  A: 

I'm not familiar with XNA specifically but I'll give a few suggestions. For one thing, you probably want to keep the pieces in a 2D array or similar rather than having them in their own variables (like wknight1). Otherwise you'll have to check every variable every time the user clicks.

I'm assuming you want a system where the user clicks a piece to select it, then clicks an empty square to move it there. Here's some pseudo-code for something like that (I'm using a null board location to mean an empty square here):

if(mouse.LeftButton == ButtonState.Pressed
  && board[mouse.x][mouse.y] != null && pieceSelected == null)
{
    pieceSelected = board[mouse.x][mouse.y];
    selectedX = mouse.x;
    selectedY = mouse.y
}
else if (mouse.LeftButton == ButtonState.Pressed
  && board[mouse.x][mouse.y] == null && pieceSelected != null)
{
    board[selectedX][selectedY] == null;
    board[mouse.x][mouse.y] = pieceSelected;
    pieceSelected = null;
}

You can add in further conditions like isAValidMove(pieceType, startx, starty, finishx, finishy) where you check that the player is trying to move their own piece and that it's a legal chess move etc. You could probably make this more elegant and OO (and/or event-driven) too (and add click-and-dragging etc) but I'm keeping it simple to illustrate the basic logic.

Ryan
how do i setup the 2d array to hold all the pieces? i have sprite images for all of them.
Sankar
The array doesn't actually hold the images of the pieces or whatever, it holds a logical reference to the pieces (whether a string like "white_knight", or a custom Piece object, or even just a number). Then you can know how to render the graphical board by looking at the board array. Basically, the board array is a logical *model* of the game-state, and the graphical display is a *view* of that gamestate. You should try to avoid mixing up the model and view too much - keeping them separate will make it easier to change things later on.
Ryan