How we can perform Action on Sequence UIButtons? - iphone

As My Screen shot show that i am working on word matching game.In this game i assign my words to different UIButtons in Specific sequence on different loctions(my red arrow shows this sequence)and of rest UIButtons i assign a one of random character(A-Z).when i Click on any UIButtons its title will be assign to UILabel which is in Fornt of Current Section:i campare this UILabel text to below UILabels text which is in fornt of timer.when it match to any of my UILabels its will be deleted.i implement all this process already.
But my problem is that which is show by black lines.if the player find the first word which is "DOG". he click the Two UIButtons in Sequence,but not press the Third one in Sequence.(as show by black line).so here i want that when player press the any UIButtons which is not in Sequence then remove the previous text(which is "DO") of UILabel and now the Text of UILabel is only "G" .
Here is my code to get the UIButtons titles and assign it UILabel.
- (void)aMethod:(id)sender
{
UIButton *button = (UIButton *)sender;
NSString *get = (NSString *)[[button titleLabel] text];
NSString *origText = mainlabel.text;
mainlabel.text = [origText stringByAppendingString:get];
if ([mainlabel.text length ]== 3)
{
if([mainlabel.text isEqualToString: a]){
lbl.text=#"Right";
[btn1 removeFromSuperview];
score=score+10;
lblscore.text=[NSString stringWithFormat:#"%d",score];
words=words-1;
lblwords.text=[NSString stringWithFormat:#"%d",words];
mainlabel.text=#"";
a=#"tbbb";
}
else if([mainlabel.text isEqualToString: c]){
lbl.text=#"Right";
[btn2 removeFromSuperview];
score=score+10;
lblscore.text=[NSString stringWithFormat:#"%d",score];
words=words-1;
lblwords.text=[NSString stringWithFormat:#"%d",words];
mainlabel.text=#"";
c=#"yyyy";
}
else
if([mainlabel.text isEqualToString: d]){
lbl.text=#"Right";
[btn3 removeFromSuperview];
score=score+10;
lblscore.text=[NSString stringWithFormat:#"%d",score];
words=words-1;
lblwords.text=[NSString stringWithFormat:#"%d",words];
mainlabel.text=#"";
d=#"yyyy";
}
else {
lbl.text=#"Wrong";
mainlabel.text=#"";
}
}}
Thanx in advance

Assign tag to each button from left to right.
So you will have,
GButton.tag = 0;
TButton.tag = 1;
DButton.tag = 2;
.
.
.
VButton.tag = 9;
.
.
.
EButton.tag = 18;
.
.
.
CButton.tag = 26;
Now keep the track of previous pressed button and current pressed button.
Call below function when your button delegate hits:
Write below code into your .h file
#define SEQ_TYPE_ANY 0
#define SEQ_TYPE_RIGHT 1
#define SEQ_TYPE_LEFT 2
#define SEQ_TYPE_TOP 3
#define SEQ_TYPE_BOTTOM 4
#define SEQ_TYPE_RIGHT_DIAGONAL_DOWN 5
#define SEQ_TYPE_RIGHT_DIAGONAL_UP 6
#define SEQ_TYPE_LEFT_DIAGONAL_DOWN 7
#define SEQ_TYPE_LEFT_DIAGONAL_UP 8
#define NO_OF_BUTTONS_IN_ROW 9
//Add below variables into your class
int curentSequence;
UILabel *resultLabel;
UIButton *previousButton;
//Declare property for previousButton
#property(nonatomic, retain) UIButton *previousButton;
//Write below code to .m file
#synthesize previousButton;
-(BOOL) isAdjacent:(UIButton *)currentButton
{
if(previousButton == nil)
{
resultLabel.text = currentButton.titleLabel.text;
curentSequence = SEQ_TYPE_ANY;
return TRUE;
}
if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_RIGHT) &&
(previousButton.tag + 1 == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_ANY;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_LEFT) &&
(previousButton.tag - 1 == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_LEFT;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_TOP) &&
(previousButton.tag - NO_OF_BUTTONS_IN_ROW == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_TOP;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_BOTTOM) &&
(previousButton.tag + NO_OF_BUTTONS_IN_ROW == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_BOTTOM;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_RIGHT_DIAGONAL_DOWN) &&
(previousButton.tag + NO_OF_BUTTONS_IN_ROW + 1 == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_RIGHT_DIAGONAL_DOWN;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_RIGHT_DIAGONAL_UP) &&
(previousButton.tag - NO_OF_BUTTONS_IN_ROW + 1 == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_RIGHT_DIAGONAL_UP;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_LEFT_DIAGONAL_UP) &&
(previousButton.tag - NO_OF_BUTTONS_IN_ROW - 1 == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_LEFT_DIAGONAL_UP;
return TRUE;
}
else if((curentSequence == SEQ_TYPE_ANY || curentSequence == SEQ_TYPE_LEFT_DIAGONAL_DOWN) &&
(previousButton.tag + NO_OF_BUTTONS_IN_ROW - 1 == currentButton.tag))
{
resultLabel.text = [resultLabel.text stringByAppendingString:currentButton.titleLabel.text];
curentSequence = SEQ_TYPE_LEFT_DIAGONAL_DOWN;
return TRUE;
}
else
{
resultLabel.text = #"";
curentSequence = SEQ_TYPE_ANY;
return FALSE;
}
}
// Event handler for button event
- (void)aMethod:(id)sender
{
UIButton *currentButton = (UIButton *)sender;
BOOL result = [self isAdjacent:currentButton];
if(result == FALSE)
{
self.previousButton = nil;
resultLabel.text = #"";
curentSequence = SEQ_TYPE_ANY;
}
else
{
self.previousButton = sender;
}
}
Hope it will help.

If I understand correctly, you need to know if the pushed button is adjacent to the previously pushed button? Use this function to test for adjacency in the grid:
bool isAdjacent(UIButton* current, UIButton* previous) {
if( !previous )
return false;
//Create a rectangle around the previous button (assuming all buttons are in a fixed grid)
CGRect previousRect = previous.frame;
CGRect adjacentRect = CGRectMake(previous.frame.origin.x - previous.frame.size.width,
previous.frame.origin.y - previous.frame.size.height,
previous.frame.size.width*3,
previous.frame.size.height*3);
return CGRectIntersectsRect(adjacentRect, previousRect);
}
And only append if they are adjacent, ie:
- (void)aMethod:(id)sender
{
UIButton *button = (UIButton *)sender;
static UIButton* previous = nil;
NSString *get = (NSString *)[[button titleLabel] text];
NSString *origText = mainlabel.text;
if( isAdjacent(button, previous) )
mainlabel.text = [origText stringByAppendingString:get];
previous = button;
//Rest of function
}

Fun question:
In this particular case, I agree with Luke about subclassing the UIButton. This way you could give each button an (X, Y) on your grid, as well as a (Xnext, Ynext) list for all of the possible expected next press locations (if the button itself can be used to make multiple words). Externally you will compare the currently being hit against the expected (Xnext, Ynext). If the two dont match, this is the signal you are looking for.
This is an answer that accounts for all of your situations, forward and backward horizontal (if you choose to implement backware), upward and downward vertical (if you choose to implement upward), and any diagonal, or any other combination you can come up with!
This also accounts for lets say hitting the D, then the O then trying to press the D again versus hitting the G. It also takes care of hitting the incorrect G.
Create a new .m .h pair of files (a new object) and give it your name.
Some example code for implementing a custom UIButton (h file):
#interface myConnectedUIButton : UIButton {
BOOL isAWordBeginCharacter;
unsigned int beginWordKey;
unsigned int myGridX;
unsigned int myGridY;
NSMutableArray * myConnectedSet;
}
-(id)init;
-(void)initWithGridX:(unsigned int)X GridY:(unsigned int)Y BeginChar:(BOOL)yesNo BeginWordKey:(unsigned int)key;
-(void)setGridPosWithX:(unsigned int)X Y:(unsigned int)Y;
-(void)setGridX:(unsigned int)X;
-(void)setGridY:(unsigned int)Y;
-(unsigned int)getGridX;
-(unsigned int)getGridY;
-(void)setIsABeginChar:(BOOL)yesNo;
-(BOOL)getIsABeginChar;
-(void)addPosToConnectedSetGridX:(unsigned int)X GridY:(unsigned int)Y WordKey:(unsigned int)key;
-(NSArray *)getMyConnectedSetArray;
-(void)clearConnectedSet;
#end
In the .m file of your
#implementation myConnectedUIButton
-(id)init{
[super init];
// Lets go ahead and initialize the NSMutableArray here also IFF it hasnt already been allocated
if( nil == myConnectedSet ){
myConnectedSet = [[NSMutableArray alloc] init];
}
// Lets also zero out the x, y position
myGridX = 0;
myGridY = 0;
// Lets also state that this is NOT a begin char for the time being and 0 for the begin char key
isAWordBeginCharacter = NO;
beginWordKey = 0;
return self;
}
-(void)initWithGridX:(unsigned int)X GridY:(unsigned int)Y BeginChar:(BOOL)yesNo BeginWordKey:(unsigned int)key{
// Lets go ahead and initialize the NSMutableArray here also IFF it hasnt already been allocated
if( nil == myConnectedSet ){
myConnectedSet = [[NSMutableArray alloc] init];
}
myGridX = X;
myGridY = Y;
isAWordBeginCharacter = yesNo;
beginWordKey = key;
}
-(void)setGridPosWithX:(unsigned int)X Y:(unsigned int)Y{
myGridX = X;
myGridY = Y;
}
-(void)setGridX:(unsigned int)X{
myGridX = X;
}
-(void)setGridY:(unsigned int)Y{
myGridY = Y;
}
-(unsigned int)getGridX{
return myGridX;
}
-(unsigned int)getGridY{
return myGridY;
}
-(void)setIsABeginChar:(BOOL)yesNo{
isAWordBeginCharacter = yesNo;
}
-(BOOL)getIsABeginChar{
return isAWordBeginCharacter;
}
-(void)addPosToConnectedSetGridX:(unsigned int)X GridY:(unsigned int)Y WordKey:(unsigned int)key{
[myConnectedSet addObject:[GridPointNext GridPointNextWithX:X GridPointY:Y NextWordKey:key]];
}
-(NSArray *)getMyConnectedSetArray{
return myConnectedSet;
}
-(void)clearConnectedSet{
[myConnectedSet removeAllObjects];
}
-(void)dealloc{
[myConnectedSet release];
[super dealloc];
}
#end
You will also now need a "GridPointNext" object.
The Grid Object header should look as follows:
#interface GridPointNext : NSObject {
unsigned int GridPointX;
unsigned int GridPointY;
unsigned int nextWordKey;
}
+(GridPointNext *)GridPointNextWithX:(unsigned int)X GridPointY:(unsigned int)Y NextWordKey:(unsigned int)key;
-(id)initWithX:(unsigned int)X GridPointY:(unsigned int)Y NextWordKey:(unsigned int)key;
-(unsigned int)getGridX;
-(unsigned int)getGridY;
-(unsigned int)getNextWordKey;
#end
The m file for the object should look as follows:
#implementation GridPointNext
+(GridPointNext *)GridPointNextWithX:(unsigned int)X GridPointY:(unsigned int)Y NextWordKey:(unsigned int)key{
GridPointNext * aPoint = [[GridPointNext alloc] initWithX:X GridPointY:Y NextWordKey:key];
[aPoint autorelease];
return aPoint;
}
-(id)initWithX:(unsigned int)X GridPointY:(unsigned int)Y NextWordKey:(unsigned int)key{
GridPointX = X;
GridPointY = Y;
nextWordKey = key;
return self;
}
-(unsigned int)getGridX{
return GridPointX;
}
-(unsigned int)getGridY{
return GridPointY;
}
-(unsigned int)getNextWordKey{
return nextWordKey;
}
#end
You will have to deal with the dealloc portion. This at least give you some tools for creating your custom button and your word list algorithm around it.

If I understand correctly. The user can only have a correct word, if the letters chosen are all sitting next to each other?
Have you tried this:
Keep two references. One UIButton for previousPressedButton and one UIButtonfor lastPressedButton.
First a user presses D. lastPressedButton will refer to the D.
Then a user presses O. previousPressedButton will be D. lastPressedButton will be O.
Now, get the width and height of the UIButtons and compare if the lastPressedButton.frame.origin.x will be less than width or -width away.
Also check if the lastPressedButton.frame.origin.y will be less than height or -height away.
Now you know if it's touching the previous button. Use this to decide if it's a new word or not.
I would put this into a method.
-(BOOL)isAdjacentLetter {
float buttonWidth = lastPressedButton.size.width;
float buttonHeight = lastPressedButton.size.height;
if(lastPressedButton.frame.origin.x>previousPressedButton.frame.origin.x+buttonWidth) return NO;
if(lastPressedButton.frame.origin.y>previousPressedButton.frame.origin.y+buttonHeight) return NO;
if(lastPressedButton.frame.origin.x<previousPressedButton.frame.origin.x-buttonWidth) return NO;
if(lastPressedButton.frame.origin.y<previousPressedButton.frame.origin.y-buttonHeight) return NO;
return YES;
}
Then whenever a button is clicked. you can use
if ([self isAdjacentLetter]) {
//still same word
} else {
//new word. erase
}
Or, if I understand differently. The words can only be made when the letters are in a row.Such as : From left to right. From down to up. From bottom right to top left etc.
In this case, determine all directions.
Such as, top left is 0, top is 1, top right is 2. right is 3. down right is 4. down is 5. down left is 6. left is 7.
When two buttons are clicked, store the directions. For example:
If it's from left to right, direction = 3;
Then when another button is clicked, check the new direction. If it's 3, the word is still in the same direction. if it's something else, then erase and start over.
Hope this helps.

Related

How to put a decimal point according to the will of the user in a calculator in iphone?

I have a calculator in which i would like to put the decimal point according to the button press for the decimal point. I get the decimal point but if I enter another digit the decimal pint vanishes and is overwritten .
The code is mentioned below for the decimal press:-
-(IBAction)decimalPressed:(id)sender{
calculatorScreen.text = [calculatorScreen.text stringByAppendingString:#"."];
}
For the digit press it is :-
-(IBAction)buttonDigitPressed:(id)sender{
currentNumber = currentNumber*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%g",currentNumber];
}
How can i do something like 23 then "." then 45. The result would be 23.45
I've recently done a calculator app and could understand your problem. Another thing you want to take note about the point is that you do not want to have multiple point in your calculation, e.g. 10.345.1123.5. Simply put, you want it to be a legal float number as well.
With that said, you can use a IBAction (remember to link it to your storyboard or xib file)
-(IBAction)decimalPressed:(UIButton *)sender
{
NSRange range = [self.display.text rangeOfString:#"."];
if (range.location ==NSNotFound){
self.display.text = [ self.display.text stringByAppendingString:#"."];
}
self.userIsInTheMiddleOfEnteringANumber = YES;
}
While it might be possible we are doing on the same project, it could also be entirely different (you starting from scratch by yourself) so i will go through some of the codes
you could replace UIButton with the default id, but it is better to static replace it to make clear clarification for yourself, or anyone else who view your code.
NSRange as the name implies, mark the range, and the range will be ur display text of calculation (e.g. 1235.3568), and the range of string it is targeting in this case is "."
therefore, if NSNotfound (rangeOfString "." is not found in the text range) you will append the current display text with "." with the function stringByAppendingString:#".", there is no else, so no function will take place if "." is already found, which solve the problem of multiple point on the display.
userIsInTheMiddleOfEnteringANumber is a BOOL to solve the problem of having 0 in ur display (e.g. 06357), if you have a method to change it, then replace my method name with your own.
Try with below code:
-(IBAction)buttonDigitPressed:(id)sender
{
UIButton *pressedButton = (UIButton *)sender;
calculatorScreen.text = [calculatorScreen.text stringByAppendingFormat:#"%d",pressedButton.tag];
currentNumber = [calculatorScreen.text floatValue];
}
-(IBAction)ButtonDot
{
decimalChecker = 10;
calculatorScreen.text = [NSString stringWithFormat:#"$ %g.", currentSavings];
decimalChecker=1;
}
-(IBAction)buttonDigitPressed:(id)sender
{
if (decimalChecker ==1)
{
currentDecimal = currentDecimal*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"$ %g.%g", currentSavings,currentDecimal];
}
else
{
currentSavings = currentSavings*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"$ %g",currentSavings];
}
}
This is my solution:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
float result;
IBOutlet UILabel *TextInput;
int currentOperation;
float currentNumber;
BOOL userInTheMiddleOfEnteringDecimal;
}
- (IBAction)buttonDigitPressed:(id)sender;
- (IBAction)buttonOperationPressed:(id)sender;
- (IBAction)cancelInput;
- (IBAction)cancelOperation;
- (IBAction)dotPressed;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)buttonDigitPressed:(id)sender {
if(!userInTheMiddleOfEnteringDecimal)
{
currentNumber = currentNumber*10 + (float)[sender tag];
TextInput.text = [NSString stringWithFormat:#"%d",(int)currentNumber];
}
else{
TextInput.text= [TextInput.text stringByAppendingString:[NSString stringWithFormat:#"%d",[sender tag]]];
currentNumber = [TextInput.text floatValue];
}
}
- (IBAction)buttonOperationPressed:(id)sender {
if (currentOperation == 0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
default:
break;
}
}
currentNumber = 0;
TextInput.text = [NSString stringWithFormat:#"%.2f",result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
}
-(IBAction)cancelInput{
currentNumber = (int)(currentNumber/10);
TextInput.text = [NSString stringWithFormat:#"%.2f",currentNumber];;
}
-(IBAction)cancelOperation{
currentNumber = 0;
TextInput.text = #"0";
userInTheMiddleOfEnteringDecimal = NO;
}
- (IBAction)dotPressed{
if(!userInTheMiddleOfEnteringDecimal){
userInTheMiddleOfEnteringDecimal = YES;
TextInput.text= [TextInput.text stringByAppendingString:#"."];
}
}
#end
Hope this helps.. Another way of solution...
after pressing the "." all values after will be divided as following
the first number ur press after pressing "." will be divided by 10 the second by 100 and so on
so editing ur function it would be like this
-(IBAction)buttonDigitPressed:(id)sender{
currentNumber = currentNumber + (float)[sender tag] / 10.0;
calculatorScreen.text = [NSString stringWithFormat:#"%g",currentNumber];
}
i think in that solve your problem
http://www.datasprings.com/resources/articles-information/iphone-sdk-getting-started-example-code
There is sample code of calculator.

compare between two tagged objects?

I have 2 buttons, each one with tag. how can I compare between them, each with his own tag and image. for example:
// sender is (UIButton *)sender.
if ((sender.tag == 1)theImageOnTheButton == (sender.tag == 2)theImageOnTheButton
{
// egual
}
else
// not egual
so, if the sender than tagged as 1, his image is equal to the sender with tag 2, his image are equal, say equal, else, say that they are not egual. how can I do that?
the original code is:
-(void)flipView:(UIButton*)sender
{
x = x + 1;
if (x == 1)
{
// When flipping the first card
NSLog(#"X == 1");
[sender setTag:1];
}
else if (x == 2)
{
// When flipping the second card
NSLog(#"X == 2");
x = 0;
[sender setTag:2];
if ((sender.tag == 2) == (sender.tag == 1))
{
NSLog(#"IGUAL");
}
else
{
NSLog(#"NOT EGUAL");
}
}
}
Thanks allot.
[sender setTag:2];
and then -
if ((sender.tag == 2) == (sender.tag == 1))
when already tag is set to 2, then how can it be equal to 1? Wrong logic.
If I have more than two buttons then how can i compare the images?
suppose you have two buttons with tags
IBOutlet UIButton *btn1, *btn2;
btn1.tag = 1;
btn2.tag = 2;
connect these two IBOutlet buttons to your buttons in your xid file and for both add a common IBAction.
-(IBAction)checkingBtns:(id)sender
{
if([sender tag] == 1){
//Do what ever with your btn1 change color, change text, change image
}
if([sender tag] == 2){
//Do what ever with your btn2 change color, change text, change image
}
}
hope this will help you !! properly connect the oulets and actions for proper function

How to update an object's image in NSMutableArray?

I am trying to set the image of the face down card to the image that the value of the card is. The method in KCCard, image:, returns the image of the card.
- (UIImage *)image:(BOOL)yesOrNo
{
if (!yesOrNo) {
return [UIImage imageNamed:#"back-blue-150-3.png"];
} else {
return [UIImage imageNamed:[NSString stringWithFormat:#"%#-%#-150", [self suitAsString], [self valueAsString]]];
}
}
The code I am using in the deal method is as follows.
int lastDealerX = 437;
//int lastDealerY = 49;
int lastDealerTag = 0;
for (KCCard *aCard in dealerHand) {
if (lastDealerTag == 0) {
KCCardView *cardView = [[KCCardView alloc] initWithFrame:CGRectMake(lastDealerX, 49, 150, 215)];
cardView.backgroundColor = [UIColor blackColor];
cardView.image = [aCard image:NO];
cardView.tag = lastDealerTag;
[self.view addSubview:cardView];
lastDealerTag = lastDealerTag + 1;
lastDealerX = lastDealerX + 42;
} else {
KCCardView *cardView = [[KCCardView alloc] initWithFrame:CGRectMake(lastDealerX, 49, 150, 215)];
cardView.backgroundColor = [UIColor blackColor];
cardView.image = [aCard image:YES];
cardView.tag = lastDealerTag;
[self.view addSubview:cardView];
lastDealerTag = lastDealerTag + 1;
lastDealerX = lastDealerX + 42;
}
}
The KCCardView with tag 0 shows the card face down and the other card is face up. The problem is that when I want the face down card to show, it won't. Here is the show code.
- (IBAction)showCard:(id)sender {
for (UIView *view in self.view.subviews) {
for (KCCard *aCard in dealerHand) {
KCCardView *cardView = (KCCardView *)view;
if (cardView.tag == 0) {
cardView.image = [[dealerHand objectAtIndex:0] image:YES];
}
}
}
}
KCCard is an NSObject, KCCardView is a UIImageView, and dealerHand is an NSMutableArray.
Here is a video showing the build and run: http://aleckazarian.com/misc/Blackjack.mov
Here is the XCode project: http://aleckazarian.com/misc/Blackjack.zip
If you look at the connection in the nib you'll notice that it is connected to
showCard
this is a completely different method to
showCard:
In your class you implement - (IBAction)showCard:(id)sender; therefore you need to break the connection in Interface builder and reconnect it.
Update
The second time I ran your program I got
-[UIRoundedRectButton setImage:]: unrecognized selector sent to instance 0x68612e0
This looks like it's because you are iterating over the view's subviews and checking if 0 == tag. 0 is the default value for tag so essentially mostly every view will respond true unless you have explicitly set the tags to something else. The problem code it
for (UIView *view in self.view.subviews) {
for (KCCard *aCard in dealerHand) {
KCCardView *cardView = (KCCardView *)view;
if (cardView.tag == 0) { // <------- This is the bad check
cardView.image = [((KCCard *)[dealerHand objectAtIndex:0]) image:YES];
}
}
}
To fix this either do one of these (they are in order of my preference - I wouldn't go near 3 or 4 in this case):
Keep a reference to the cardView's in an array
Give the cardView's a non zero tag when they are created
Use respondsToSelector:
Test for the class `[cardView isKindOf:[UIButton class]];
The compiler does not know, what kind of object [dealerHand objectAtIndex:0] is, thus it cannot respond to image:. Try this:
cardView.image = [((KCCard *)[dealerHand objectAtIndex:0]) image:YES];

How to change number of decimal places and add decimal button iPhone Calculator?

So, look at the following code below- my first question is, how can I make it so there is only 0, 1, or 2 decimal places or make it automatically have however many decimal places are there? the second question is, how would I add a decimal button to the calculator? it has +-/*, how would I add a decimal button? Tutorial I used is here http://www.youtube.com/watch?v=Ihw0cfNOrr4 and here is my code-
viewcontroller.h
#import <UIKit/UIKit.h>
#interface calcViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
#end
in the .m
#import "calcViewController.h"
#implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%2f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:#"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = #"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = #"0";
currentOperation = 0;
}
you can use this on the output.
Float *number = 2.2f;
NSLog(#"%.2f",number);
Another thing you want to take note about the point is that you do not want to have multiple point in your calculation, e.g. 10.345.1123.5. Simply put, you want it to be a legal float number as well.
With that said, you can use a IBAction (remember to link it to your storyboard or xib file)
-(IBAction)decimalPressed:(UIButton *)sender
{
NSRange range = [self.display.text rangeOfString:#"."];
if (range.location ==NSNotFound){
self.display.text = [ self.display.text stringByAppendingString:#"."];
}
self.userIsInTheMiddleOfEnteringANumber = YES;
}
While it might be possible we are doing on the same project, it could also be entirely different (you starting from scratch by yourself) so i will go through some of the codes
you could replace UIButton with the default id, but it is better to static replace it to make clear clarification for yourself, or anyone else who view your code.
NSRange as the name implies, mark the range, and the range will be ur display text of calculation (e.g. 1235.3568), and the range of string it is targeting in this case is "." therefore, if NSNotfound (rangeOfString "." is not found in the text range) you will append the current display text with "." with the function stringByAppendingString:#".", there is no else, so no function will take place if "." is already found, which solve the problem of multiple point on the display.
userIsInTheMiddleOfEnteringANumber is a BOOL to solve the problem of having 0 in ur display (e.g. 06357), if you have a method to change it, then replace my method name with your own.
Regarding the display, as I'm using a different approach compared to yours, I'm unable to give any help or guide in that aspect.
This is my solution:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
float result;
IBOutlet UILabel *TextInput;
int currentOperation;
float currentNumber;
BOOL userInTheMiddleOfEnteringDecimal;
}
- (IBAction)buttonDigitPressed:(id)sender;
- (IBAction)buttonOperationPressed:(id)sender;
- (IBAction)cancelInput;
- (IBAction)cancelOperation;
- (IBAction)dotPressed;
#end
Viewcontroller.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)buttonDigitPressed:(id)sender {
if(!userInTheMiddleOfEnteringDecimal)
{
currentNumber = currentNumber*10 + (float)[sender tag];
TextInput.text = [NSString stringWithFormat:#"%d",(int)currentNumber];
}
else{
TextInput.text= [TextInput.text stringByAppendingString:[NSString stringWithFormat:#"%d",[sender tag]]];
currentNumber = [TextInput.text floatValue];
}
}
- (IBAction)buttonOperationPressed:(id)sender {
if (currentOperation == 0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
default:
break;
}
}
currentNumber = 0;
TextInput.text = [NSString stringWithFormat:#"%.2f",result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
}
-(IBAction)cancelInput{
currentNumber = (int)(currentNumber/10);
TextInput.text = [NSString stringWithFormat:#"%.2f",currentNumber];;
}
-(IBAction)cancelOperation{
currentNumber = 0;
TextInput.text = #"0";
userInTheMiddleOfEnteringDecimal = NO;
}
- (IBAction)dotPressed{
if(!userInTheMiddleOfEnteringDecimal){
userInTheMiddleOfEnteringDecimal = YES;
TextInput.text= [TextInput.text stringByAppendingString:#"."];
}
}
#end
Hope this helps.. This includes the decimal point in the button...

Game crashes when I try to destroy a b2Body, what should I do?

"Assertion failed: (m_bodyCount < m_bodyCapacity), function Add, file libs/Box2D/Dynamics/b2Island.h, line 65."
That is what it the crash leaves in the console.
[self removeChild:(CCSprite*)body->GetUserData() cleanup:YES];
body->SetTransform(b2Vec2(30, 30), 0); //moving the body out of the scene so it doesnt collide anymore!
world->DestroyBody(body);
I think im doing the right stuff..
#property (nonatomic, assign) b2Body *body;
Here is how i "make it" a property
I dont understand why it doesnt work, "body" is a proper pointer because I can retrieve infromation from the bodys UserData like tags that are set in the creatin of the body, so that shouldnt be a problem.. Do anyone know whats wrong with my code?
Thank you.
Edited in:
-(void) tick: (ccTime) dt //Main loop
{
if (ballFired) {
Magnet *aMagnet = [magnetArray objectAtIndex:0];
world->DestroyBody(aMagnet.body); //It crashes here!
}
int32 velocityIterations = 8;
int32 positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
//Iterate over the bodies in the physics world
for (b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite *myActor = (CCSprite*)b->GetUserData();
myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b>GetPosition().y * PTM_RATIO);
myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
Isnt this outside the world step?
Edit 2:
ContactListener::ContactListener(){};
void ContactListener::BeginContact(b2Contact* contact)
{
// Box2d objects that collided
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
CCSprite* actorA = (CCSprite*) fixtureA->GetBody()->GetUserData();
CCSprite* actorB = (CCSprite*) fixtureB->GetBody()->GetUserData();
if(actorA == nil || actorB == nil) return;
b2WorldManifold* worldManifold = new b2WorldManifold();
contact->GetWorldManifold(worldManifold);
Kollisjon *kollisjon = [Kollisjon sharedKollisjon];
if (actorA.tag == 1) {
NSLog(#"OK1");
kollisjon.kollidertBody = fixtureB->GetBody();
kollisjon.world->DestroyBody(kollisjon.kollidertBody); //Isnt this ok?
}
else if (actorB.tag == 1) {
NSLog(#"OK2");
kollisjon.kollidertBody = fixtureA->GetBody();
kollisjon.world->DestroyBody(kollisjon.kollidertBody); //Isnt this ok?
}
}
Is it not outside the timestep? Please help me here...
Thank you
You must scan for contacts, store all contacts in an array, and then AFTER all contacts have been checked, you remove your bodies.
Checking for contacts:
std::vector<MyContact>::iterator pos;
for(pos = _contactListener->_contacts.begin();
pos != _contactListener->_contacts.end(); ++pos)
{
MyContact contact = *pos;
b2Body *bodyA = contact.fixtureA->GetBody();
b2Body *bodyB = contact.fixtureB->GetBody();
// Rocket explosion rect
if(bodyA->GetUserData() == NULL)
{
NSLog(#"NULL collision detected. (BODY A)");
hasDoneRocketCollisions = YES;
CCSprite *sprite = (CCSprite*) bodyB->GetUserData();
if(sprite.visible == NO) continue;
if(sprite.tag >= 200 && sprite.tag < 300)
{
index = sprite.tag - 200;
if([spriteTracker containsObject:sprite]) continue;
[spriteTracker addObject:sprite];
bodiesToKill[counter] = bodyB;
[enemyChargerIsAlive replaceObjectAtIndex:(int)(sprite.tag-200) withObject:[NSNumber numberWithInt:0]];
[ParticleController spawnExplosion:sprite.position inParent:currentDefaultNode];
}
else if(sprite.tag >= 300 && sprite.tag < 400)
{
index = sprite.tag - 300;
if([spriteTracker containsObject:sprite]) continue;
[spriteTracker addObject:sprite];
bodiesToKill[counter] = bodyB;
[enemyShooterIsAlive replaceObjectAtIndex:(int)(sprite.tag-300) withObject:[NSNumber numberWithInt:0]];
[ParticleController spawnExplosion:sprite.position inParent:currentDefaultNode];
counter++;
}
}
}
Later in your method after all contacts have been checked:
b2Body *dyingBody;
for(int i = 0; i < counter; i++)
{
CCSprite *dyingSprite;
dyingSprite = [spriteTracker objectAtIndex:i];
dyingSprite.visible = NO;
// Is player projectile
if(dyingSprite.tag >= 100 && dyingSprite.tag < 200)
{
CCParticleSystemQuad *dyingParticle;
dyingParticle = [particlesToKill objectAtIndex:particleIndex];
particleIndex++;
[dyingParticle stopSystem];
dyingBody = bodiesToKill[i];
dyingBody->SetActive(false);
[ParticleController spawnExplosion:dyingSprite.position inParent:currentDefaultNode];
[AudioController playExplosion];
dyingSprite.visible = NO;
if([_player currentShotType] == 1)
{
rocketHitBody->SetTransform(b2Vec2(dyingSprite.position.x/PTM_RATIO, dyingSprite.position.y/PTM_RATIO), 0.0);
rocketHitBody->SetActive(true);
}
}
}
Take note that these are just random chunks of code I have copy and pasted in. They are for example only and may only confuse you if you try to read them as exact instructions.
The point here is: You can not remove a body while it is being accessed by the step or contact listener. Finish using the contact listener and then remove your bodies.