Reputation: 27
Im new to the coding world and have begun coding a chess board with XNA in C#. I got this piece of code that I think should be put in a method to reduce clutter and increase efficiency but Im not really sure how.
if (movement.isSelected == false)
{
if (movement.PawnBl1pos.X <= movement.mouseCord.X
&& movement.PawnBl1pos.X + 100 >= movement.mouseCord.X
&& movement.PawnBl1pos.Y <= movement.mouseCord.Y
&& movement.PawnBl1pos.Y + 100 >= movement.mouseCord.Y)
{
movement.PawnBl1Col = Color.Red;
movement.isSelected = true;
}
}
I got 32 different sprites and the current plan is to copy that code for each sprite. movement.PawnBl1pos is the Vector2 for the 1st Black Pawn, and all I would have to do is replace the vectors for each piece.
Is it possible to make this bit of code change for each piece without a simple copy paste? Im pretty sure the term for this would be polymorphism?
(movement.PawnBl1pos.X <= movement.mouseCord.X
&& movement.PawnBl1pos.X + 100 >= movement.mouseCord.X
&& movement.PawnBl1pos.Y <= movement.mouseCord.Y
&& movement.PawnBl1pos.Y + 100 >= movement.mouseCord.Y)
Upvotes: 1
Views: 239
Reputation: 11252
The concept you need to learn is arrays.
Each square on the chess board should be a member of an array of squares. You should have 64 squares. You could represent each square by a class you define.
Each chess piece can also be represented by a class and each one would be a member of an array. The cleanest way to do it would be to define a base class and then derive from it for each piece.
Square[] squares = new Square[64];
public class Square
{
public Point Location { get; set; }
public Piece Resident { get; set; }
}
public enum TeamColor
{
Red,
Black
}
public abstract class Piece
{
public TeamColor Color { get; set; }
public Square Location { get; set; }
public abstract Square[] MovesAllowed(Square[] allSquares);
}
public class King : Piece
{
public override Square[] MovesAllowed(Square[] allSquares)
{
...
}
}
This way each type of piece (King, Queen, Pawn, etc) can calculate their own possible moves and you don't need to check what type of piece it is, you just have an array of Pieces.
Upvotes: 2
Reputation: 5514
You should store your pieces in an array, and then loop over that array. Copying some code 32 times is never a good idea..!
Upvotes: 2