Puzzle Game in iPhone

Introduction

In this article I will create a Single View application to implement a Puzzle game. In this article I will use five image views. In this game when I show an image in a view and the task is to set images in a corresponding sequence, if you set the images in the wrong order then it will be centered and doesn't look like a real image but if we set the images properly then it looks like real images; it totally works on the touch event. In short way, in this article we learn how to do a touch event for more than one image.

To understand it we use the following.

Step 1

Open XCode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now select Single View Application and click on Next.

Step 4

Now provide your Product Name and Company Identifier.

Step 5

Select the location where you want to save your project and click on Create.

Step 6

Now here we write the code.

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UIView *dropTarget;
@property (nonatomic, strong) IBOutlet UIImageView *dragObject1;
@property (nonatomic, strong) IBOutlet UIImageView *dragObject2;
@property (nonatomic, strong) IBOutlet UIImageView *dragObject3;
@property (nonatomic, strong) IBOutlet UIImageView *dragObject4;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize dropTarget;
@synthesize dragObject1,dragObject2,dragObject3,dragObject4;

-(
void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
// Send to the dispatch method, which will make sure the appropriate subview is acted upon
[self dispatchTouchEvent:[touch view] toPosition:[touch locationInView:self.view]];
}
}
-(void)dispatchTouchEvent:(UIView *)theView toPosition:(CGPoint)position
{
// Check to see which view, or views, the point is in and then move to that position.
if (CGRectContainsPoint([dragObject1 frame], position)) {
dragObject1.center = position;
}
if (CGRectContainsPoint([dragObject2 frame], position)) {
dragObject2.center = position;
}
if (CGRectContainsPoint([dragObject3 frame], position)) {
dragObject3.center = position;
}
if (CGRectContainsPoint([dragObject4 frame], position)) {
dragObject4.center = position;
}
}
@end

Step 7

Finally we click on the Run button to show the output.

Step 8

Output1 in iPhone:

Output1-in-iphone.png

Output2 in iPhone:

Output2-in-iphone.png

Output3 in iPhone:

Output3-in-iphone.png

Output4 in iPhone:

Output4-in-iphone.png

The proper way to set images.

Output5 in iPhone:

Output5-in-iphone.png

Output6 in iPhone:

Output6-in-iphone.png

Output7 in iPhone:

Output7-in-iphone.png

Up Next
    Ebook Download
    View all
    Learn
    View all