我有一个迷宫游戏。按Enter键后,您可以输入作弊码,计时器也会暂停。但是在输入代码后,我的计时器恢复,但每秒减少3次。这是按Enter键的条件:
// gt.setTimer() is called at the moment the maze started
// I'm using getch to trap inputs
else if (move == 13) //Reads if Enter is pressed
{
pause = 1; //A Flag saying that the timer must be paused
gt.setTimer(pause); //Calls my setTimer() method
Console.Write("Enter Cheat: ");
cheat = Console.ReadLine();
pause = 0; //A Flag saying that the timer should resume
gt.setTimer(lives, pause); //Calls again the Timer
}
这是我的setTimer()代码:
static System.Timers.Timer t = new System.Timers.Timer();
static int gTime = 300;
public void setTimer(int pause)
{
t.Interval = 1000; // Writes the time after every 1 sec
if (pause == 1)
t.Stop(); // Stop the timer if you press Enter
else
t.Start(); // Starts the timer if not
t.Elapsed += new ElapsedEventHandler(showTimer);
}
public static void showTimer(object source, ElapsedEventArgs e)
{
Console.Write("Time " + gTime); //Writes time
gTime--; //Decrements the time
}
有什么问题吗?我错过了什么吗?
答案 0 :(得分:5)
问题出在setTimer
方法的最后一行。计时器处理程序应该在调用构造函数后只注册一次,而不是setTimer
。在elapsed timer事件中,处理程序被称为已注册的次数。因此,你使用的运算符越多+ =被调用的次数越多。
答案 1 :(得分:2)
每当你这样做时: t.Elapsed + = new ElapsedEventHandler(showTimer); 您为此事件添加了一个事件处理程序
此strind只运行一次,在初始化计时器的par代码中