2010-03-11 60 views
2

我已經制定了大部分代碼並且有幾個遊戲類。我現在堅持的一點是,它如何繪製實際的Connect 4網格。誰能告訴我這個for循環有什麼問題?我沒有得到任何錯誤,但網格並未出現。我正在使用C#。連接4 C#(如何繪製網格)

private void Drawgrid() 
{ 
    Brush b = Brushes.Black; 
    Pen p = Pens.Black; 
    for (int xCoor = XStart, col = 0; xCoor < XStart + ColMax * DiscSpace; xCoor += DiscSpace, col++) 
    { 
     // x coordinate beginning; while the x coordinate is smaller than the max column size, times it by 
     // the space between each disc and then add the x coord to the disc space in order to create a new circle. 
     for (int yCoor = YStart, row = RowMax - 1; yCoor < YStart + RowMax * DiscScale; yCoor += DiscScale, row--) 
     { 
      switch (Grid.State[row, col]) 
      { 
       case GameGrid.Gridvalues.Red: 
        b = Brushes.Red; 
        break; 
       case GameGrid.Gridvalues.Yellow: 
        b = Brushes.Yellow; 
        break; 
       case GameGrid.Gridvalues.None: 
        b = Brushes.Aqua; 
        break; 
      } 
     } 
     MainDisplay.DrawEllipse(p, xCoor, yCoor, 50, 50); 
     MainDisplay.FillEllipse(b, xCoor, yCoor, 50, 50); 
    } 
    Invalidate(); 
} 
+0

@John Rasch - 對不起,我們都似乎在編輯。我會停下來。 – 2010-03-11 18:41:05

回答

2

當窗口重繪本身時,需要執行Drawgrid()中的代碼。

Invalidate()調用告訴應用程序它需要重新繪製窗口內容(它會觸發重繪窗口)。此代碼(除Invalidate()調用外)應該在您的覆蓋OnPaint()方法中,否則無論由此代碼繪製什麼,都將立即被OnPaint()中的默認繪圖代碼覆蓋(默認情況下,它可能會繪製白色背景)當你撥打Invalidate()時。

protected override void OnPaint(PaintEventArgs e) 
{ 
    Graphics g = e.Graphics; 

    // (your painting code here...) 
} 
+0

對不起,我沒有一個onDraw()方法。 這個功能我有這樣的代碼,以將圖像存儲爲位圖之前: 私人無效Form1_Load的(對象發件人,EventArgs的) { MainBitmap =新位圖(this.ClientRectangle.Width,this.ClientRectangle.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); MainDisplay = Graphics.FromImage(MainBitmap); MainDisplay.Clear(Color.Aqua); Drawgrid(); } 感謝您的快速回復。 – 2010-03-11 18:36:29

+0

對不起,在上面的評論中沒有很好地分開。 – 2010-03-11 18:37:39

+0

@Matt Wilde:這不是你如何在Winforms中進行自定義繪圖。你需要做Scott所說的,從'System.Windows.Forms.Control'繼承你的板子控制並覆蓋它的'OnPaint'方法。如果你想使用一個位圖作爲某種緩衝區,那麼可以(不是很好),但是實際上你需要使用'Graphics.DrawImage'在'OnPaint'方法中將位圖繪製到控制表面。簡單地在內存位圖上繪圖不會使其內容奇蹟般地出現在屏幕上。 – Aaronaught 2010-03-11 18:43:45