2016-12-06 20 views
0

我正在製作象棋遊戲,並且要移動棋子我需要變量board,它位於Form1類中。我想知道是否在我的基類中調用board變量,所以我可以在引用我的基類的其他類中使用它。從1類抓取變量,並在沒有繼承的情況下在另一個類中使用它們c#

這是代碼看起來是(我只包括關鍵零部件不是一切)

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]); 
} 

這是我想的,但我想知道是否有一種不同的方法

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]); 
} 
+0

首先嚐試創建PIECES類的FORM1的朋友類,這樣您可以訪問form1的所有變量。但董事會是公開的,所以我會假設你只需要一個董事會的實例,爲什麼不把它做成靜態的。但是,如果你不想這樣做,那麼你可以做的是創建一個接收form1對象的件類中的函數,並且由於董事會是公開的,它將通過該對象容易地在該函數中可用。除此之外,BradleyDOTNET表示你應該考慮改變你的對象模型。 –

+0

我對編程相當陌生,所以我真的不明白靜態是什麼或者如何有效地使用類,我知道這是一個壞習慣,但我一直在避免在該程序中使用類,我真的只是硬編碼所有這些動作和'Form1'類的所有內容,但是我把板子變量公開,試着看看我是否可以從pieces類訪問它,並且不會被要求刪除它。現在我把它作爲'public static string [,] board = new string [8,8];並且我複製了白嘴鴉的動作並將它放入白嘴鴉班,並且它現在不想移動 –

+0

我現在修好了,所以現在白嘴鴉動起來了,這是因爲if語句中的空引用異常 –

回答

2

比繼承更喜歡構圖。

您的對象模型現在都是錯誤的。你正試圖控制所有這些來自各個類的類,當這些類應該只包含片段特定的邏輯時,包含類應該控制狀態。你真的想有一個Board對象包含Piece對象,然後就可以繼承

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); 
} 

然後子類RookBishop等從「海賊王」。如果有必要,您可以通過構造函數或屬性將Board傳遞給Piece,但該依賴關係非常錯誤,Board應該控制自己的狀態。

+0

對不起,我不是那種先進的,我真的不知道這是如何工作的 –

+0

或者真的你是什麼意思的子類和一切 –

+0

@DoomedSpace你能更具體一點嗎?您已經通過編寫'Rook:Pieces'創建了一個子類。我試圖在正確的OO設計的開始處寫入所有東西,而不寫所有東西,所以爲了獲得更多幫助,我需要一個更具體的問題。你懂繼承嗎?多態性?你只需要定義「子類」(如果是這樣,它只是一個從另一個類派生出來的類) – BradleyDotNET

相關問題