Reputation: 31
I'm making a chess game and for the pieces to move I need the variable board
and it's located in the Form1
class. I was wondering if there is anyway to call the board
variable in my base class so I can use it in my other classes that reference my base class.
This is how code looks (I only included key parts not everything)
public partial class Form1 : Form
{
public string[,] board = new string[8, 8];
}
class Pieces
{
//I want there to be a variable here that will always contain the exact data as the board variable
//I also have other variables that are in the Form1 class that I need in here
}
class Rook : Pieces
{
//This is just a small sample of how I set up the moves but its in a for loop
if (board[x + i, y] == null && !board[x + i, y].Contains("King"))
pieceMove.AddLast(placementBoard[x + i, y]);
}
This is what I've thought of but I want to know if there is a different approach
public partial class Form1 : Form
{
public string[,] board = new string[8, 8];
Rook[] whiteRook = new Rook[10];//I made an array of rooks so when a pawn gets to the opposite side of the board it can turn into a rook
public Form1()
{
InitializeComponent();
Rook[0] whiteRook = new Rook();
whiteRook.board = board;//Everytime a piece moves I will call this with every piece to update it
}
}
class Pieces
{
public string[,] board = new string[8,8];
}
class Rook : Pieces
{
//This is just a small sample of how I set up the moves but its in a for loop
if (board[x + i, y] == null && !board[x + i, y].Contains("King"))
pieceMove.AddLast(placementBoard[x + i, y]);
}
Upvotes: 0
Views: 75
Reputation: 61339
Prefer composition over inheritance.
Your object model is all wrong right now. You are trying to control everything from the various piece classes when those should just contain piece specific logic, the containing class should control the state. You really want to have a Board
object that contains Piece
objects that you can then subclass
public class Board
{
List<Piece> pieces;
}
public abstract class Piece
{
//Some base behavior/interface
public bool Move(int xTarget, int yTarget)
{
if (IsValidMove(xTarget, yTarget))
{
//Do stuff
}
}
protected abstract bool IsValidMove(int xTarget, int yTarget);
}
And then subclass Rook
, Bishop
etc from "Piece". If necessary you can pass the Board
into the Piece
via constructor or a property but that dependency is very much the wrong way, the Board
should be controlling its own state.
Upvotes: 2