我正在尝试用c#编写俄罗斯方块。第一个木块的速度是正常的,但是第二个木块下降的速度是第一个的两倍,然后第三个木块下降的速度是第一个的三倍。我想一定是定时器坏了。
下面是我的部分代码:
Timer timer = new Timer();
private void Form1_Load(object sender, EventArgs e)
{
/* ... Some code ... */
Watch().Start();
}
public Timer Watch()
{
timer.Stop();
timer.Interval = 1000;
timer.Enabled = true;
/* ... Some code ... */
// Check if the block can fall down
if (CheckDown() == true)
{
timer.Tick += (sender, e) => timer_Tick(sender, e, Current_sharp.sharp);
}
return timer;
}
void timer_Tick(object sender, EventArgs e, Sharp sharp)
{
if (CheckDown())
{
/* ... Some code ... */
}
else
{
Watch().Start();
}
}
谁能告诉我为什么会这样? 问题是你的功能Watch()
。
事件每次被触发时都可以调用多个函数,这就是为什么它使用+=
符号而不是=
符号。每次调用timer.Tick += (sender, e) => timer_Tick(sender, e, Current_sharp.sharp);
时,您都在队列中添加了对timer_Tick
的额外调用。
所以第一次timer_Tick
被调用一次,然后它重新注册处理程序,然后第二次左右timer_Tick
被调用两次,它添加了2个更多的触发队列(使其4)…等等。
不查看完整的代码是我能想到的最好的解决问题的方法。我所做的就是将timer.Tick
注册从Watch()
移动到Form1_Load()
Timer timer = new Timer();
private void Form1_Load(object sender, EventArgs e)
{
/* ... Some code ... */
//regester the event handler here, and only do it once.
timer.Tick += (sender, e) => timer_Tick(sender, e, Current_sharp.sharp);
Watch().Start();
}
public Timer Watch()
{
timer.Stop();
timer.Interval = 1000;
timer.Enabled = true;
/* ... Some code ... */
return timer;
}
void timer_Tick(object sender, EventArgs e, Sharp sharp)
{
if (CheckDown())
{
/* ... Some code ... */
}
else
{
Watch().Start();
}
}
也许你正在执行这个:
timer.Tick += ...
对每个块使用多次 ?
似乎应该在构造函数中。现在的位置:just have:
if(...)
timer.Enabled = true;
else
timer.Enabled = false;
你的问题(可能)在这里:
void timer_Tick(object sender, EventArgs e, Sharp sharp)
{
if (CheckDown())
{
Some code.....
}
else
{
Watch().Start();
}
//throw new NotImplementedException();
}
我不知道你的CheckDown()背后的逻辑,但我假设它返回false*当块触摸下来?在这种情况下,每次一个块下降,它创建一个新的计时器,而你已经有一个定时器从Form1_Load()运行…