winforms 点击按钮不会做任何事情

4urapxun  于 2023-06-24  发布在  其他
关注(0)|答案(3)|浏览(108)

我在Windows窗体中为一个学校项目编写此代码。它基本上是一个智力游戏,你必须记住数字在正方形中的位置。问题是,我被困在点击显示数字的按钮的一部分。下面是我的代码(更新后的版本仍然没有点击按钮的结果):

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

namespace Project
{
    public partial class Form1 : Form
    {
        private const int MaxLevel = 25;
        private const int ShowTimeMilliseconds = 1000;
        private const int InitialTimeSeconds = 5;

        private Button[] buttons;
        private int currentLevel;
        private int currentPlayerLevel;
        private bool gameStarted;
        private bool showingNumbers;
        private Timer showNumbersTimer;
        private Timer gameTimer;
        private Random random;

        public Form1()
        {
            InitializeComponent();
            InitializeButtons();
            random = new Random();
        }

        private void InitializeButtons()
        {
            buttons = new Button[] { button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16, button17, button18, button19, button20, button21, button22, button23, button24, button25, button26 };

            foreach (var button in buttons)
            {
                button.Click += Button_Click;
            }

            startButton.Click += startButton_Click;
        }

        private void InitializeGame()
        {
            currentPlayerLevel = 1;
            currentLevel = 1;
            UpdateLevelLabel();
        }

        private void StartGame()
        {
            gameStarted = true;
            gameTimer = new Timer();
            gameTimer.Interval = 1000;
            gameTimer.Tick += GameTimer_Tick;
            gameTimer.Start();

            InitializeGame();

            int randomButtonIndex = random.Next(0, currentLevel * currentLevel);

            foreach (Button button in buttons)
            {
                button.Text = string.Empty;
            }

            ShuffleButtons();

            buttons[randomButtonIndex].Text = "1";

            StartNewLevel();

            startButton.Enabled = false;
        }

        private void ShuffleButtons()
        {
            int n = buttons.Length;
            while (n > 1)
            {
                n--;
                int k = random.Next(n + 1);
                Button value = buttons[k];
                buttons[k] = buttons[n];
                buttons[n] = value;
            }
        }

        private void StartNewLevel()
        {
            showingNumbers = true;
            DisableButtons();

            List<int> numbers = Enumerable.Range(1, currentLevel).ToList();
            numbers = numbers.OrderBy(x => random.Next()).ToList();

            int randomButtonIndex = random.Next(0, currentLevel);

            for (int i = 0; i < currentLevel; i++)
            {
                buttons[i].Text = numbers[i].ToString();
                buttons[i].BackColor = Color.LightGreen;
                buttons[i].Enabled = true;
            }

            buttons[randomButtonIndex].Text = "1";

            showNumbersTimer = new Timer();
            showNumbersTimer.Interval = ShowTimeMilliseconds;
            showNumbersTimer.Tick += ShowNumbersTimer_Tick;
            showNumbersTimer.Start();
        }

        private void EndLevel()
        {
            showingNumbers = false;
            showNumbersTimer.Stop();
            ClearButtons();
            EnableButtons();
        }

        private void EndGame()
        {
            gameStarted = false;
            gameTimer.Stop();
            currentPlayerLevel = 0;
            UpdateLevelLabel();
            MessageBox.Show("Game Over!");
        }

        private void UpdateLevelLabel()
        {
            textBox1.Text = $"Level: {currentPlayerLevel}";
        }

        private void ShowNumbersTimer_Tick(object sender, EventArgs e)
        {
            int index = Array.FindIndex(buttons, button => button.Text == "1");
            buttons[index].BackColor = SystemColors.Control;
            buttons[index].Text = string.Empty;

            EndLevel();
        }

        private int initialTimeSeconds = InitialTimeSeconds;

        private void GameTimer_Tick(object sender, EventArgs e)
        {
            initialTimeSeconds--;

            if (initialTimeSeconds < 0)
            {
                gameTimer.Stop();
                EndGame();
            }

            UpdateTimerLabel();
        }

        private void UpdateTimerLabel()
        {
            textBox2.Text = initialTimeSeconds.ToString();
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            if (showingNumbers)
                return;

            int expectedNumber = currentPlayerLevel;

            if (button.Text == expectedNumber.ToString())
            {
                currentPlayerLevel++;

                if (currentPlayerLevel > MaxLevel)
                {
                    gameTimer.Stop();
                    EndGame();
                }
                else if (currentPlayerLevel > currentLevel)
                {
                    currentLevel++;
                    UpdateLevelLabel();
                    StartNewLevel();
                }
            }
        }

        private void DisableButtons()
        {
            foreach (Button button in buttons)
            {
                button.Enabled = false;
            }
        }

        private void EnableButtons()
        {
            foreach (Button button in buttons)
            {
                button.Enabled = true;
            }
        }

        private void ClearButtons()
        {
            foreach (Button button in buttons)
            {
                button.Text = string.Empty;
                button.BackColor = SystemColors.Control;
            }
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            if (!gameStarted)
            {
                InitializeGame();
                StartGame();
            }
        }
    }
}

还有一些窗体启动时的外观图像:
program when startedform
我试着用代码添加按钮,但效果不好,我希望程序允许我点击按钮并实际工作。

hgtggwj0

hgtggwj01#

对于基本按钮或其他控件,可以通过Visual Studio设计器中的控件属性窗格将控件连接到事件处理程序。但是你想让所有这些按钮使用相同的方法,这有点奇怪。在这种情况下,您可以在代码中连接事件处理程序:

private void InitializeButtons()
{
    buttons = new Button[] { button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16, button17, button18, button19, button20, button21, button22, button23, button24, button25, button26 };

    foreach(var button in buttons)
    {
        button.Click += this.Button_Click;
    }
}
  • 请确保此InitializeButtons()方法只被调用一次!*

这也让我很难过:

buttons.OrderBy(b => Guid.NewGuid())

大多数情况下,它只会比O(n)差一点,但有可能进入罕见的病理情况,这需要很长时间才能完成。相反,查找如何进行Fisher-Yates shuffle,这保证为O(n)。
这也让我很难过:

Random random = new Random();

线本身是好的,但它在错误的地方。如果PRNG是长期存在的,而不是局限于一个方法,您的情况会好得多。而是将其范围限定到类(窗体)或应用程序。

esyap4oy

esyap4oy2#

要处理按钮上的单击事件,可以双击Form1.cs[Design]文件中的按钮。它将在中添加eventHandler:InitializeComponent();
像这样:this.button1.Click += new System.EventHandler(this.button1_Click);
最好不要修改InitializeComponent文件,但您仍然可以使用以下内容更改行:this.button1.Click += new System.EventHandler(this.Button_Click);当button1被按下时,这将调用你的函数Button_Click(),然后你可以将它应用到你所有的按钮上。
或者(也是最佳实践),您可以将函数InitializeButtons()修改为:

private void InitializeButtons()
        {
            buttons = new Button[] { button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16, button17, button18, button19, button20, button21, button22, button23, button24, button25, button26 };
            foreach(var button in buttons)
            {
                button.Click += new System.EventHandler(this.Button_Click);
            }
            startButton.Click += new System.EventHandler(this.startButton_Click);
        }

它将为按钮中的每个按钮创建EventHandler,当您单击按钮时,它将调用函数Button_Click();

ctzwtxfj

ctzwtxfj3#

我纠正了你的游戏,但它可能不完全做你想要的。

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

namespace Project
{
    public partial class Form1 : Form
    {
        private const int MaxLevel = 25;
        private const int ShowTimeMilliseconds = 1000;
        private const int InitialTimeSeconds = 15;

        private Button[] buttons;
        private int currentLevel;
        private int currentPlayerLevel;
        private bool gameStarted;
        private bool showingNumbers;
        private Timer showNumbersTimer;
        private Timer gameTimer;
        private Random random;
        private List<string> toRememberOrder = new List<string>();

        public Form1()
        {
            InitializeComponent();
            InitializeButtons();
            random = new Random();
        }

        private void InitializeButtons()
        {
            buttons = new Button[] { button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16, button17, button18, button19, button20, button21, button22, button23, button24, button25, button26 };

            foreach (var button in buttons)
            {
                button.Click += Button_Click;
            }

            startButton.Click += startButton_Click;
        }

        private void InitializeGame()
        {
            currentPlayerLevel = 1;
            currentLevel = 1;
            UpdateLevelLabel();
        }

        private void StartGame()
        {
            gameStarted = true;
            gameTimer = new Timer();
            gameTimer.Interval = 1000;
            gameTimer.Tick += GameTimer_Tick;
            gameTimer.Start();

            InitializeGame();

            int randomButtonIndex = random.Next(0, currentLevel * currentLevel);

            foreach (Button button in buttons)
            {
                button.Text = string.Empty;
            }

            ShuffleButtons();

            //buttons[randomButtonIndex].Text = "1";

            StartNewLevel();

            startButton.Enabled = false;
        }

        private void ShuffleButtons()
        {
            int n = buttons.Length;
            while (n > 1)
            {
                n--;
                int k = random.Next(n + 1);
                Button value = buttons[k];
                buttons[k] = buttons[n];
                buttons[n] = value;
            }
        }

        private void StartNewLevel()
        {
            showingNumbers = true;
            ClearButtons();
            int randomButtonIndex;
            List<int> indexUsed = new List<int>();

            for (int i = 0; i < currentPlayerLevel; i++)
            {
                randomButtonIndex = GetRandomIndexNotUse(indexUsed);
                indexUsed.Add(randomButtonIndex);
                buttons[randomButtonIndex].Text = (i+1).ToString();
                buttons[randomButtonIndex].BackColor = Color.LightGreen;
                buttons[randomButtonIndex].Enabled = true;
                toRememberOrder.Add(buttons[randomButtonIndex].Name);
            }

            //buttons[randomButtonIndex].Text = "1";
            show_num = currentPlayerLevel;
            showNumbersTimer = new Timer();
            showNumbersTimer.Interval = ShowTimeMilliseconds;
            showNumbersTimer.Tick += ShowNumbersTimer_Tick;
            showNumbersTimer.Start();
        }
        
        private int GetRandomIndexNotUse(List<int> indexUsed)
        {
            int randomIndex = random.Next(0, buttons.Length - 1);
            if(indexUsed.Contains(randomIndex) == true)
            {
                randomIndex = GetRandomIndexNotUse(indexUsed);
            }
            return randomIndex;
        }

        private void EndLevel()
        {
            showingNumbers = false;
            showNumbersTimer.Stop();
            ClearButtons();
            EnableButtons();
        }

        private void EndGame()
        {
            gameStarted = false;
            gameTimer.Stop();
            currentPlayerLevel = 0;
            UpdateLevelLabel();
            MessageBox.Show("Game Over!");
        }

        private void UpdateLevelLabel()
        {
            textBox1.Text = $"Level: {currentPlayerLevel}";
        }

        private int show_num;
        private void ShowNumbersTimer_Tick(object sender, EventArgs e)
        {
            if (show_num == 0)
            {
                int index;
                for (int i = 0; i < currentPlayerLevel; i++)
                {
                    index = Array.FindIndex(buttons, button => button.Text == (i+1).ToString());
                    buttons[index].BackColor = SystemColors.Control;
                    buttons[index].Text = string.Empty;
                }
                showingNumbers = false;
                gameTimer.Start();
            }
            show_num--;
            //EndLevel();
        }

        private int initialTimeSeconds = InitialTimeSeconds;

        private void GameTimer_Tick(object sender, EventArgs e)
        {
            initialTimeSeconds--;

            if (initialTimeSeconds < 0)
            {
                gameTimer.Stop();
                EndGame();
            }

            UpdateTimerLabel();
        }

        private void UpdateTimerLabel()
        {
            textBox2.Text = initialTimeSeconds.ToString();
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            if (showingNumbers)
                return;

            if(button.Name == toRememberOrder.First())
            {
                toRememberOrder.Remove(button.Name);
            }
            else
            {
                gameTimer.Stop();
                EndGame();
            }
            if(toRememberOrder.Count() == 0)
            {
                gameTimer.Stop();
                Timer_Reset();
                currentPlayerLevel++;
                UpdateLevelLabel();
                StartNewLevel();
            }
        }

        private void DisableButtons()
        {
            foreach (Button button in buttons)
            {
                button.Enabled = false;
            }
        }

        private void EnableButtons()
        {
            foreach (Button button in buttons)
            {
                button.Enabled = true;
            }
        }

        private void ClearButtons()
        {
            foreach (Button button in buttons)
            {
                button.Text = string.Empty;
                button.BackColor = SystemColors.Control;
            }
        }

        private void Timer_Reset()
        {
            initialTimeSeconds = InitialTimeSeconds;
            UpdateTimerLabel();
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            if (!gameStarted)
            {
                InitializeGame();
                StartGame();
            }
        }
    }
}

相关问题