我正在尝试用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();
}
}
有人能告诉我为什么会这样吗?
发布于 2013-05-24 04:05:42
问题出在你的函数Watch()
。
事件的每次触发时都可以调用多个函数,这就是为什么它使用+=
符号而不是=
符号。每次调用timer.Tick += (sender, e) => timer_Tick(sender, e, Current_sharp.sharp);
时,都会向队列中添加一个对timer_Tick
的额外调用。
因此,第一次调用timer_Tick
时,它会重新注册处理程序;第二次调用timer_Tick
时,会调用两次,并向队列中再添加两次触发(使其变为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();
}
}
发布于 2013-05-24 03:54:51
你的问题(可能)在这里:
void timer_Tick(object sender, EventArgs e, Sharp sharp)
{
if (CheckDown())
{
Some code.....
}
else
{
Watch().Start();
}
//throw new NotImplementedException();
}
我不知道CheckDown()背后的确切逻辑,但我假设它在块触地时返回false*?在这种情况下,每次块下降时,它都会创建一个新的计时器,而您已经从Form1_Load()...hence中运行了一个计时器,因此您可以看到速度的逐步提高。
发布于 2013-05-24 03:58:06
也许您正在执行以下操作:
timer.Tick += ...
每个区块要执行多少次?
看起来这应该在构造函数中。它现在在哪里:只需拥有:
if(...)
timer.Enabled = true;
else
timer.Enabled = false;
https://stackoverflow.com/questions/16722665
复制相似问题