So i am attempting to make a MasterMind program as sort of exercise.
- Field of 40 picture boxes (line of 4, 10 rows)
- 6 buttons (red, green, orange, yellow, blue, purple)
When i press one of these buttons (lets assume the red one) then a picture box turns red.
My question is how do i iterate trough all these picture boxes? I can get it to work but only if i write : And this is offcourse no way to write this, would take me countless of lines that contain basicly the same. private void picRood_Click(object sender, EventArgs e)
{
UpdateDisplay();
pb1.BackColor = System.Drawing.Color.Red;
}
Press the red button -> first picture box turns red
Press the blue button -> second picture box turns blue Press the orange button -> third picture box turns orange And so on...Ive had a previous similar program that simulates a traffic light, there i could assign a value to each color (red 0, orange 1, green 2).
Is something similar needed or how exactly do i adress all those picture boxes and make them correspond to the proper 开发者_开发知识库button.Best Regards.
I wouldn't use controls, instead you can use a single PictureBox and handle the Paint
event. This lets you draw inside that PictureBox so you can quickly handle all your boxes.
In code:
// 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
}
I would use a panel as the container control for all the pic boxes, then:
foreach (PictureBox pic in myPanel.Controls)
{
// do something to set a color
// buttons can set an enum representing a hex value for color maybe...???
}
I wouldn't use pictureboxes, but instead would use a single picturebox, drawing directly onto it using GDI. The result is a lot faster, and it will set you up to write more complex games involving sprites and animation ;)
It's very easy to learn how.
精彩评论