public void GenerateField() { Random random = new Random(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { FieldButton newButton = new FieldButton(); newButton.Location = new Point(x * offset, (y + 1) * offset); newButton.Size = new Size(offset, offset); newButton.isClickable = true; if (random.Next(0, 100) <= bombPercent) { newButton.isBomb = true; bombs++; } newButton.xCoord = x; newButton.yCoord = y; Controls.Add(newButton); newButton.MouseUp += new MouseEventHandler(FieldButtonClick); field[x, y] = newButton; } } }
void OpenRegion(int xCoord, int yCoord, FieldButton clickedButton) { Queue <FieldButton> queue = new Queue <FieldButton>(); queue.Enqueue(clickedButton); clickedButton.wasAdded = true; while (queue.Count > 0) { FieldButton currentCell = queue.Dequeue(); OpenCell(currentCell.xCoord, currentCell.yCoord, currentCell); cellsOpened++; if (CountBombsAround(currentCell.xCoord, currentCell.yCoord) == 0) { for (int y = currentCell.yCoord - 1; y <= currentCell.yCoord + 1; y++) { for (int x = currentCell.xCoord - 1; x <= currentCell.xCoord + 1; x++) { if (x == currentCell.xCoord && y == currentCell.yCoord)// { continue; } if (x >= 0 && x < width && y < height && y >= 0) { if (!field[x, y].wasAdded) { queue.Enqueue(field[x, y]); field[x, y].wasAdded = true; } } } } } } }
void EmptyFieldButtonClick(FieldButton clickedButton) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (field[x, y] == clickedButton) { OpenRegion(x, y, clickedButton); } } } }
void OpenCell(int x, int y, FieldButton clickedButton) { int bombsAround = CountBombsAround(x, y); if (bombsAround == 0) { } else { clickedButton.BackColor = Color.White; clickedButton.Text = "" + bombsAround; } clickedButton.Enabled = false; }
void FieldButtonClick(object sender, MouseEventArgs e) { FieldButton clickedButton = (FieldButton)sender; if (e.Button == MouseButtons.Left && clickedButton.isClickable) { if (clickedButton.isBomb) { if (isFirstClick) { timer1.Start(); timer1.Enabled = true; clickedButton.isBomb = false; isFirstClick = false; bombs--; OpenRegion(clickedButton.xCoord, clickedButton.yCoord, clickedButton); } else { Explode(); } } else { EmptyFieldButtonClick(clickedButton); } isFirstClick = false; } if (e.Button == MouseButtons.Right) { clickedButton.isClickable = !clickedButton.isClickable; if (!clickedButton.isClickable) { clickedButton.Image = Image.FromFile("C:/Users/Lev/Pictures/Saved Pictures/flagsInMiner.png"); } else { clickedButton.Text = ""; } } CheckWin(); }