পৃষ্ঠাসমূহ

শুক্রবার, ২৫ মার্চ, ২০১১

Game Tic Tak Toe



Building a game Tic Tak Toe --Matin


Tic-Tac-Toe:

It helps to write out what we want it to do. Right now it will be as if there are two people playing the game. Later we may add an AI so the user can play against the computer. BUT lets just getting it working right now.
We want the user to touch a square on the board and place a X or an O depending on whose turn it is.

We want to check for a win after the user places their token on the board.
If there is no winner, then update the text label to say that it is the next persons turn.
We also want there to be a button that allows the user to manually reset the game.

Open XCode and create a new View based application.

I called mine tictactoe.


Unzip the files and Drag them into the resources folder.

Open up tictactoeViewController.h and put in the following information:


Code:
 
#import <UIKit/UIKit.h>
 
@interface tictactoeViewController : UIViewController {
      //the image of the X or O
      IBOutlet UIImage * oImg;
      IBOutlet UIImage * xImg;
      
      //these are the UIImageViews that will hold the X or O
      //the 's' stands for Slot
      IBOutlet UIImageView *s1;
      IBOutlet UIImageView *s2;
      IBOutlet UIImageView *s3;
      IBOutlet UIImageView *s4;
      IBOutlet UIImageView *s5;
      IBOutlet UIImageView *s6;
      IBOutlet UIImageView *s7;
      IBOutlet UIImageView *s8;
      IBOutlet UIImageView *s9;
      
      //button to manually reset the game
      IBOutlet UIButton *resetButton; 
      
      //Image view that will hold the # pattern
      IBOutlet UIImageView * board;
      
      //label to let the player know who can go or let player know who wins
      IBOutlet UILabel * whoseTurn;
      
      //integer that represents the player
      NSInteger playerToken;
}
 
@property (nonatomic,retain) UIImage *oImg;
@property (nonatomic,retain) UIImage *xImg;
 
@property (nonatomic,retain) UIButton *resetButton;
 
@property (nonatomic,retain) UIImageView *board;
 
@property (nonatomic,retain) UIImageView *s1;
@property (nonatomic,retain) UIImageView *s2;
@property (nonatomic,retain) UIImageView *s3;
@property (nonatomic,retain) UIImageView *s4;
@property (nonatomic,retain) UIImageView *s5;
@property (nonatomic,retain) UIImageView *s6;
@property (nonatomic,retain) UIImageView *s7;
@property (nonatomic,retain) UIImageView *s8;
@property (nonatomic,retain) UIImageView *s9;
 
 
@property (nonatomic,retain) UILabel * whoseTurn;
 
//method that will change the player and update the label and place the X or O on the board
-(void) updatePlayerInfo;
 
//method that will check to see if someone has won returns TRUE if someone wins
-(BOOL) checkForWin;
 
//button reset
-(IBAction)buttonReset;
 
//this will reset the game, by clearing the board and reseting the playerTurn to 1
-(void) resetBoard;
 
@end


Now open up the tictactoeViewController.xib by double clicking it
Drag one UIImageView to the window and resize it to be 300x300 and set its image to board.png by using the Attributes Inspector.

Then drag 1 more UIImageView to the window and resize it to 100x100 then check the box for User Interaction Enabled.

Then copy and paste that 8 more times. Move those boxes to be hovering over the spaces of the game board lining them up.

Drag a UILable to the window and position it under the board.

Drag a UIButton to the window and rename the text to RESET GAME.

Now that we have the basic layout, control click (or right click if you can) top left UIImageView starting and drag the + sign to the Files Owner and select S1.

Then go to the top middle piece and do the same selecting S2, continue on until all 9 UIImageViews have been assigned.

Then control-click the Label and click the + sign and drag to files owner and select whoseTurn.

Then control-click the Reset Button and click the + sign from the TOUCH UP INSIDE and drag to the files owner and select resetButton.

Save and close the Interface Builder

Open up the tictactoeViewController.m and type the following code.

I have tried to comment a lot of it. And this is just a skeleton.

Code:

#import "tictactoeViewController.h"
 
 
//the NSInteger holds a numerical value of the player
//X is represented by a 1 (one)
//O is represented by a 0 (zero)
 
 
 
@implementation tictactoeViewController
 
//since we created somethings in the header we need to synthesize them here.
//just to keep things clean and in order I broke up the synthesizing but you could
//have very well put them all on one line, or put everyone on its own @synthesize
@synthesize s1,s2,s3,s4,s5,s6,s7,s8,s9;
@synthesize oImg,xImg,whoseTurn,board;
@synthesize resetButton;
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
      
 
           }
    return self;
}
 
 
//this is where we will put the touch event for the tic tac toe game
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
 
      
}
//this is the button that will call the resetBoard method
-(IBAction) buttonReset{
      
}
 
 
 
//method that will check to see if someone has won returns TRUE if someone wins
-(BOOL) checkForWin{
      //right now return 1 becuase we havn't implemented this yet
      return 1;
}
 
//this will reset the game, by clearing the board and reseting the playerTurn to 1
-(void) resetBoard{
 
 
}
 
//method that will change the player and update the label and place the X or O on the board
- (void) updatePlayerInfo{
      if(playerToken == 1){
           
           playerToken == 2; //because now its the second players turn
           whoseTurn.text = @"O can go"; //Update the label to tell who goes next
           
      }
      if(playerToken == 2){
           playerToken == 1;
           whoseTurn.text =@"X can go";
           
      }
           
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}
 
 
- (void)dealloc {
      //we have to release all the stuff we created in the header for memory managment
      [s1 release];
      [s2 release];
      [s3 release];
      [s4 release];
      [s5 release];
      [s6 release];
      [s7 release];
      [s8 release];
      [s9 release];
      [resetButton release];
      [board release];
      [oImg release];
      [xImg release];
      [whoseTurn release];
    [super dealloc];
}
 
@end




Now you should be able to build and run the project and see the board the UILabel and the Reset Button.

This is just a skeleton of the project so far. Nothing works right now. But we will get there.

This is all for now. If anyone has any suggestions or sees a problem with how I am doing it so far PLEASE say something!



Praise for Learning iOS Game Programming

“An excellent introduction into the world of game development explaining every aspect of game design and implementation for the iPad, iPhone, and iPod touch devices. A great way for anyone interested in writing games to get started.”
–Tom Bradley, Software Architect, Designer of TBXML

“A great developer and a great game.That’s everything you can find in this book to learn how to write an awesome game for iPhone.Maybe you’re the next AppStore hit!”
–Sebastien Cardoso

“With Learning iOS Game Programming, you’ll be writing your own games in no time. The code included is well explained and will save you hours of looking up obscure stuff in the documentation and online forums.”
–Pablo Gomez Basanta, Founder, Shifting Mind

“I always thought that to teach others one has to be an expert and a person with an established reputation in the field. Michael Daley proved me wrong. He is teaching others while studying himself. Michael’s passion in teaching and studying, ease of solutions to problems, and a complete game as a resulting project makes this book one of the best I have ever read.”
–Eugene Snyetilov

“If you’re interested in 2D game programming with the iOS using OpenGL and OpenAL directly, this book walks you through creating a complete and fun game without getting bogged down in technical details.”
–Scott D.Yelich

“Michael Daley brings clarity to the haze of iPhone application development. Concrete examples, thorough explanation, and timesaving tips make this book a must have for the up and coming iPhone game developer.”
–Brandon Middleton, Creator of Tic Tac Toe Ten

“This is the A-Z guide to iOS game development; Michael’s book takes you from the basics and terminology to using the techniques in practice on a fully working game. Before you know it, you will find yourself writing your own game, fueled by a firm grasp of the principles and techniques learned within. I could not ask for a better reference in developing our own games.”
–Rod Strougo, Founder Prop Group

Product Description

Get Started Fast with iOS Game Programming

Since the launch of the App Store, games have been the hottest category of apps for the iPhone, iPod touch, and iPad. That means your best chance of tapping into the iPhone/iPad “Gold Rush” is to put out a killer game that everyone wants to play (and talk about). While many people think games are hard to build, they can actually be quite easy, and Learning iOS Game Programming is your perfect beginner’s guide. Michael Daley walks you through every step as you build a killer 2D game for the iPhone.

In Learning iOS Game Programming, you’ll learn how to build a 2D tile map game, Sir Lamorak’s Quest: The Spell of Release (which is free in the App Store). You can download and play the game you’re going to build while you learn about the code and everything behind the scenes. Daley identifies the key characteristics of a successful iPhone game and introduces the technologies, terminology, and tools you will use. Then, he carefully guides you through the whole development process: from planning storylines and game play all the way through testing and tuning.

Download the free version of Sir Lamorak’s Quest from the App Store today, while you learn how to build the game in this book.
 
Coverage includes
  • Planning high-level game design, components, and difficulty levels
  • Using game loops to make sure the right events happen at the right time
  • Rendering images, creating sprite sheets, and building basic animations
  • Using tile maps to build large game worlds from small reusable images
  • Creating fire, explosions, smoke, sparks, and other organic effects
  • Delivering great sound via OpenAL and the iPhone’s media player
  • Providing game control via iPhone’s touch and accelerometer features
  • Crafting an effective, intuitive game interface
  • Building game objects and entities and making them work properly
  • Detecting collisions and ensuring the right response to them
  • Polishing, testing, debugging, and performance-tuning your game 
Learning iOS Game Programming focuses on the features, concepts, and techniques you’ll use most often—and helps you master them in a real-world context. This book is 100% useful and 100% practical; there’s never been an iPhone game development book like it!

Praise for Learning iOS Game Programming

“An excellent introduction into the world of game development explaining every aspect of game design and implementation for the iPad, iPhone, and iPod touch devices. A great way for anyone interested in writing games to get started.”
–Tom Bradley, Software Architect, Designer of TBXML

“A great developer and a great game.That’s everything you can find in this book to learn how to write an awesome game for iPhone.Maybe you’re the next AppStore hit!”
–Sebastien Cardoso

“With Learning iOS Game Programming, you’ll be writing your own games in no time. The code included is well explained and will save you hours of looking up obscure stuff in the documentation and online forums.”
–Pablo Gomez Basanta, Founder, Shifting Mind

“I always thought that to teach others one has to be an expert and a person with an established reputation in the field. Michael Daley proved me wrong. He is teaching others while studying himself. Michael’s passion in teaching and studying, ease of solutions to problems, and a complete game as a resulting project makes this book one of the best I have ever read.”
–Eugene Snyetilov

“If you’re interested in 2D game programming with the iOS using OpenGL and OpenAL directly, this book walks you through creating a complete and fun game without getting bogged down in technical details.”
–Scott D.Yelich

“Michael Daley brings clarity to the haze of iPhone application development. Concrete examples, thorough explanation, and timesaving tips make this book a must have for the up and coming iPhone game developer.”
–Brandon Middleton, Creator of Tic Tac Toe Ten

“This is the A-Z guide to iOS game development; Michael’s book takes you from the basics and terminology to using the techniques in practice on a fully working game. Before you know it, you will find yourself writing your own game, fueled by a firm grasp of the principles and techniques learned within. I could not ask for a better reference in developing our own games.”
–Rod Strougo, Founder Prop Group



//  TicTacToe1AppDelegate.h
//  TicTacToe1
//
//  Created by Md. Abdul Matin on 23/03/2011.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import <UIKit/UIKit.h>
@class TicTacToe1ViewController;
@interface TicTacToe1AppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    TicTacToe1ViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet TicTacToe1ViewController *viewController;
@end



//
//  TicTacToe1AppDelegate.m
//  TicTacToe1
//
//  Created by  Md. Abdul Matin on 23/03/2011.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import "TicTacToe1AppDelegate.h"
#import "TicTacToe1ViewController.h"

@implementation TicTacToe1AppDelegate
@synthesize window;
@synthesize viewController;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
   
    // Override point for customization after app launch   
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];    
            return YES;
}


- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}

@end



//
//  TicTacToe1ViewController.h
//  TicTacToe1
//
//  Created by Md. Abdul Matin on 23/03/2011.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface TicTacToe1ViewController : UIViewController {
           
           
           
            IBOutlet UIImage *oImg;
            IBOutlet UIImage *xImg;
           
           
           
            IBOutlet UIImageView *s1;
            IBOutlet UIImageView *s2;
            IBOutlet UIImageView *s3;
            IBOutlet UIImageView *s4;
            IBOutlet UIImageView *s5;
            IBOutlet UIImageView *s6;
            IBOutlet UIImageView *s7;
            IBOutlet UIImageView *s8;
            IBOutlet UIImageView *s9;
           
           
           
            UIImage *theImg;
            IBOutlet UIButton *resetButton;
            IBOutlet UIImageView *board;
            IBOutlet UILabel *whoseTurn;
            NSInteger playerToken;
           
            BOOL cellwasused;
           
            //BOOL selfwasused;
           
            NSInteger numberOfPlayer;
            UIAlertView *myAlertView;
           
           

}

@property (nonatomic,retain) UIImage *oImg;
@property (nonatomic,retain) UIImage *xImg;
@property (nonatomic,retain) UIImage *theImg;
@property (nonatomic,retain) UIButton *resetButton;
@property (nonatomic,retain) UIImageView *board;

@property (nonatomic,retain) UIImageView *s1;
@property (nonatomic,retain) UIImageView *s2;
@property (nonatomic,retain) UIImageView *s3;
@property (nonatomic,retain) UIImageView *s4;
@property (nonatomic,retain) UIImageView *s5;
@property (nonatomic,retain) UIImageView *s6;
@property (nonatomic,retain) UIImageView *s7;
@property (nonatomic,retain) UIImageView *s8;
@property (nonatomic,retain) UIImageView *s9;

@property (nonatomic,retain) UIAlertView *myAlertView;
@property (nonatomic,retain) UILabel * whoseTurn;



-(void)processLogic;
-(void) updatePlayerInfo;
-(BOOL) checkForWin;
-(IBAction)buttonReset;
-(void) resetBoard;



@end


//
//  TicTacToe1ViewController.m
//  TicTacToe1
//
//  Created by  Md. Abdul Matin on 23/03/2011.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import "TicTacToe1ViewController.h"

@implementation TicTacToe1ViewController


@synthesize s1,s2,s3,s4,s5,s6,s7,s8,s9;
@synthesize oImg,xImg,theImg,whoseTurn,board;
@synthesize resetButton,myAlertView;


// The designated initializer. Override to perform setup that is required before the view is loaded.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}


/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
           
            oImg = [UIImage imageNamed:@"o.png"];
           
            xImg = [UIImage imageNamed:@"x.png"];
            board.image=[UIImage imageNamed:@"board.png"];
           
            playerToken = 1;
            whoseTurn.text = @"x can go";
            numberOfPlayer = 0;
           
           
           
    [super viewDidLoad];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

switch (playerToken) {
            case 1:
                        theImg = xImg;
                        break;
                       
            case 2:
                        theImg = oImg;
                        break;

    }
            UITouch *touch = [[event allTouches]anyObject];
            cellwasused = NO;
            if (CGRectContainsPoint([s1 frame],[touch locationInView:self.view])&(s1.image ==NULL)) {
                       
                        cellwasused = YES;
                        s1.image = theImg;
                       
            }
            if (CGRectContainsPoint([s2 frame],[touch locationInView:self.view])&(s2.image ==NULL)) {
                       
                        cellwasused = YES;
                        s2.image = theImg;
                       
            }
            if (CGRectContainsPoint([s3 frame],[touch locationInView:self.view])&(s3.image ==NULL)) {
                       
                        cellwasused = YES;
                        s3.image = theImg;
                       
            }          
            if (CGRectContainsPoint([s4 frame],[touch locationInView:self.view])&(s4.image ==NULL)) {
                       
                        cellwasused = YES;
                        s4.image = theImg;
                       
            }
            if (CGRectContainsPoint([s5 frame],[touch locationInView:self.view])&(s5.image ==NULL)) {
                       
                        cellwasused = YES;
                        s5.image = theImg;
                       
            }
           
           
            if (CGRectContainsPoint([s6 frame],[touch locationInView:self.view])&(s6.image ==NULL)) {
                       
                        cellwasused = YES;
                        s6.image = theImg;
                       
            }
           

           
            if (CGRectContainsPoint([s7 frame],[touch locationInView:self.view])&(s7.image ==NULL)) {
                       
                        cellwasused = YES;
                        s7.image = theImg;
                       
            }          
           
            if (CGRectContainsPoint([s8 frame],[touch locationInView:self.view])&(s8.image ==NULL)) {
                       
                        cellwasused = YES;
                        s8.image = theImg;
                       
            }
           
            if (CGRectContainsPoint([s9 frame],[touch locationInView:self.view])&(s9.image ==NULL)) {
                       
                        cellwasused = YES;
                        s9.image = theImg;
                       
            }
           
            [self processLogic];
           
            if (cellwasused) {
                       
                        [self updatePlayerInfo];
            }
                       

}




-(void)processLogic{
           
if ([self checkForWin]) {
            if (playerToken == 1) {
                        myAlertView = [[UIAlertView alloc] initWithTitle:@"winner!" message:@"x win!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [myAlertView show];
                        [self resetBoard];
                       
            }
            else if(playerToken == 2) {
                        myAlertView = [[UIAlertView alloc] initWithTitle:@"winner!" message:@"o win!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [myAlertView show];
                        [self resetBoard];      
           
            }
           
            if (numberOfPlayer == 9) {
                        myAlertView = [[UIAlertView alloc]initWithTitle:@"NO Winner" message:@"Sorry, cats game" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil ];
           
                        [myAlertView show];
                       
                        [self resetBoard];
                       
            }
           
}
}          



/*-(BOOL)checkForWin {
            if ((s1.image==s2.image)& (s2.image==s3.image)&(s1.image != NULL)) {return YES;}
                       
            }
            */



-(BOOL)checkForWin{
           
            if ((s1.image == s2.image) & (s2.image == s3.image) & (s1.image!=NULL)) { return YES;}      
            if ((s4.image == s5.image) & (s5.image == s6.image) & (s4.image!=NULL)) { return YES;}
            if ((s7.image == s8.image) & (s8.image == s9.image) & (s7.image!=NULL)) { return YES;}      
            if ((s1.image == s4.image) & (s4.image == s7.image) & (s1.image!=NULL)) { return YES;}      
    if ((s2.image == s5.image) & (s5.image == s8.image) & (s2.image!=NULL)) { return YES;}  
    if ((s3.image == s6.image) & (s6.image == s9.image) & (s3.image!=NULL)) { return YES;}  
            if ((s1.image == s5.image) & (s5.image == s9.image) & (s1.image!=NULL)) { return YES;}      
            if ((s3.image == s5.image) & (s5.image == s7.image) & (s3.image!=NULL)) { return YES;}
           

           
            return NO;
           
}




-(void)displayWinner{
            if ([self checkForWin] == YES) {
                       
                        if (playerToken == 1) {
                                    whoseTurn.text =@"x is the Winner!";
                        }
                        else {whoseTurn.text = @"o is the Winner!";
                        }

            }
                       
                       
                       
}




-(IBAction)buttonReset{
           
            [self resetBoard];
           
}

-(void)resetBoard{
           
           
            s1.image =NULL;
            s2.image =NULL;
            s3.image =NULL;
            s4.image =NULL;     
            s5.image =NULL;
            s6.image =NULL;
            s7.image =NULL;
            s8.image =NULL;     
            s9.image =NULL;
           
            playerToken = 1;
            whoseTurn.text =@"x can go";
            numberOfPlayer = 0;
           
           
}

-(void)updatePlayerInfo{
           
           
            numberOfPlayer++;
            if (numberOfPlayer ==9) {
                       
                       
                        [self resetBoard];
            }
                       
                         
            if (playerToken ==1) {
                       
                       
                        playerToken =2;
                        whoseTurn.text = @"o can go";
                       
            }          
            else {
                        playerToken = 1;
                        whoseTurn.text =@"x can go";
            }

                         
                         
}
                       
           
           

           
           
           
           
           

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
            // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
           
            // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
            // Release any retained subviews of the main view.
            // e.g. self.myOutlet = nil;
}


- (void)dealloc {
           
            [s1 release];
            [s2 release];
            [s3 release];
            [s4 release];
            [s5 release];
            [s6 release];
            [s7 release];
            [s8 release];
            [s9 release];
           
            [theImg release];
            [resetButton release];
            [board release];
            [oImg release];
            [xImg release];
            [whoseTurn release];
            [myAlertView release];
           
           
           
    [super dealloc];
}

@end



/*-(BOOL)checkForWin {
            if (s1.image === s2.image) {
                        <#statements#>
            }
*/



//
//  main.m
//  TicTacToe1
//
//  Created by  Md. Abdul Matin on 23/03/2011.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
   
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}