I'm creating a chess game, I already created the rook's and the bishop's and I'm about to start creating the queen piece. The problem is that the queen combines the moves of the rook's and the bishop's, so I don't want to write repetitive code and instead just use the 2 classes for the rook's and the bishop's and they're methods into the queen one.
Here's the bishop class
public class OficerPiece : Figure
{
public OficerPiece(FigureDefinition definition) : base(definition)
{
}
protected override List<Tuple<int, int>> GetValidTurns()
{
//here i set the valid moves
}
}
The rook class is basically the same but with different implementation of the GetValidTurns()
Every single piece in my project inherits the Figure
abstract class which contains info that every piece is using the only difference is in the GetValidTurns
method so we leave that for the derived class to implement.
That's the queen class
public class Kralica : Figure
{
public Kralica(FigureDefinition definition) : base(definition)
{
}
protected override List<Tuple<int, int>> GetValidTurns()
{
//here i want to combine the 2 methods GetValidTurns from the bishop class and the rook class
}
}
You can create a new class or interface for your valid turns to encapsulate them and make it easy to reuse.
public interface ValidTurn
{
List<Tuple<int, int>> GetValidTurns();
}
public class StraightSlide : ValidTurn
{
public List<Tuple<int, int>> GetValidTurns()
{
// ... valid rook turns here
}
}
public class DiagonalSlide : ValidTurn
{
public List<Tuple<int, int>> GetValidTurns()
{
// ... valid bishops turns here
}
}
public class Kralica : Figure
{
public Kralica(FigureDefinition definition) : base(definition)
{
}
protected override List<Tuple<int, int>> GetValidTurns()
{
var straight = new StraightSlide();
var diagonal = new DiagonalSlide();
return straight.Concat(diagonal);
}
}
Also the code in your original classes should be replaced by your new ValidTurn classes.
Edit:
public class StraightSlide : ValidTurn
{
private Figure figure;
public StraightSlide(Figure figure)
{
this.figure = figure;
}
public List<Tuple<int, int>> GetValidTurns()
{
figure.YourMethodToCall();
// ... valid rook turns here
}
}
You could maybe consider put all your validation logic into the ValidTurn(TurnValidation).