开发者

Chess Logic in XNA

开发者 https://www.devze.com 2022-12-13 03:51 出处:网络
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

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消