2010-04-15 104 views
3

所以我试图做一个MasterMind程序作为一种练习。窗体颜色变化

  • 场的40图片框(第4行,10行)
  • 6按键(红,绿,橙,黄,蓝,紫)

在按下这些按钮中的一个(让我们假设红色),然后一个图片框变成红色。
我的问题是我如何迭代槽所有这些图片框?
我可以得到它的工作,但只有当我写:
而这是offcourse没有办法写这个,会带我无数包含基本相同的行。

 private void picRood_Click(object sender, EventArgs e) 
    { 
     UpdateDisplay(); 
     pb1.BackColor = System.Drawing.Color.Red; 
    } 

按下红色按钮 - >第一个图片框变为红色
按下蓝色按钮 - >第二个图片框变为蓝色
按下橙色按钮 - >第三图片框变为橙色
等。 ..

我曾经有一个类似的程序,模拟交通灯,我可以为每种颜色(红色0,橙色1,绿色2)分配一个值。
是类似的东西需要或我如何处理所有这些图片框,并使其对应于正确的按钮。

最好的问候。

回答

0

我会用一个面板作为所有PIC盒容器控制,则:

foreach (PictureBox pic in myPanel.Controls) 
{ 
    // do something to set a color 
    // buttons can set an enum representing a hex value for color maybe...??? 
} 
0

我不会用pictureboxes,而是将使用单一的PictureBox,使用GDI直接绘制到其上。其结果是更快,它会让你写更复杂的游戏,涉及精灵和动画;)

这是很容易学习如何。

+0

真的不知道你在说什么,它会如何简单的是什么=)。 – Sef 2010-04-15 15:55:38

1

我不会使用控件,而是可以使用单个PictureBox并处理Paint事件。这使您可以在该PictureBox内绘制,以便快速处理所有框。

在代码:

// define a class to help us manage our grid 
public class GridItem { 
    public Rectangle Bounds {get; set;} 
    public Brush Fill {get; set;} 
} 

// somewhere in your initialization code ie: the form's constructor 
public MyForm() { 
    // create your collection of grid items 
    gridItems = new List<GridItem>(4 * 10); // width * height 
    for (int y = 0; y < 10; y++) { 
     for (int x = 0; x < 4; x++) { 
      gridItems.Add(new GridItem() { 
       Bounds = new Rectangle(x * boxWidth, y * boxHeight, boxWidth, boxHeight), 
       Fill = Brushes.Red // or whatever color you want 
      }); 
     } 
    } 
} 

// make sure you've attached this to your pictureBox's Paint event 
private void PictureBoxPaint(object sender, PaintEventArgs e) { 
    // paint all your grid items 
    foreach (GridItem item in gridItems) { 
     e.Graphics.FillRectangle(item.Fill, item.Bounds); 
    } 
} 

// now if you want to change the color of a box 
private void OnClickBlue(object sender, EventArgs e) { 
    // if you need to set a certain box at row,column use: 
    // index = column + row * 4 
    gridItems[2].Fill = Brushes.Blue; 
    pictureBox.Invalidate(); // we need to repaint the picturebox 
}