How can I move a piece in a two-dimensional C# array?
Asked by
MellowPine42
I'm building a chess game in Visual Studio and need to move pieces around a two-dimensional array. I can loop through the array and locate a piece, but I can't use the usual built-in array methods and I'm unsure how to transfer a value from one position to another while clearing its original position.
Answers
A move is just an assignment to the new location followed by removing the value from the old one. For example, if a piece is at [0,4] and should move to [0,7], assign the piece to [0,7], then set [0,4] to an empty value such as default or null, depending on the array's element type. You would still need separate logic to validate whether the chess move is legal.
Reply to this answer
Copy the value into the destination cell, then clear the original cell. For a rectangular two-dimensional array, that would be: board[newX,newY] = board[oldX,oldY]; board[oldX,oldY] = default; Make sure the old and new coordinates aren't identical, or you'll clear the piece immediately after copying it. If you're using a jagged array instead, use board[newX][newY] and board[oldX][oldY].
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowPine42: I hadn't seen that syntax before. I'll give it a tryโthanks!