I’m trying to write a simple game based on selecting the correct answer (A B or C) from several question like a school test, and count the correct/incorrect answers to set a score.
I can t figure how to use an NSArray to store all the questions and correct answers and how to set a score. My only solution is to create a new View for each question but it sounds me like a bad solution.
Any help will be truly appreciated.
Thanks
ViewController.h
@interface ViewController : UIViewController {
IBOutlet UILabel *numPregunta;
IBOutlet UILabel *pregunta;
IBOutlet UILabel *lblRespuesta1;
IBOutlet UILabel *lblRespuesta2;
IBOutlet UILabel *lblRespuesta3;
IBOutlet UILabel *lblResultado;
IBOutlet UIButton *respuesta1;
IBOutlet UIButton *respuesta2;
IBOutlet UIButton *respuesta3;
}
-(IBAction)btnRespuesta1:(id)sender;
-(IBAction)btnRespuesta2:(id)sender;
-(IBAction)btnRespuesta3:(id)sender;
-(IBAction)nextPregunta:(id)sender;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
numPregunta.text = @"Question 1";
pregunta.text = @"Question 1 text";
lblRespuesta1.text = @"ANSWER 1";
lblRespuesta2.text = @"ANSWER 2";
lblRespuesta3.text = @"ANSWER 3 ";
[super viewDidLoad];
}
-(IBAction)btnRespuesta1:(id)sender
{
if(pregunta.text == @"Question 1 text")
{
lblRespuesta1.textColor = [UIColor redColor];
lblResultado.text = @"False! ";
lblResultado.textColor = [UIColor redColor];
}
}
-(IBAction)btnRespuesta2:(id)sender
{
if(pregunta.text == @"Question 1 text")
{
lblRespuesta2.textColor = [UIColor redColor];
lblResultado.text = @"False! ";
lblResultado.textColor = [UIColor redColor];
}
}
-(IBAction)btnRespuesta3:(id)sender
{
if(pregunta.text == @"Question 1 text")
{
lblRespuesta3.textColor = [UIColor greenColor];
lblResultado.text = @"Nice! ";
lblResultado.textColor = [UIColor greenColor];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
You can have an array of question say questionsArray, which will contain all questions.Second create array of dictionary which will contain all options and correct result say resultArray contain at 0 index dictionary with keys Answer1, Answer2, Answer3 and result and value will contain corresponding values.Now take one global variable which will store the question number means which question it is displaying, say question0, question1..etc, which is nothing but question index in questionsArray.Say you are displaying question at index 0,then display options corresponding to that index ie 0 as follows:
and say correct answer is answer2, then result key will be 2.
and provide tag o each button like 1,2 and 3.
then in Button action you can check whether user has selected correct option or not as follows: