好的,所以,这段代码非常基本。用户在文本框中输入一个答案,如果它等于“第一+第二”,他们就得一分。然后,他们有 5 秒的时间来回答下一个数学问题。如果他们这样做了,函数“doCalculation”会再次运行,他们会得到另一分。如果他们不这样做,那么函数“onTimer”就会运行,并且会击中风扇。
问题是,当用户连续遇到多个正确的问题时,“doCalculation”会运行多次,然后我有多个计时器同时运行。这真的开始把游戏搞砸了。
我需要停止计时器。显然使用“无效”,但我不知道在哪里。我不能在计时器开始之前使计时器无效,所以... whhhhatt?
我不知道该怎么做的另一个选项,如果当你得到正确的问题时它只是将计时器设置回 5 秒而不是创建一个新的。但是如何判断计时器是否已经创建?我不确定最好的做法或语法是什么。想法?
非常感谢!
- (IBAction)doCalculation:(id)sender
{
NSInteger numAnswer = [answer.text intValue];
if ( numAnswer == first + second) {
numAnswered++;
NSString *numberAnsweredCorrectly = [[NSString alloc] initWithFormat:@"%d", numAnswered];
numCorrectlyAnswered.text = numberAnsweredCorrectly;
answer.text = @"";
NSTimer *mathTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
//Set the variables to two HUGE numbers, so they can't keep plugging in the same answer
first = arc4random() % 10;
second = arc4random() % 10;
NSString *firstString = [[NSString alloc] initWithFormat:@"%d", first];
NSString *secondString = [[NSString alloc] initWithFormat:@"%d", second];
firstNumber.text = firstString;
secondNumber.text = secondString;
}