首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >俄罗斯方块计时器不工作

俄罗斯方块计时器不工作
EN

Stack Overflow用户
提问于 2013-05-24 03:51:16
回答 3查看 287关注 0票数 2

我正在尝试用c#编写俄罗斯方块。第一个积木的速度是正常的,但是第二个积木下降的速度是第一个积木的两倍,那么第三个积木的速度是第一个积木的三倍。我想定时器一定是出了什么问题。

下面是我的代码的一部分:

代码语言:javascript
运行
复制
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();
    }
}

有人能告诉我为什么会这样吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 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()

代码语言:javascript
运行
复制
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();
    }
}
票数 1
EN

Stack Overflow用户

发布于 2013-05-24 03:54:51

你的问题(可能)在这里:

代码语言:javascript
运行
复制
void timer_Tick(object sender, EventArgs e, Sharp sharp)
{


    if (CheckDown())
    {
        Some code.....

    }
    else
    {
        Watch().Start();
    }

    //throw new NotImplementedException();
}

我不知道CheckDown()背后的确切逻辑,但我假设它在块触地时返回false*?在这种情况下,每次块下降时,它都会创建一个新的计时器,而您已经从Form1_Load()...hence中运行了一个计时器,因此您可以看到速度的逐步提高。

票数 0
EN

Stack Overflow用户

发布于 2013-05-24 03:58:06

也许您正在执行以下操作:

代码语言:javascript
运行
复制
timer.Tick += ...

每个区块要执行多少次?

看起来这应该在构造函数中。它现在在哪里:只需拥有:

代码语言:javascript
运行
复制
if(...)
   timer.Enabled = true;
else
   timer.Enabled = false;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16722665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档