5
\$\begingroup\$

I made a Minesweeper for school and it works already. The only problem I have is that I need to optimize one part of my code but I have no idea how. The code below is for the whole program. The second form is just a page for explaining to the user how to play. The part I need to optimize is the part where I basically repeat the same thing 4 times but change 1 number every 4 times. But if you find another part that could have been done better, please do let me know. That part of the code looks like this:

foreach (Control item in groupBox1.Controls)
            {
                if (
                item.Name == string.Format("button{0}", red1 - orange1) ||
                item.Name == string.Format("button{0}", red1 + orange1) ||
                item.Name == string.Format("button{0}", red1 - orange2) ||
                item.Name == string.Format("button{0}", red1 + orange2) ||

                item.Name == string.Format("button{0}", red2 - orange1) ||
                item.Name == string.Format("button{0}", red2 + orange1) ||
                item.Name == string.Format("button{0}", red2 - orange2) ||
                item.Name == string.Format("button{0}", red2 + orange2) ||

                item.Name == string.Format("button{0}", red3 - orange1) ||
                item.Name == string.Format("button{0}", red3 + orange1) ||
                item.Name == string.Format("button{0}", red3 - orange2) ||
                item.Name == string.Format("button{0}", red3 + orange2) ||

                item.Name == string.Format("button{0}", red4 - orange1) ||
                item.Name == string.Format("button{0}", red4 + orange1) ||
                item.Name == string.Format("button{0}", red4 - orange2) ||
                item.Name == string.Format("button{0}", red4 + orange2))
            {
                item.ForeColor = Color.Orange;
            }
        }

This is the full code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Minesweeper
{
    public partial class MinesweeperForm : Form
    {
        private int ticks; 

        int currentHighscore;

        //values to calculate which button should be orange
        int orange1 = 1;
        int orange2 = 5;

        #region initializer
        public MinesweeperForm()
        {
            InitializeComponent();
        }
        #endregion

        //play button function 
        #region play button
        private void btnPlay_Click(object sender, EventArgs e)
        {
            //start timer
            GameTimer.Start();
            //every button in playfield groupbox enabled
            foreach (Control item in groupBox1.Controls)
            {
                item.Enabled = true;
            }
            //calls shuffle mines
            ShuffleMines();
            //disables play button and enables stop button
            btnPlay.Enabled = false;
            btnStop.Enabled = true;
        }
        #endregion

        //shufflemines function
        #region shuffleMines
        private void ShuffleMines()
        {
            //makes list of all buttons in groupbox
            List<Button> listButtons = new List<Button>
            {
                button1, button2, button3, button4, button5,
                button6, button7, button8, button9, button10,
                button11, button12, button13, button14, button15,
                button16, button17, button18, button19, button20,
                button21, button22, button23, button24, button25
            };

            //makes a new random
            Random rnd = new Random();

            //selects randoms button numbers from list
            int red1 = rnd.Next(listButtons.Count);
            int red2 = rnd.Next(listButtons.Count);
            int red3 = rnd.Next(listButtons.Count);
            int red4 = rnd.Next(listButtons.Count);

            //makes the buttons name from the random button numbers
            var redButton1 = string.Format("button{0}", red1);
            var redButton2 = string.Format("button{0}", red2);
            var redButton3 = string.Format("button{0}", red3);
            var redButton4 = string.Format("button{0}", red4);

            //set forecolor of the not selected buttons to green
            foreach (Control item in groupBox1.Controls)
            {
                item.ForeColor = Color.Green;
            }

            foreach (Control item in groupBox1.Controls)
            {
                if (
                    item.Name == string.Format("button{0}", red1 - orange1) ||
                    item.Name == string.Format("button{0}", red1 + orange1) ||
                    item.Name == string.Format("button{0}", red1 - orange2) ||
                    item.Name == string.Format("button{0}", red1 + orange2) ||

                    item.Name == string.Format("button{0}", red2 - orange1) ||
                    item.Name == string.Format("button{0}", red2 + orange1) ||
                    item.Name == string.Format("button{0}", red2 - orange2) ||
                    item.Name == string.Format("button{0}", red2 + orange2) ||

                    item.Name == string.Format("button{0}", red3 - orange1) ||
                    item.Name == string.Format("button{0}", red3 + orange1) ||
                    item.Name == string.Format("button{0}", red3 - orange2) ||
                    item.Name == string.Format("button{0}", red3 + orange2) ||

                    item.Name == string.Format("button{0}", red4 - orange1) ||
                    item.Name == string.Format("button{0}", red4 + orange1) ||
                    item.Name == string.Format("button{0}", red4 - orange2) ||
                    item.Name == string.Format("button{0}", red4 + orange2))
                {
                    item.ForeColor = Color.Orange;
                }
            }

            //set forecolor of the selected buttons for red to right color
            foreach (Control item in groupBox1.Controls)
            {
                if (item.Name == redButton1 || item.Name == redButton2 || item.Name == redButton3 || item.Name == redButton4)
                {
                    item.ForeColor = Color.Red;
                }
            }

        }
        #endregion

        //win function
        #region win
        private void Win()
        {
            //checks if all non-mine buttons are pressed
            if(progressBarGame.Value == 21)
            {
                //checks for new highscore
                currentHighscore = int.Parse(lblHighscore.Text);
                if (ticks < currentHighscore)
                {
                    lblHighscore.Text = ticks.ToString();
                }
                //displays messagebox saying you win
                MessageBox.Show("You win!");
            }

        }
        #endregion

        //stop button function
        #region stop button
        private void btnStop_Click(object sender, EventArgs e)
        {
            //calls gameover function
            gameOver();
        }
        #endregion

        //gameover function
        #region gameOver
        private void gameOver()
        {
            //disables all playfield buttons and resets button color
            foreach (Control item in groupBox1.Controls)
            {
                item.Enabled = false;
                item.BackColor = Color.FromKnownColor(KnownColor.ControlLight);
            }
            //disables stop button and enables play button
            btnStop.Enabled = false;
            btnPlay.Enabled = true;
            //resets progressbar
            progressBarGame.Value = 0;
        }
        #endregion

        //switch forms function
        #region switch forms
        //open howtoplay form and hides current form
        private void btnHowToPlay_Click(object sender, EventArgs e)
        {
            HowToPlayForm frm2 = new HowToPlayForm();
            frm2.Show();
            this.Hide();
        }
        #endregion

        //proper close function
        #region proper close
        //properly closes form after switching forms
        private void MinesweeperForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
        #endregion

        //playfield button clicked
        #region playfieldbutton pressed
        private void PlayFieldButton_MouseDown(object sender, MouseEventArgs e)
        {
            //checks which button is pressed
            Button button = sender as Button;

            //if left mouse button pressed
            if (e.Button == MouseButtons.Left)
            {
                //sets invisible color to visible
                button.BackColor = button.ForeColor;

                //if button is not a mine adds point to bar and checks win
                if (button.BackColor == Color.Green || button.BackColor == Color.Orange)
                {
                    progressBarGame.Value += 1;
                    Win();
                }
                //if button is mine calls function "gameOver"
                else if (button.BackColor == Color.Red)
                {
                    MessageBox.Show("Gameover!");
                    gameOver();
                }

                //disables the button that is presssed
                button.Enabled = false;
            }

            //if right mouse button pressed set button color to black
            if (e.Button == MouseButtons.Right)
            {
                button.BackColor = Color.Black;
            }
        }
        #endregion

        //timer function
        #region timer
        private void GameTimer_Tick(object sender, EventArgs e)
        {
            ticks++;
            string regel1 = string.Format("Time: {0} sec", ticks);
            lblTimer.Text = regel1;
        }
        #endregion
    }
}

Designer code:

namespace Minesweeper
{
    partial class MinesweeperForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MinesweeperForm));
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.button6 = new System.Windows.Forms.Button();
            this.button7 = new System.Windows.Forms.Button();
            this.button8 = new System.Windows.Forms.Button();
            this.button9 = new System.Windows.Forms.Button();
            this.button10 = new System.Windows.Forms.Button();
            this.button11 = new System.Windows.Forms.Button();
            this.button12 = new System.Windows.Forms.Button();
            this.button13 = new System.Windows.Forms.Button();
            this.button14 = new System.Windows.Forms.Button();
            this.button15 = new System.Windows.Forms.Button();
            this.button16 = new System.Windows.Forms.Button();
            this.button17 = new System.Windows.Forms.Button();
            this.button18 = new System.Windows.Forms.Button();
            this.button19 = new System.Windows.Forms.Button();
            this.button20 = new System.Windows.Forms.Button();
            this.button21 = new System.Windows.Forms.Button();
            this.button22 = new System.Windows.Forms.Button();
            this.button23 = new System.Windows.Forms.Button();
            this.button24 = new System.Windows.Forms.Button();
            this.button25 = new System.Windows.Forms.Button();
            this.btnPlay = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.btnStop = new System.Windows.Forms.Button();
            this.progressBarGame = new System.Windows.Forms.ProgressBar();
            this.lblHighscoreText = new System.Windows.Forms.Label();
            this.lblHighscore = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.btnHowToPlay = new System.Windows.Forms.Button();
            this.lblTimer = new System.Windows.Forms.Label();
            this.GameTimer = new System.Windows.Forms.Timer(this.components);
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Enabled = false;
            this.button1.Location = new System.Drawing.Point(17, 34);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(50, 50);
            this.button1.TabIndex = 0;
            this.button1.Tag = "speelveld";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button2
            // 
            this.button2.Enabled = false;
            this.button2.Location = new System.Drawing.Point(73, 34);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(50, 50);
            this.button2.TabIndex = 1;
            this.button2.Tag = "speelveld";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button3
            // 
            this.button3.Enabled = false;
            this.button3.Location = new System.Drawing.Point(129, 34);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(50, 50);
            this.button3.TabIndex = 2;
            this.button3.Tag = "speelveld";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button4
            // 
            this.button4.Enabled = false;
            this.button4.Location = new System.Drawing.Point(185, 34);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(50, 50);
            this.button4.TabIndex = 3;
            this.button4.Tag = "speelveld";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button5
            // 
            this.button5.Enabled = false;
            this.button5.Location = new System.Drawing.Point(241, 34);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(50, 50);
            this.button5.TabIndex = 4;
            this.button5.Tag = "speelveld";
            this.button5.UseVisualStyleBackColor = true;
            this.button5.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button6
            // 
            this.button6.Enabled = false;
            this.button6.Location = new System.Drawing.Point(17, 90);
            this.button6.Name = "button6";
            this.button6.Size = new System.Drawing.Size(50, 50);
            this.button6.TabIndex = 5;
            this.button6.Tag = "speelveld";
            this.button6.UseVisualStyleBackColor = true;
            this.button6.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button7
            // 
            this.button7.Enabled = false;
            this.button7.Location = new System.Drawing.Point(73, 90);
            this.button7.Name = "button7";
            this.button7.Size = new System.Drawing.Size(50, 50);
            this.button7.TabIndex = 6;
            this.button7.Tag = "speelveld";
            this.button7.UseVisualStyleBackColor = true;
            this.button7.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button8
            // 
            this.button8.Enabled = false;
            this.button8.Location = new System.Drawing.Point(129, 90);
            this.button8.Name = "button8";
            this.button8.Size = new System.Drawing.Size(50, 50);
            this.button8.TabIndex = 7;
            this.button8.Tag = "speelveld";
            this.button8.UseVisualStyleBackColor = true;
            this.button8.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button9
            // 
            this.button9.Enabled = false;
            this.button9.Location = new System.Drawing.Point(185, 90);
            this.button9.Name = "button9";
            this.button9.Size = new System.Drawing.Size(50, 50);
            this.button9.TabIndex = 8;
            this.button9.Tag = "speelveld";
            this.button9.UseVisualStyleBackColor = true;
            this.button9.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button10
            // 
            this.button10.Enabled = false;
            this.button10.Location = new System.Drawing.Point(241, 90);
            this.button10.Name = "button10";
            this.button10.Size = new System.Drawing.Size(50, 50);
            this.button10.TabIndex = 9;
            this.button10.Tag = "speelveld";
            this.button10.UseVisualStyleBackColor = true;
            this.button10.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button11
            // 
            this.button11.Enabled = false;
            this.button11.Location = new System.Drawing.Point(17, 146);
            this.button11.Name = "button11";
            this.button11.Size = new System.Drawing.Size(50, 50);
            this.button11.TabIndex = 10;
            this.button11.Tag = "speelveld";
            this.button11.UseVisualStyleBackColor = true;
            this.button11.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button12
            // 
            this.button12.Enabled = false;
            this.button12.Location = new System.Drawing.Point(73, 146);
            this.button12.Name = "button12";
            this.button12.Size = new System.Drawing.Size(50, 50);
            this.button12.TabIndex = 11;
            this.button12.Tag = "speelveld";
            this.button12.UseVisualStyleBackColor = true;
            this.button12.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button13
            // 
            this.button13.Enabled = false;
            this.button13.Location = new System.Drawing.Point(129, 146);
            this.button13.Name = "button13";
            this.button13.Size = new System.Drawing.Size(50, 50);
            this.button13.TabIndex = 12;
            this.button13.Tag = "speelveld";
            this.button13.UseVisualStyleBackColor = true;
            this.button13.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button14
            // 
            this.button14.Enabled = false;
            this.button14.Location = new System.Drawing.Point(185, 146);
            this.button14.Name = "button14";
            this.button14.Size = new System.Drawing.Size(50, 50);
            this.button14.TabIndex = 13;
            this.button14.Tag = "speelveld";
            this.button14.UseVisualStyleBackColor = true;
            this.button14.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button15
            // 
            this.button15.Enabled = false;
            this.button15.Location = new System.Drawing.Point(241, 146);
            this.button15.Name = "button15";
            this.button15.Size = new System.Drawing.Size(50, 50);
            this.button15.TabIndex = 14;
            this.button15.Tag = "speelveld";
            this.button15.UseVisualStyleBackColor = true;
            this.button15.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button16
            // 
            this.button16.Enabled = false;
            this.button16.Location = new System.Drawing.Point(17, 202);
            this.button16.Name = "button16";
            this.button16.Size = new System.Drawing.Size(50, 50);
            this.button16.TabIndex = 15;
            this.button16.Tag = "speelveld";
            this.button16.UseVisualStyleBackColor = true;
            this.button16.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button17
            // 
            this.button17.Enabled = false;
            this.button17.Location = new System.Drawing.Point(73, 202);
            this.button17.Name = "button17";
            this.button17.Size = new System.Drawing.Size(50, 50);
            this.button17.TabIndex = 16;
            this.button17.Tag = "speelveld";
            this.button17.UseVisualStyleBackColor = true;
            this.button17.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button18
            // 
            this.button18.Enabled = false;
            this.button18.Location = new System.Drawing.Point(129, 202);
            this.button18.Name = "button18";
            this.button18.Size = new System.Drawing.Size(50, 50);
            this.button18.TabIndex = 17;
            this.button18.Tag = "speelveld";
            this.button18.UseVisualStyleBackColor = true;
            this.button18.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button19
            // 
            this.button19.Enabled = false;
            this.button19.Location = new System.Drawing.Point(185, 202);
            this.button19.Name = "button19";
            this.button19.Size = new System.Drawing.Size(50, 50);
            this.button19.TabIndex = 18;
            this.button19.Tag = "speelveld";
            this.button19.UseVisualStyleBackColor = true;
            this.button19.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button20
            // 
            this.button20.Enabled = false;
            this.button20.Location = new System.Drawing.Point(241, 202);
            this.button20.Name = "button20";
            this.button20.Size = new System.Drawing.Size(50, 50);
            this.button20.TabIndex = 19;
            this.button20.Tag = "speelveld";
            this.button20.UseVisualStyleBackColor = true;
            this.button20.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button21
            // 
            this.button21.Enabled = false;
            this.button21.Location = new System.Drawing.Point(17, 258);
            this.button21.Name = "button21";
            this.button21.Size = new System.Drawing.Size(50, 50);
            this.button21.TabIndex = 20;
            this.button21.Tag = "speelveld";
            this.button21.UseVisualStyleBackColor = true;
            this.button21.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button22
            // 
            this.button22.Enabled = false;
            this.button22.Location = new System.Drawing.Point(73, 258);
            this.button22.Name = "button22";
            this.button22.Size = new System.Drawing.Size(50, 50);
            this.button22.TabIndex = 21;
            this.button22.Tag = "speelveld";
            this.button22.UseVisualStyleBackColor = true;
            this.button22.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button23
            // 
            this.button23.Enabled = false;
            this.button23.Location = new System.Drawing.Point(129, 258);
            this.button23.Name = "button23";
            this.button23.Size = new System.Drawing.Size(50, 50);
            this.button23.TabIndex = 22;
            this.button23.Tag = "speelveld";
            this.button23.UseVisualStyleBackColor = true;
            this.button23.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button24
            // 
            this.button24.Enabled = false;
            this.button24.Location = new System.Drawing.Point(185, 258);
            this.button24.Name = "button24";
            this.button24.Size = new System.Drawing.Size(50, 50);
            this.button24.TabIndex = 23;
            this.button24.Tag = "speelveld";
            this.button24.UseVisualStyleBackColor = true;
            this.button24.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // button25
            // 
            this.button25.Enabled = false;
            this.button25.Location = new System.Drawing.Point(241, 258);
            this.button25.Name = "button25";
            this.button25.Size = new System.Drawing.Size(50, 50);
            this.button25.TabIndex = 24;
            this.button25.Tag = "speelveld";
            this.button25.UseVisualStyleBackColor = true;
            this.button25.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
            // 
            // btnPlay
            // 
            this.btnPlay.Location = new System.Drawing.Point(11, 460);
            this.btnPlay.Name = "btnPlay";
            this.btnPlay.Size = new System.Drawing.Size(172, 50);
            this.btnPlay.TabIndex = 0;
            this.btnPlay.Text = "Play!";
            this.btnPlay.UseVisualStyleBackColor = true;
            this.btnPlay.Click += new System.EventHandler(this.btnPlay_Click);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.button9);
            this.groupBox1.Controls.Add(this.button1);
            this.groupBox1.Controls.Add(this.button25);
            this.groupBox1.Controls.Add(this.button2);
            this.groupBox1.Controls.Add(this.button24);
            this.groupBox1.Controls.Add(this.button3);
            this.groupBox1.Controls.Add(this.button23);
            this.groupBox1.Controls.Add(this.button4);
            this.groupBox1.Controls.Add(this.button22);
            this.groupBox1.Controls.Add(this.button5);
            this.groupBox1.Controls.Add(this.button21);
            this.groupBox1.Controls.Add(this.button6);
            this.groupBox1.Controls.Add(this.button20);
            this.groupBox1.Controls.Add(this.button7);
            this.groupBox1.Controls.Add(this.button19);
            this.groupBox1.Controls.Add(this.button8);
            this.groupBox1.Controls.Add(this.button18);
            this.groupBox1.Controls.Add(this.button10);
            this.groupBox1.Controls.Add(this.button17);
            this.groupBox1.Controls.Add(this.button11);
            this.groupBox1.Controls.Add(this.button16);
            this.groupBox1.Controls.Add(this.button12);
            this.groupBox1.Controls.Add(this.button15);
            this.groupBox1.Controls.Add(this.button13);
            this.groupBox1.Controls.Add(this.button14);
            this.groupBox1.Location = new System.Drawing.Point(41, 90);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(300, 318);
            this.groupBox1.TabIndex = 25;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Speelveld";
            // 
            // btnStop
            // 
            this.btnStop.Location = new System.Drawing.Point(189, 460);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(192, 50);
            this.btnStop.TabIndex = 26;
            this.btnStop.Text = "Stop";
            this.btnStop.UseVisualStyleBackColor = true;
            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            // 
            // progressBarGame
            // 
            this.progressBarGame.Location = new System.Drawing.Point(11, 522);
            this.progressBarGame.Maximum = 21;
            this.progressBarGame.Name = "progressBarGame";
            this.progressBarGame.Size = new System.Drawing.Size(370, 23);
            this.progressBarGame.Step = 1;
            this.progressBarGame.TabIndex = 29;
            // 
            // lblHighscoreText
            // 
            this.lblHighscoreText.AutoSize = true;
            this.lblHighscoreText.Location = new System.Drawing.Point(177, 425);
            this.lblHighscoreText.Name = "lblHighscoreText";
            this.lblHighscoreText.Size = new System.Drawing.Size(76, 17);
            this.lblHighscoreText.TabIndex = 32;
            this.lblHighscoreText.Text = "Highscore:";
            // 
            // lblHighscore
            // 
            this.lblHighscore.AutoSize = true;
            this.lblHighscore.Location = new System.Drawing.Point(259, 425);
            this.lblHighscore.Name = "lblHighscore";
            this.lblHighscore.Size = new System.Drawing.Size(24, 17);
            this.lblHighscore.TabIndex = 33;
            this.lblHighscore.Text = "20";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(289, 425);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(34, 17);
            this.label1.TabIndex = 34;
            this.label1.Text = "sec.";
            // 
            // btnHowToPlay
            // 
            this.btnHowToPlay.Location = new System.Drawing.Point(11, 12);
            this.btnHowToPlay.Name = "btnHowToPlay";
            this.btnHowToPlay.Size = new System.Drawing.Size(370, 56);
            this.btnHowToPlay.TabIndex = 36;
            this.btnHowToPlay.Text = "How to play";
            this.btnHowToPlay.UseVisualStyleBackColor = true;
            this.btnHowToPlay.Click += new System.EventHandler(this.btnHowToPlay_Click);
            // 
            // lblTimer
            // 
            this.lblTimer.AutoSize = true;
            this.lblTimer.Location = new System.Drawing.Point(13, 425);
            this.lblTimer.Name = "lblTimer";
            this.lblTimer.Size = new System.Drawing.Size(47, 17);
            this.lblTimer.TabIndex = 37;
            this.lblTimer.Text = "Time: ";
            // 
            // GameTimer
            // 
            this.GameTimer.Interval = 1000;
            this.GameTimer.Tick += new System.EventHandler(this.GameTimer_Tick);
            // 
            // MinesweeperForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.Control;
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.ClientSize = new System.Drawing.Size(396, 558);
            this.Controls.Add(this.lblTimer);
            this.Controls.Add(this.btnHowToPlay);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.lblHighscore);
            this.Controls.Add(this.lblHighscoreText);
            this.Controls.Add(this.progressBarGame);
            this.Controls.Add(this.btnStop);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.btnPlay);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximumSize = new System.Drawing.Size(414, 605);
            this.MinimumSize = new System.Drawing.Size(414, 530);
            this.Name = "MinesweeperForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Tag = "";
            this.Text = "Minesweeper";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MinesweeperForm_FormClosing);
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.Button button6;
        private System.Windows.Forms.Button button7;
        private System.Windows.Forms.Button button8;
        private System.Windows.Forms.Button button9;
        private System.Windows.Forms.Button button10;
        private System.Windows.Forms.Button button11;
        private System.Windows.Forms.Button button12;
        private System.Windows.Forms.Button button13;
        private System.Windows.Forms.Button button14;
        private System.Windows.Forms.Button button15;
        private System.Windows.Forms.Button button16;
        private System.Windows.Forms.Button button17;
        private System.Windows.Forms.Button button18;
        private System.Windows.Forms.Button button19;
        private System.Windows.Forms.Button button20;
        private System.Windows.Forms.Button button21;
        private System.Windows.Forms.Button button22;
        private System.Windows.Forms.Button button23;
        private System.Windows.Forms.Button button24;
        private System.Windows.Forms.Button button25;
        private System.Windows.Forms.Button btnPlay;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button btnStop;
        private System.Windows.Forms.ProgressBar progressBarGame;
        private System.Windows.Forms.Label lblHighscoreText;
        private System.Windows.Forms.Label lblHighscore;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnHowToPlay;
        private System.Windows.Forms.Label lblTimer;
        private System.Windows.Forms.Timer GameTimer;
    }
}
\$\endgroup\$
  • \$\begingroup\$ @Henrik Hansen Do you need the full designer content? \$\endgroup\$ – Stijn Hendriks Mar 12 at 15:25
  • \$\begingroup\$ As a suggestion, feel free to check out (or implement) the c# Minesweeper library I built. All it requires is a UI and some minor client logic. It handles all the complicated internal logic, including chording, and has a simple API. \$\endgroup\$ – Brad M Mar 12 at 15:58
  • \$\begingroup\$ @Brad M Thanks for the suggestion. Unfortunately, my school wants us to create the program ourselves. If this wasn't the case I would definitely check it out. \$\endgroup\$ – Stijn Hendriks Mar 12 at 16:17
6
\$\begingroup\$

So what it looks like your doing is going through a list of Controls inside of groupBox1 and trying to figure out what they are and if they are one of you random buttons. You're doing this by naming all the buttons the same but adding there number to the end and then searching them by going through each controller in the groupBox1 and checking their name agents the ones you have generated.

There is a way to speed this up a bunch by using a List instead of every time you need to find the correct item looping through groupBox1 and checking ever name. You have already created a list but you filled it with newly created buttons that you actual never used. I would suggest just looping through the groupBox1 and adding all the Controls to the list.

Here is a example. (Note if groupBox1 has more than just buttons you might want to check its type to make sure it is a button and not something else)

//Creates and populates listButton with all button controls
List<Control> listButtons = new List<Control>();
foreach (Control item in groupBox1.Controls)
    listButtons.Add(item);

Now you have all the buttons in a list (hopefully in order (I don't know how you setup groupBox1)) and we can start doing the changes you wanted.

Next we want to set all buttons to Green and then we can change the color of the once we want. You are already doing this with the //set forecolor of the not selected buttons to green But we are just going to change it to now work with listButtons. Also if you want to optimize this more just set the buttons colors to green when you create them in groupBox1 Unfortunately, I cannot see were you created this group so I cannot help with that

foreach (Control item in listButtons)
{
    item.ForeColor = Color.Green;
}

Next we want to create a for loop for every time you want you had a random number. and then inside the for loop we want to create this new random number. Now we want to use that random number to access that button from the list and change its color to orange. And to change the red buttons Red.

Random rnd = new Random();

for (int i = 1; i <= 4; i ++)
{
    int listLength = listButtons.Count - 1;
    int randomNumber = rnd.Next(listLength);

    int minOrange1 = randomNumber - orange1;
    int plusOrange1 = randomNumber + orange1;

    int minOrange2 = randomNumber - orange2;
    int plusOrange2 = randomNumber + orange2;

    //Sets the red random buttons red
    listButtons[randomNumber].ForeColor = Color.Red;
    //Sets all the orange random buttons orange
    if (listLength <= minOrange1 && minOrange1 >= 0)
        listButtons[minOrange1].ForeColor = Color.Orange;
    if (listLength <= plusOrange1 && plusOrange1 >= 0)
        listButtons[plusOrange1].ForeColor = Color.Orange;
    if (listLength <= minOrange2 && minOrange2 >= 0)
        listButtons[minOrange2].ForeColor = Color.Orange;
    if (listLength <= plusOrange2 && plusOrange2 >= 0)
        listButtons[plusOrange2].ForeColor = Color.Orange;
}

Now if we put it all together the new ShuffleMines() should look something like this (Note you might have to make some tweaks to get it to work within your game. Let me know if you need help or if the code just won't build because of a error I made)

Make sure you added all the buttons in order in groupBox1

public void ShuffleMines()
{
    //Creates and populates listButton with all button controls
    List<Control> listButtons = new List<Control>();
    foreach (Control item in groupBox1.Controls)
        listButtons.Add(item);

    foreach (Control item in listButtons)
        item.ForeColor = Color.Green;

    Random rnd = new Random();

    //Loops for all 4 random sets of buttons
    for (int i = 1; i <= 4; i++)
    {
        int listLength = listButtons.Count - 1;
        int randomNumber = rnd.Next(listLength);

        int minOrange1 = randomNumber - orange1;
        int plusOrange1 = randomNumber + orange1;

        int minOrange2 = randomNumber - orange2;
        int plusOrange2 = randomNumber + orange2;



        //Sets the red random buttons red
        listButtons[randomNumber].ForeColor = Color.Red;
        //Sets all the orange random buttons orange
        if (listLength >= minOrange1 && minOrange1 >= 0)
            listButtons[minOrange1].ForeColor = Color.Orange;
        if (listLength >= plusOrange1 && plusOrange1 >= 0)
            listButtons[plusOrange1].ForeColor = Color.Orange;
        if (listLength >= minOrange2 && minOrange2 >= 0)
            listButtons[minOrange2].ForeColor = Color.Orange;
        if (listLength >= plusOrange2 && plusOrange2 >= 0)
            listButtons[plusOrange2].ForeColor = Color.Orange;
    }
}
\$\endgroup\$
  • \$\begingroup\$ @Stijn Hendriks Just wanted to say thanks for adding the designer code to your question. I wanted to ask you to but unfortunately, you cannot comment on other people questions when you have less then 50 rep. My answer was made without seeing it but it should all work. I dont have time now (IT took me like 35 minutes to type the answer out) to change anything from it. I hope it helps you! \$\endgroup\$ – Tyler Gregorcyk Mar 12 at 16:02
  • \$\begingroup\$ I implemented your code into the program and it gave me a new sort error. It gave me this: "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'" And the few times that it did work, it doesn't put the orange color in the right place for some reason. \$\endgroup\$ – Stijn Hendriks Mar 12 at 16:12
  • \$\begingroup\$ @StijnHendriks Ah yes I forgot to check if the button was in the list. I have corrected the code \$\endgroup\$ – Tyler Gregorcyk Mar 12 at 16:20
  • \$\begingroup\$ I changed the code to the new code and I still get the same error. I was also wondering where you have the following line: "Random rnd = new Random();" Are you sure this code works or am I doing something wrong? \$\endgroup\$ – Stijn Hendriks Mar 12 at 16:40
  • \$\begingroup\$ @StijnHendriks Yes I also forgot to add back the creation of the random. I have added it the script. You should be able to figure out any other issues. Luckily C# has a rely good error system and the errors are pretty strait forward. Also if you are using VS or Rider or another modern IDE it will show you what line it failed at and then what the error is. Let me know if you need any help and what other errors you found and how to fix them. I wont be able to respond till the morning though if you need help because im heading off to bed. I hope you do well on your project! \$\endgroup\$ – Tyler Gregorcyk Mar 12 at 16:46
0
\$\begingroup\$

Problems:

  • ShuffleMines only works for exactly 4 mines. It also contains a fair amount of duplicate code. Changing the number of mines requires a decent amount of work.
  • The random tile selection does not take duplicates into account. You may end up with less than 4 mines, but elsewhere you assume that there are exactly 21 empty tiles.
  • Going through all buttons and comparing their name against what's essentially a list of names is not a very efficient approach.
  • You're treating a 5x5 grid as a single list, and you're using an offset of 1 to find the buttons directly left and right of the current one. That does not work correctly for buttons on the left or right edge of the grid - you'll end up with an orange button on the opposite edge.
  • The game-over logic does not stop the game timer.

Suggestions:

Why not treat these buttons as an actual grid? A Button[][] buttonsGrid field would let you access buttons by their coordinates: buttonsGrid[x][y]. That also makes it easier and more obvious to access a neighboring button: buttonsGrid[x + 1][y] gives you the button directly to the right. You'll need to guard against invalid coordinates, so write a few helper methods:

private bool IsValidCoordinate(int x, int y)
{
    return x >= 0 && x < BoardWidth && y >= 0 && y < BoardHeight;
}

private void SetButtonColor(int x, int y, Color color)
{
    if (!IsValidCoordinate(x, y))
        return;

    buttonsGrid[x][y].ForeColor = color;
}

Now, instead of having a method that places exactly 4 mines, it's better to have a method that places 1 mine. If you want to add more mines, you would simply call that method multiple times:

private void AddMine(int x, int y)
{
    SetButtonColor(x, y, Color.Red);

    SetButtonColor(x - 1, y, Color.Orange);
    SetButtonColor(x, y - 1, Color.Orange);
    SetButtonColor(x + 1, y, Color.Orange);
    SetButtonColor(x, y + 1, Color.Orange);
}

However, the above method could accidentally overwrite existing mines. One way to solve that is to check that a button isn't red before overwriting its color, so a GetButtonColor method would be useful.


One issue here is that it's still using UI elements to store actual game state. That not only ties the game heavily to a specific UI, it also results in code that's harder to understand. It's better to have a grid of Tile objects, where each Tile contains information such as whether it's a mine, how many mines are nearby, whether it's been uncovered by the player or marked with a flag, and so on. Something like tile.HasMine or tile.IsFlagged is much more self-explanatory than tile.ForeColor == Color.Red or tile.ForeColor == Color.Black.


Other improvements would be to generate buttons based on the tile grid, which makes it easier to support different board sizes. It may also be a good idea to store tile coordinates in a buttons Tag property, so you can quickly look up the associated tile:

button.Tag = new Point(x, y);
...
if (button.Tag is Point position)
{
    var tile = GetTile(position.X, position.Y);
    if (tile.IsMine)
        ...
}

Other notes:

  • Regions can be useful to group related things together, but that's often a sign that classes might be doing too many different thing. Surrounding every method with a region only clutters the code.
  • Use comments to explain things that the code itself cannot tell you, such as why you decided to do something the way you did, or how or for what purpose a method is intended to be used, or certain gotcha's that a caller should be aware of. Repeating method names is not useful.
  • I'd rename Win to CheckWinCondition - it more accurately describes what the method does.
  • string.Format("button{0}", id) can be written more succinctly with an interpolated string: $"button{id}".
\$\endgroup\$
  • \$\begingroup\$ First of all, thank you for addressing all the problems I have and for including some other notes that helped me out. And second, thank you for giving me some solutions. Unfortunately, the level of your solution goes above my head since I am still a beginner. I should have said that in the beginning, so sorry about that. If I had some more experience I would definitely use your solution, but because I am not and Tyler stayed closer to my current level of programming skill, I chose for his answer. \$\endgroup\$ – Stijn Hendriks Mar 13 at 10:51
  • \$\begingroup\$ @StijnHendriks: no problem. We all have to start somewhere. \$\endgroup\$ – Pieter Witvoet Mar 13 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.