I am developing a game for class where a timer is ran when a button is pressed.
-(void)setTimer{
self->mTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(buttonNotPushed) userInfo: nil repeats:NO];
}
-(void)resetTimer{
[self->mTimer invalidate];
self->mTimer = nil;
Here is a snippet of how the timer code is used.
- (IBAction)yellowDot1:(id)sender {
if ([_labelColor.text isEqualToString:#"Yellow"]) {
[ self Scoring];
[self label];
[self resetTimer];
[self setTimer];
}
else ([self GameOver]);
}
- (IBAction)redDot1:(id)sender {
if ([_labelColor.text isEqualToString:#"Red"]) {
[ self Scoring];
[self label];
[self resetTimer];
[self setTimer];
}
else ([self GameOver]);
}
The game presents with a Play button which modals over to the next screen. Currently at 5 seconds, I would like to create a "difficult" mode where at the home screen, the user clicks on a "difficult" button and the timer for the game runs at 2 seconds instead. Right now, I am contemplating duplicating my storyboard and view controllers and going that way where I just make the timer a different interval. Is a shorter way possible through code for a difficult mode?
Simply declare a global a variable for this. Use a class (maybe a singleton) that holds the mode and use a -(float) getGameDuration; method
lets say...
// GameHandler.h
static GameHandler *sharedInstance = nil;
#interface GameHandler : NSObject
{
GameMode *mode;
}
typedef enum{
GAMEMODE_EASY = 0,
GAMEMODE_NORMAL,
GAMEMODE_HARD
} GameMode;
-(float) getGameDuration;
implementation
// GameHandler.m
+ (GameHandler *)sharedInstance // implement singleton
{};
-(float) getGameDuration
{
switch(mode)
{
case GAMEMODE_EASY:
return 10.f;
case GAMEMODE_NORMAL:
return 5.f;
case GAMEMODE_HARD:
return 2.f;
}
return 5.f;
}
// your other classes
float gameDurration = [[GameHandler sharedInstance] getGameDuration];
self->mTimer = [NSTimer scheduledTimerWithTimeInterval:gameDurration
target:self
selector:#selector(buttonNotPushed)
userInfo:nil
repeats:NO];
Related
In the .h file I set up the Goodguy, Building1 and 2, the NSTimer, and the falldown method.
IBOutlet UIImageView *Goodguy;
IBOutlet UIImageView *Building1;
IBOutlet UIImageView *Building2;
NSTimer *GoodguyFall;
-(void)falldown;
In the .m file I set up the GoodguyFall NSTimer, and the code for when an image touches another image it will invalidate the NSTimer. How do I set it up so the timer is valid while it isn't touching the "buildings"?
-(void)viewDidLoad{
GoodguyFall = [ NSTimer scheduledTimerWithTimeInterval: 0.03 target:self selector:#selector(falldown) userInfo:nil repeats:YES];
}
-(void)falldown{
Goodguy.center = (CGPointMake(Goodguy.center.x, Goodguy.center.y + 6));
}
if (CGRectIntersectsRect(Goodguy.frame, Building1.frame)){
[GoodguyFall invalidate];
}
if (CGRectIntersectsRect(Goodguy.frame, Building2.frame)){
[GoodguyFall invalidate];
}
}
To get the Goodguy to fall again after not touching a building, you’ll need to schedule another timer. This can be accomplished by
-(void)BuidlingMoving{
if (CGRectIntersectsRect(Goodguy.frame, Building1.frame)){
[GoodguyFall invalidate];
GoodguyFall = nil;
}
else if (CGRectIntersectsRect(Goodguy.frame, Building2.frame)){
[GoodguyFall invalidate];
GoodguyFall = nil;
} else if (GoodguyFall == nil) {
GoodguyFall = [ NSTimer scheduledTimerWithTimeInterval: 0.03 target:self selector:#selector(falldown) userInfo:nil repeats:YES];
}
}
In this solution, I’m handling the case where Goodguy is no longer in contact with a building.
I want to execute some codes with a time sequence like [5s, 10s, 10s, 20s], which means that it executes the code after 5 seconds, and executes it the second time after 10s. I want to use NSTimer, but I can not figure out how can I do.
My method is a bit simpler to implement.
- (void)startExecute
{
intervals=#[#(5),#(10),#(10),#(20)]; // class member
isExecuting=YES; // class member
[self executeTaskAtIndex:0]; // start first task
}
- (void)executeTaskAtIndex:(NSUInteger)index
{
if (index>=intervals.count || !isExecuting) // no intervals left or reset execution
return;
NSNumber *intervalNumber=intervals[index];
NSTimeInterval interval=intervalNumber.doubleValue;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if(!isExecuting)
return;
// execute your task here
//...
index++;
[self executeTaskAtIndex:index]; // another iteration
});
}
Create a data structure to hold the time intervals, the target and the action to execute:
(untested)
typedef struct {
NSTimeInterval interval;
id target;
SEL selector;
} ScheduledItem;
Then create an array of these items:
static ScheduledItem _schedule[] = {
{ 5.0, someTarget, #selector(someMethod) },
{ 10.0, someTarget, #selector(someMethod) },
{ 15.0, someTarget, #selector(someMethod) }
};
#define NUM_SCHEDULED_ITEMS (sizeof(schedule) / sizeof(schedule[0]))
and then create a timer somewhere to dispatch the work:
#interface MyClass ()
{
NSTimer *_timer;
unsigned _scheduledItem;
}
- (void)_setupTimer;
- (void)_timerFired:(NSTimer *)timer;
#end
#interface MyClass
- (instancetype)init
{
self = [super init];
if (self) {
_scheduledItem = 0;
[self _setupTimer];
}
return self;
}
- (void)_setupTimer
{
_timer = nil;
if (_scheduledItem < NUM_SCHEDULED_ITEMS) {
NSTimeInterval interval = _schedule[_scheduledItem].interval
_timer = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:#selector(_timerFired:)
userInfo:nil
repeats:NO];
}
}
- (void)_timerFired:(NSTimer *)timer
{
id target = _schedule[_scheduledItem].target;
SEL action = _schedule[_scheduleItem].action;
[target performSelector:action withObject:nil];
_scheduledItem++;
[self _setupTimer];
}
You will most probably have to set-up the _schedule array at runtime, as the target won't be available at compile time. If it's always self then you can leave it out of the schedule altogether and if you always call the same selector then you can leave that out too, leaving just an array of time intervals.
I'm trying to create a simple countdown timer app for myself. So far I've figured out how to create the countdown timers with a stop/reset action on them for a single button I've got attached to the timer.
However, I would like to add multiple timers to the same page and I'm not really sure how to do about making extra calls for the timers. Each of the timers would have it's own number to count down from (7 minutes for one, 3 minutes for the other, etc). These are set intervals that the user is not able to change. Google hasn't really worked out for me on how to do this so I'm hoping someone can at least guide me in the right direction. Below is my code snippets:
ViewController.h
#interface ViewController : UIViewController {
IBOutlet UILabel *firstCountdownLabel;
NSTimer *firstCountdownTimer;
bool timerActive;
int secondsCount;
}
- (IBAction)start:(id)sender;
- (void)timerRun;
#end
ViewController.m
#interface ViewController ()
#end
#implementation ViewController
- (void) timerRun {
secondsCount = secondsCount - 1;
int minutes = secondsCount / 60;
int seconds = secondsCount - (minutes * 60);
NSString *timerOutput = [NSString stringWithFormat:#"%2d:%.2d", minutes, seconds];
firstCountdownLabel.text = timerOutput;
if (secondsCount == 0) {
[firstCountdownTimer invalidate];
firstCountdownTimer = nil;
}
}
//- (void) setTimer {
- (IBAction)start:(id)sender {
secondsCount = 420;
if (timerActive == NO) {
timerActive = YES;
self->firstCountdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerRun) userInfo:nil repeats:YES];
}
else {
timerActive=NO;
[self->firstCountdownTimer invalidate];
self->firstCountdownTimer = nil;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self setTimer];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Google doesn't help in showing you how to implement original application ideas.
If you want multiple timers, define multiple timer instance variables:
#interface ViewController : UIViewController
{
IBOutlet UILabel *timer1Label;
IBOutlet UILabel *timer2Label;
IBOutlet UILabel *timer3Label;
NSTimer *timer1;
NSTimer *timer2;
NSTimer *timer3;
int timer1Count;
int timer2Count;
int timer3Count;
bool timer1Active;
bool timer2Active;
bool timer3Active;
}
Then create a separate IBAction for each button that starts each of the timers:
- (IBAction)startTimer1:(id)sender
{
timer1Count = 420;
if (timer1Active == NO)
{
timer1Active = YES;
timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timer1Run:)
userInfo:nil
repeats:YES];
}
else
{
timer1Active=NO;
[timer1 invalidate];
timer1 = nil;
}
}
- (void) timer1Run: (NSTimer*) timer
{
timer1Count -= 1;
int minutes = timer1Count / 60;
int seconds = timer1Count - (minutes * 60);
NSString *timerOutput = [NSString stringWithFormat:#"%2d:%.2d", minutes, seconds];
timer1Label = timerOutput;
if (timer1Count == 0) {
[timer2 invalidate];
timer2 = nil;
}
}
Duplicate the above code for each timer, using "timer2" and "timer3" in place of "timer1". Change the time counts for each one to the desired values. (I changed the names from "firstTimer" to "timer1" because it's easier to edit the code to support multiple timers that way.
I did not write 3 versions of each method for you because you need to figure this out rather than copy & pasting in code that you don't understand.
It would be possible, and require less code, to use the same IBAction method for all your start timer buttons, and have the code check the tag on the button to decide which timer to start.
The code might look like this:
- (IBAction)startTimer1:(id)sender
{
int tag = [sender tag];
switch (tag)
{
case 1: //timer 1
//Put code to start timer 1 here
break;
case 2: //timer 2
//put code to start timer 2 here
break;
}
}
But that might be a bit over your head at the moment.
By the way, forget you ever saw the "self->variable" syntax. it is slower and more error-prone than just referring to the instance variable directly. using object->variable syntax also allows you to access the instance variables of other objects, which is bad practice. You should always use properties to access the instance variables of objects other than yourself.
Also, the timer method should take a single parameter, a timer. I corrected the timer method in the above code.
Create a class as YourTimer with few properties like
NSString *timerLabel;
NSTimer *timer;
NSInteger timerCounter;
Now create an array of YourTimer objects. Then you can access it easily.
This will be modular, maintainable and reusable code, as may be later on you need one more identifier to be with all timers, hence wrap them in one class and use it.
I am developing an iPAD application and I want to auto save the contents of the form into SQLITE in every 10 sec intervals. Right now if I press the save button then it saves to the database. Is there any way to auto save the whatever I am writing in the form in every 10-15 seconds. Help me out with this.
Use NSTimer and perform the save every x minutes. The code will look something like this. It is a modified version of the code here.
#interface MyController : UIViewController
{
#private
NSTimer * countdownTimer;
NSUInteger remainingTicks;
}
-(IBAction)doCountdown: (id)sender;
-(void)handleTimerTick;
-(void) saveData;
#end
#implementation MyController
// { your own lifecycle code here.... }
-(IBAction)doCountdown: (id)sender
{
if (countdownTimer)
return;
remainingTicks = 60;
[self saveData];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: #selector(handleTimerTick) userInfo: nil repeats: YES];
}
-(void)handleTimerTick
{
remainingTicks--;
[self updateLabel];
if (remainingTicks <= 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
}
-(void) saveData
{
//Save your data here
}
#end
I'm trying to make multiple buttons fall down the screen all at once, at different speeds. But when I have my if statement check if it passed through the value, all the other buttons disappear with it. I'm also incrementing the score to go -1 each time a button passes through the Y value. Any help is appreciated, thanks.
- (void)b1Fall
{
b1.center = CGPointMake(b1.center.x, b1.center.y+6);
if (b1.center.y >= 506) {
[self updateScore];
b1.center = CGPointMake(44, 11);
}
}
- (void)b2Fall
{
b2.center = CGPointMake(b2.center.x, b2.center.y+7);
if (b2.center.y >= 506) {
[self updateScore];
b2.center = CGPointMake(160, 11);
}
}
- (void)b3Fall
{
b3.center = CGPointMake(b3.center.x, b3.center.y+8);
if (b3.center.y >= 506) {
[self updateScore];
b3.center = CGPointMake(276, 11);
}
}
- (void)updateScore
{
healthLabel.text = [NSString stringWithFormat:#"%d", [healthLabel.text intValue]-1];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// REMOVE AFTER TESTING
b1Timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(b1Fall) userInfo:nil repeats:true];
b2Timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(b2Fall) userInfo:nil repeats:true];
b2Timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:#selector(b3Fall) userInfo:nil repeats:true];
}
A few things:
1.) Put these animations in viewDidAppear instead of viewDidLoad - you want the animation to begin when the user is actually looking at the buttons, not when the view is loaded into memory, where the user may not be able to see it (viewDidLoad).
2.) Don't use NSTimer for animations, use this:
[UIView animateWithDuration:0.5
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
}
completion:^(BOOL finished){
// loop your animation here.
}];
3.) If you want to make a game, I don't recommend using this approach. All animations using UIKit are going to perform on the main thread and block the user flow. What you want is a framework like Cocos2D where the animations are doing in the GPU and ASYNC game logic is readily supported. UIKit isn't a good choice for game development in general.