How can I move a piece within a two-dimensional C# array?

0
1
Asked By MellowPine42 On

I'm building a chess game in Visual Studio and need to move pieces around a two-dimensional array. I understand how to loop through the board and locate a piece, but I'm not sure how to transfer it from its current coordinates to a new position. I also need to avoid using the array helper methods.

3 Answers

Answered By AmberKite88 On

Think of a move as two assignments: put the piece at its new square, then clear the square it came from. For example, moving a queen from [0,4] to [0,7] means assigning board[0,7] from board[0,4], followed by resetting board[0,4]. Chess-specific validation, such as checking whether the move is legal, should happen before these assignments.

Answered By CobaltMango7 On

For a rectangular two-dimensional array, copy the value from the old coordinates to the destination, then clear the old position:

board[newX, newY] = board[oldX, oldY];
board[oldX, oldY] = default;

You should first check whether the old and new coordinates are different. Otherwise, you would copy the piece onto itself and then erase it. If the destination contains an opposing piece, assigning to it will replace it, which handles a capture.

Answered By QuietOrbit3 On

If your board is a jagged array, use the other indexing syntax: board[newX][newY] and board[oldX][oldY]. For a normal rectangular array declared with something like int[,] or Piece[,], use board[newX, newY] and board[oldX, oldY].

MellowPine42 -

Thanks, I hadn’t seen the comma-versus-brackets difference before. I’ll check which kind of array I declared.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.