<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>iPhone Programming Tutorials &#187; game</title>
	<atom:link href="/tag/game/feed/" rel="self" type="application/rss+xml" />
	<link>http://icodeblog.com</link>
	<description>iPhone Programming Tutorials</description>
	<lastBuildDate>Tue, 19 Nov 2013 19:34:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.1</generator>
	<item>
		<title>DICE+, rocketships and a giveaway.</title>
		<link>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/</link>
		<comments>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/#comments</comments>
		<pubDate>Sat, 06 Jul 2013 00:18:39 +0000</pubDate>
		<dc:creator><![CDATA[ebennett]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Dice+]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[rocketship]]></category>
		<category><![CDATA[space]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=4414</guid>
		<description><![CDATA[<a href="/wp-content/uploads/2013/07/screenShot.jpg"></a>
I received my <a title="DICE+" href="http://developers.dicepl.us" target="_blank">DICE+</a> developer kit a couple weeks ago and was excited to get to testing. What is DICE+? DICE+ is a bluetooth connected, smart, 6 sided die that is made out of materials safe to roll directly on your devices. It has a 20hr battery which powers a bunch of cool sensors like accelerometers, magnetic field sensor, touch sensitive faces, and a few more. The built in anti-cheat protection makes sure each roll is  ...]]></description>
				<content:encoded><![CDATA[<p style="text-align: center"><img class="alignleft size-medium wp-image-4469" alt="Dice+Image" src="/wp-content/uploads/2013/07/Dice+Image-300x300.jpg" width="300" height="300" /><a href="/wp-content/uploads/2013/07/screenShot.jpg"><img class="alignleft size-medium wp-image-4529" alt="screenShot" src="/wp-content/uploads/2013/07/screenShot-225x300.jpg" width="225" height="300" /></a></p>
<p>I received my <a title="DICE+" href="http://developers.dicepl.us" target="_blank">DICE+</a> developer kit a couple weeks ago and was excited to get to testing. What is DICE+? DICE+ is a bluetooth connected, smart, 6 sided die that is made out of materials safe to roll directly on your devices. It has a 20hr battery which powers a bunch of cool sensors like accelerometers, magnetic field sensor, touch sensitive faces, and a few more. The built in anti-cheat protection makes sure each roll is fair, and each face can display a wide range of colors due to the red, green and blue LEDs backlighting every side. Balanced to match any standard 6 sided die performance, the DICE+ brings back some of the tactile fun of playing games on digital devices. Although not quite out on the market as of this writing, developers can download the SDK, order kits and start developing. The developers over at DICE+ have also set aside a kit to give away to one of the readers of this post. The first 6 readers who reply to this post and correctly lists all sensors available, will be entered in the drawing. A DICE+ will then be rolled, a winner selected from those replies and sent one of the DICE+ developer kits. Now that I have had some fun, I thought I would share, and show how easy it was to use.</p>
<p>In the following tutorial, I have designed a simple 2 player game in which you are trying to be the first player to get your ship into space. Each player takes a turn rolling the die, the first player to reach 25 is the winner. With the addition of some simple UIView animations to animate our player ships and space background, the race to space can begin. Link to project file and assets are at the end of this post.</p>
<p>First lets create a new, single view, portrait oriented project for iPad called &#8216;RaceToSpace&#8217; using ARC (Automatic Reference Counting).  After downloading the DICE+ SDK from the website, drag and drop the framework into your project, add the &#8216;CoreBluetooth&#8217;, and QuartzCore frameworks. For DICE+, You will also have to add &#8216;-all_load&#8217; to your projects build settings, under other linker commands. In Interface Builder, add a UIImageView to your view, setting its size and origin to the following x=0, y=-1024, width=768 and height=2048. Press your editors double column view button, and while holding the control button, left mouse click the newly added UIImageView and link to your .h file creating an IBOutlet reference called &#8216;spaceBackground&#8217;. Add a Play button to start the game, a label at the bottom to show bluetooth connection info and turn status, and 2 labels at the top for displaying player scores. Link all of these to your .h file as you did with the space background UIImageView, using these corresponding names; playButton, status, player1Score, player2Score. You will also need to right click on the PLAYBUTTON, and link the &#8216;touch up inside&#8217; action onto your ViewController.m file and name it &#8216;Play&#8217;. Now that the basic building blocks are setup, we can get to configuring the software for use with your die.</p>
<p>In your ViewController .h, add the following code to match.</p>
<div class="wp_syntax">
<pre><span style="color: #800000"> 
#impor</span>t &lt;UIKit/UIKit.h&gt;
<span style="color: #800000">#import</span> &lt;DicePlus/DicePlus.h&gt;
<span style="color: #800000">#import</span> "Player.h"

<span style="color: #800000">@interface</span> ViewController : UIViewController <span style="color: #000080">&lt;DPDiceManagerDelegate&gt;</span>
{
    <span style="color: #000080">DPDiceManager</span>* diceManager;
    <span style="color: #000080">DPDie</span>* availableDie;
    <span style="color: #000080">DPDie</span>* connectedDie;
}
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *player1Score;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *player2Score;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UIImageView</span> *spaceBackground;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UILabel</span> *status;
<span style="color: #993300">@property</span> (nonatomic, retain) <span style="color: #000080">NSArray</span> *players;
<span style="color: #993300">@property</span> (nonatomic, retain) <span style="color: #000080">Player</span> *currentPlayer;
<span style="color: #993300">@property</span> (weak, nonatomic) IBOutlet <span style="color: #000080">UIButton</span> *play;

@end</pre>
</div>
<p>In your ViewController.m, add the following code to your viewDidLoad method. This initializes the dice manager, sets the DEV KEY with the <b>[diceManager startScanning]</b> command, and starts scanning for available devices. Also add the #define MaxPoints 25. This defines the winning score.</p>
<div class="wp_syntax">
<pre><span style="color: #660000"> 
#define MaxPoints 25</span>

<span style="color: #993300">@implementation</span> ViewController

- (<span style="color: #993300">void</span>)viewDidLoad
{
    [super viewDidLoad];
<span style="color: #008000">    // Do any additional setup after loading the view, typically from a nib.
</span>
    if (connectedDie != nil) {
        return;
    }
    availableDie = nil;
    diceManager = [DPDiceManager sharedDiceManager];
    diceManager.delegate = self;

<span style="color: #008000">    //DICE+ generic development key.
</span>    uint8_t key[8] = {0x83, 0xed, 0x60, 0x0e, 0x5d, 0x31, 0x8f, 0xe7};
    [diceManager setKey:key];

    <span style="color: #008000">//Start scanning for an available DICE+</span>.
    [diceManager startScan];
    self.status.text = @"Searching for DICE+...";
}</pre>
</div>
<p>If you notice the error pertaining to the #import Player.h and the player object, we will be adding that in a moment so you can ignore that for now. We do need to add some delegate calls so we can be notified of a DICE+ connection, and some to receive results when the die is rolled. I will also explain in detail the contained code when we walk thru the functionality of the game.</p>
<div class="wp_syntax">
<pre> 
- (<span style="color: #993300">void</span>)die:(<span style="color: #000080">DPDie</span> *)die didRoll:(<span style="color: #000080">DPRoll</span> *)roll error:(<span style="color: #000080">NSError</span> *)error
{
    <span style="color: #008000">//Roll was valid</span>
    if (roll.flags == <span style="color: #993366">DPRollFlagOK</span>) {
        <span style="color: #008000">//Stop roll updates just to make sure wrong player doesnt mistakenly roll DICE+.</span>
        [connectedDie stopRollUpdates];
        <span style="color: #008000">//Convert roll result (1-6) to binary mask equivalent</span>
        int mask = 1 &lt;&lt; (roll.result-1);
<span style="color: #008000">        //Blink the top face green showing roll result. DICE+ uses a binary mask for determinning which face, or faces to light.
</span>        [connectedDie startBlinkAnimationWithMask:mask priority:0 r:0 g:255 b:0 onPeriod:100 cyclePeriod:50 blinkCount:5];
        <span style="color: #008000">//Move player ship</span>
        [self moveCurrentPlayer:roll.result];

    } else if (roll.flags == <span style="color: #993366">DPRollFlagTilt</span>) {
<span style="color: #008000">        //DICE+ roll error
</span>        self.status.text = @"Roll Tilted";
<span style="color: #008000">        //Blink DICE+ faces red to indicate a roll error occured.
</span>        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    } else if (roll.flags == <span style="color: #993366">DPRollFlagTooShort</span>) {
<span style="color: #008000">        //DICE+ roll error
</span>        self.status.text = @"Roll too short";
<span style="color: #008000">        //Blink dice plus faces red to indicate a roll error occured.
</span>        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    }
}

#pragma mark - DPDiceManagerDelegate methods
- (<span style="color: #993300">void</span>)centralManagerDidUpdateState:(<span style="color: #000080">CBCentralManagerState</span>)state
{
<span style="color: #008000">    // See CBCentralManagerDelegate documentation for info about CBCentralManager state changes
</span>}

- (<span style="color: #993300">void</span>)diceManagerStoppedScan:(<span style="color: #000080">DPDiceManager</span> *)manager
{
<span style="color: #008000">    //Scanning has stopped, restart scan if no available die was found.
</span>    if (availableDie == nil) {
        [diceManager startScan];
        self.status.text = @"Searching for DICE+...";
    }
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didDiscoverDie:(<span style="color: #000080">DPDie</span> *)die
{
<span style="color: #008000">    //A DICE+ die was found, not connected yet.
</span>    availableDie = die;
    availableDie.delegate = (id)self;

    [diceManager stopScan];
<span style="color: #008000">    //Attempt to connect to available DICE+ found.
</span>    [diceManager connectDie:availableDie];

    self.status.text = @"Connecting DICE+...";
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didConnectDie:(<span style="color: #000080">DPDie</span> *)die
{
<span style="color: #008000">    //Available DICE+ connected and is ready for play.
</span>    availableDie = nil;
    connectedDie = die;
    connectedDie.delegate = (id)self;
    self.status.text = @"Press play to begin.";
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager failedConnectingDie:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ failed connection attempt.
</span>    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Connection failed... Searching...";

    [diceManager startScan];
}

- (<span style="color: #993300">void</span>)diceManager:(<span style="color: #000080">DPDiceManager</span> *)manager didDisconnectDie:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ disconnected
</span>    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Die disconnected... Searching...";

    [diceManager startScan];
}

- (<span style="color: #993300">void</span>)dieFailedAuthorization:(<span style="color: #000080">DPDie</span> *)die error:(<span style="color: #000080">NSError</span> *)error
{
<span style="color: #008000">    //DICE+ authorization failed.
</span>    self.status.text = @"Failed authorization";
}</pre>
</div>
<p>The DICE+ is well documented and there are quite a few delegate methods that can be used depending on which sensor you issue a startUpdate too.</p>
<p>We&#8217;ll go back to the functions of the game a little later on in the post, for now lets look at whats happening when connecting to the die.</p>
<p>After the app has started scanning for an active die and one has been found, the dice manager delegate , didDiscoverDie, will be called and the scanning is stopped using <b>[diceManager stopScan]</b>. Since we don&#8217;t know that we can successfully connect to the die, only that one is available, we store the returned found die as availableDie, then attempt a connection with it. If no available dice were found and the scanner times out (after 12 seconds), diceManagerStoppedScan: will get called. In our example we simply restart the scanning process and scan again.</p>
<p>Upon a successfull connection, dice manager didConnectDie delegate method is called. Since we want to differentiate between an available die and our successfully connected die, connectedDie is assigned and used for the rest of the games life cycle, and availableDie is nilled out. If for some reason there is an issue connecting to the available die, &#8216;failedConnectingDie:&#8217; is called. If a die is connected and looses that connection for some reason, the diceManager &#8216;didDisconnectDie:&#8217; is called. In this example a scan is started again to try and regain a connection.</p>
<p>Once we have a connected die, it is easy to start the various sensor updates and listen for their delegate calls. For this game, we will only worry about <b>[connectedDie startRollUpdates]</b>, <b>[connectedDie stopRollUpdates]</b>, and the corresponding delegate methods to receive the roll response once a valid roll is done.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">void</span>)die:(<span style="color: #000080">DPDie</span> *)die didRoll:(<span style="color: #000080">DPRoll</span> *)roll error:(<span style="color: #000080">NSError</span> *)error</pre>
</div>
<p>The value of the roll is returned in roll.result with roll state in roll.flag that gives information about the roll itself. <span style="color: #993366">DPRollFlagOK</span> is returned with a valid roll, <span style="color: #993366">DPRollFlagTilt</span> is returned if the die has landed on a tilt, and <span style="color: #993366">DPRollFlagTooShort</span> if not enough time was taken to make the roll. These flags are part of the anti cheat error checking done within the die.</p>
<p>As we add the functionality of the game, you will also see how easy it is to change and animate the LEDs for each face once a roll is completed, or for any other reason you may need.</p>
<p>For the actual gameplay we will be adding 6 new methods but first we need to create a player object to represent each of our 2 players. Right click on the RaceToSpace folder in the left hand, project navigator pane and select new file. Create a new subclass of NSObject and name it Player.</p>
<p>Add the following to the Player.h,</p>
<div class="wp_syntax">
<pre><span style="color: #993300">@interface</span> Player : <span style="color: #000080">NSObject</span>

<span style="color: #993300">@property</span>(nonatomic, retain) <span style="color: #000080">UIImage</span> *shipImage;
<span style="color: #993300">@property</span>(nonatomic) <span style="color: #000080">NSInteger</span> score;
<span style="color: #993300">@property</span>(nonatomic) <span style="color: #000080">NSInteger</span> playerNumber;

- (<span style="color: #993300">id</span>)initWithImage:(<span style="color: #000080">UIImage</span> *)shipImage;

@end</pre>
</div>
<p>and this to your Player.m,</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">id</span>)initWithImage:(<span style="color: #000080">UIImage</span> *)shipImage;
{
    self = [super init];
    if (self) {
<span style="color: #008000">        // Initialization code
</span>        self.shipImage = shipImage;
        self.score = 0;
    }
    return self;
}</pre>
</div>
<p>Now we need to create the 2 players, do this at the beginning of your viewDidLoad, just after the call to super. Each player is created and assigned a player number, a UIImageView is also created to display the players ship, placed at their start positions on the screen and added to the view. By setting the tag of each of these UIImageViews to the players number, we can be sure to move the correct ship for the player. Initialize our player reference NSArray with both of our players..</p>
<div class="wp_syntax">
<pre> 
    [super viewDidLoad];
<span style="color: #008000">    // Do any additional setup after loading the view, typically from a nib.
</span>    
<span style="color: #008000">    //Setup Player 1
</span>    <span style="color: #000080">Player</span> *player1 = [[Player alloc] initWithImage:[UIImage imageNamed:@"rocketShip1"]];
    player1.playerNumber = 1;
    UIImageView *player1ship = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 113)];
    player1ship.contentMode = UIViewContentModeCenter;
    player1ship.image = player1.shipImage;
    player1ship.center = CGPointMake(192, 928);
    player1ship.tag = player1.playerNumber;
    [self.view addSubview:player1ship];

<span style="color: #008000">    //Setup Player 2
</span>    <span style="color: #000080">Player</span> *player2 = [[Player alloc] initWithImage:[UIImage imageNamed:@"rocketShip2"]];
    player2.playerNumber = 2;
    UIImageView *player2ship = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 64, 113)];
    player2ship.contentMode = UIViewContentModeCenter;
    player2ship.image = player2.shipImage;
    player2ship.center = CGPointMake(576, 928);
    player2ship.tag = player2.playerNumber;
    [self.view addSubview:player2ship];</pre>
</div>
<p>Add some code to our Play button action and add these remaining methods to you ViewController.m and we will take a quick walk thru of the game.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">IBAction</span>)play:(<span style="color: #000080">id</span>)sender
{
<span style="color: #008000">    //Rest players score to 0 in case this is a <span style="color: #000080">replay.
</span></span>    self.play.hidden = YES;
    [self setupPlayer];
}

- (<span style="color: #993300">void</span>)setupPlayer
{
    if (!self.currentPlayer){
<span style="color: #008000">        //Its a new game, make current player, player 1.
</span>        self.currentPlayer = [self.players objectAtIndex:0];
    } else {
<span style="color: #008000">            //Switch between players
</span>            if (self.currentPlayer.playerNumber == 1){
<span style="color: #008000">                //Make current player, player 2.
</span>                self.currentPlayer = [self.players objectAtIndex:1];
            } else {
<span style="color: #008000">                //Make current player, player 1.
</span>                self.currentPlayer = [self.players objectAtIndex:0];
            }
        }
    self.status.text = [NSString stringWithFormat:@"Player %i's turn", self.currentPlayer.playerNumber];

<span style="color: #008000">    //Start DICE+ roll updates for current player.
</span>    [connectedDie startRollUpdates];
}

- (<span style="color: #993300">void</span>)prepareForNewGame
{
<span style="color: #008000">    //Set player scores to 0 and reset ships to start position.
</span>    for (Player *p in self.players){
        p.score = 0;
        UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:p.playerNumber];
        playerShip.center = CGPointMake(playerShip.center.x, 928);
    }

<span style="color: #008000">    //Reset some labels
</span>    self.play.hidden = NO;
    self.player1Score.text = @"0 points";
    self.player2Score.text = @"0 points";
    self.status.text = @"Press play to begin.";

<span style="color: #008000">    //Animate background back to start position
</span>    [UIView animateWithDuration:.25 animations:^{
        self.spaceBackground.center = CGPointMake(384, 0);
    }];

<span style="color: #008000">    //Set current player to nil so new game will start with player 1.
</span>    self.currentPlayer = nil;
}

- (<span style="color: #993300">BOOL</span>)currentPlayerIsWinner
{
<span style="color: #008000">    //check if current player has matched, or exceeded max points
</span>    if (self.currentPlayer.score &gt;= MaxPoints){
        return YES;
    }
    return NO;
}

- (<span style="color: #993300">void</span>)moveCurrentPlayer:(<span style="color: #000080">NSInteger</span>)rollValue
{
<span style="color: #008000">    //Get UIImageView for players ship and animate p the screen.
</span>    UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:self.currentPlayer.playerNumber];

<span style="color: #008000">    //Calculate appropriate distance to travel based on MaxPoints, so winner is always near top of screen.
</span>    int offset = (1024 - rintf(1024/6))/MaxPoints;
    int distance = rollValue * offset;
    self.currentPlayer.score = self.currentPlayer.score + rollValue;

    if ([self currentPlayerIsWinner]) {
<span style="color: #008000">        //Current player has won. Do something.
</span>        NSString *winnerText = [NSString stringWithFormat:@"Congratulations player %i, you are the Winner!", self.currentPlayer.playerNumber];
        UIAlertView *winnerNotify = [[UIAlertView alloc] initWithTitle:@"WINNER!!" message:winnerText delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [winnerNotify show];
        self.status.text = @"We have a WINNER!";

<span style="color: #008000">        //Fly the winning ship the rest of the way off the screen.
</span>        [UIView animateWithDuration:1 animations:^{
            playerShip.center = CGPointMake(playerShip.center.x, -200);
        }];
        return;
    } else {
        [UIView animateWithDuration:1 animations:^{
            playerShip.center = CGPointMake(playerShip.center.x, playerShip.center.y - distance);
        }];
        if (self.currentPlayer.playerNumber == 2){
            self.player2Score.text = [NSString stringWithFormat:@"%i points", self.currentPlayer.score];
            [self slideBackground:distance];
        } else {
            self.player1Score.text = [NSString stringWithFormat:@"%i points", self.currentPlayer.score];
            [self setupPlayer];
        }
    }
}

- (<span style="color: #993300">void</span>)slideBackground:(<span style="color: #000080">NSInteger</span>)distance
{
<span style="color: #008000">    //Check if background is able to scroll any further, if so scroll up distace value.
</span>    if (self.spaceBackground.center.y + distance &lt; 1024){
        [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.spaceBackground.center = CGPointMake(384, self.spaceBackground.center.y + distance);
        } completion:^(BOOL finished) {
<span style="color: #008000">            //Setup next player when animation is done.
</span>            [self setupPlayer];
        }];
    }
}</pre>
</div>
<p>When the play button is pressed and the <b>- (IBAction)play:(id)sender</b> callback is called, the play button is hidden and <b>[self setupPlayer]</b> is called. SetupPlayer, checks to see if self.currentPlayer uninitialized, if so then it represents a new game and currentPlayer is assigned as Player1 from index 0 of the Players reference array. We set the text of our connection status label to state that it is player 1&#8217;s turn and the DICE+ roll updates are started with <b>[connectedDie startRollUpdates]</b>; The game is now waiting for player 1 to roll. Once a valid roll is made, the <b>die: didRoll:</b> delegate method is called. With a successful roll.flag of DPRollFlagOK a few things happen. Dependent on the value of roll.result, an int called mask is set to a specific value. This mask value is how we tell the DICE+ which face or faces to light up.</p>
<p>&nbsp;</p>
<p>A quick explanation of the  mask value. If you think of a 6 bit binary number, adding each decimal value of the bits (or faces) you want lit up, this total number is the mask. For example if I wanted the number 2 face to light,</p>
<p>1    2    3    4    5    6  (face)</p>
<p>1    2    4    8    16  32  (decimal value)</p>
<p>0    1    0    0    0    0  (binary mask)</p>
<p>Number for the mask would be 2.</p>
<p>If you wanted faces 1, 2 and 3 to light up, the mask would be,</p>
<p>1    2    3    4    5    6  (face)</p>
<p>1    2    4    8    16  32  (decimal value)</p>
<p>1    1    1     0    0    0  (binary mask)</p>
<p>Number for mask would be 6.</p>
<p>All faces would be represented by the number 63.</p>
<p>&nbsp;</p>
<p>We can pass this mask, as well as color and various other info to the die in a couple of different methods used to blink and fade the lights on and off. In our game, when a roll is invalid (either tilted or too short), an animation is used to blink all the faces red for a short time. Upon a valid roll, the face of the rolled value is blinked green.</p>
<p>After a successful roll, the roll updates of the die are stopped, this may not be necessary but may stop any accidental rolls and turn changes. <b>[self moveCurrentPlayer:roll.result]</b> is then called, passing along the rolled die value. This value is used in moveCurrentPlayer to move the current players ship up the screen (players UIImageView is found in the view by its tag), added to their current score and checks to see if the current player is the winner <b>[self currentPlayerIsWinner]</b> and returns a TRUE/FALSE. If the current player is not the winner, the game continues to the next step. If this is player2, then the background image is slid down the screen an appropriate amount in <b>[self slideBackground:roll.result]</b> using a simple UIView animation. Whether the background needed sliding or not, the next step is <b>[self setupPlayer]</b>.</p>
<p><b>[self setupPlayer]</b> determines that the currentPlayer is valid, checks the player&#8217;s number of the current player, and switches current player to the other player, roll updates are started once again and the next player can take their turn. In <b>[self moveCurrentPlayer]</b> once a player reaches, or passes, 25 (as defined at the top of ViewController.m in MaxPoints) that triggers the winning phase. One slight addition to add to our game is to show a UIAlertView when a player wins and inform us when it is dismissed so we can reset the game.</p>
<p>Add to your ViewController.h so we can know when the user dismisses the winning text and delegate call for the alertView,</p>
<div class="wp_syntax">
<pre>@interface ViewController : UIViewController &lt;DPDiceManagerDelegate, <span style="color: #0000ff">UIAlertViewDelegate</span>&gt;</pre>
</div>
<p>and the following in your ViewController.m so we know when it is dismissed.</p>
<div class="wp_syntax">
<pre>- (<span style="color: #993300">void</span>)alertView:(<span style="color: #000080">UIAlertView</span> *)alertView didDismissWithButtonIndex:(<span style="color: #000080">NSInteger</span>)buttonIndex
{
<span style="color: #008000">    //Once cancel is pressed on the alertview, prepare for new game.
</span>    [self prepareForNewGame];
}</pre>
</div>
<p>On a winning score the UIAlertView is displayed, status text is updated and the winning ship is flown the rest of the way of the screen. When the player dismisses the UIAlertView popup, <b>[self prepareForNewGame]</b> is called. Within that method, variables are reset, ships are set back to their starting positions and currentPlayer is set to nil. With a press of the Play button once again, the game play can start again.</p>
<p>I realize a lot more could be added, more in-depth animations could be done and special instances such as rolling the same number twice in a row to initiate special rules but since this was more about attaching and using the DICE+, I will leave those upgrades and additions to you. Hope you enjoyed this tutorial, I have enjoyed getting to test out this new product and look forward to what may come of it. Thanks.</p>
<p>Here is the link to the <a title="Race to Space image files." href="/wp-content/uploads/2013/07/RaceToSpaceAssets.zip">images</a> used in the game, and here is a <a title="Race To Space" href="https://github.com/B-Sides/RaceToSpace" target="_blank">link</a> to the GitHub repository. In order to ensure the latest SDK, you will need to <a title="Developer link" href="http://developers.dicepl.us" target="_blank">download the DICE+ SDK</a> (the version of the SDK depends on the firmware loaded on the Die) separately, and drag the DicePlus.framework file into the project.</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2013/07/06/dice-rocketships-and-a-giveaway/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NSTimer: The Poor Man&#8217;s Threading &#8211; Code Snapshot</title>
		<link>http://icodeblog.com/2009/07/23/nstimer-the-poor-mans-threading-code-snapshot/</link>
		<comments>http://icodeblog.com/2009/07/23/nstimer-the-poor-mans-threading-code-snapshot/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 18:28:26 +0000</pubDate>
		<dc:creator><![CDATA[Collin]]></dc:creator>
				<category><![CDATA[Snippets]]></category>
		<category><![CDATA[beginner]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[NSTimer]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=1152</guid>
		<description><![CDATA[Introduction
Hey guys. So usually the posts we put up here involve screencasts and presentations, but we are going to start also posting small less time consuming pieces for the site. Today I bring to you a small project involving NSTimers. Today we are going to build an app that represents a horse race. We will create a view with 6 small UIView squares with a blue background at the bottom of the screen, we will use a timer to move  ...]]></description>
				<content:encoded><![CDATA[<h1><span style="color: #ff6600;">Introduction</span></h1>
<p>Hey guys. So usually the posts we put up here involve screencasts and presentations, but we are going to start also posting small less time consuming pieces for the site. Today I bring to you a small project involving NSTimers. Today we are going to build an app that represents a horse race. We will create a view with 6 small UIView squares with a blue background at the bottom of the screen, we will use a timer to move a random one of them forward a random amount of distance. Let&#8217;s get started!</p>
<p><a href="/wp-content/uploads/2009/07/Picture-162.png"><img class="aligncenter size-full wp-image-1164" title="Picture 16" src="/wp-content/uploads/2009/07/Picture-162.png" alt="Picture 16" width="351" height="693" /></a></p>
<h1><span style="color: #ff6600;">Source</span></h1>
<p>You can get the source here: <a href="/wp-content/uploads/2009/07/NSTimerDemo2.zip">NSTimerDemo</a></p>
<h1><span style="color: #ff6600;">Steps</span></h1>
<h3><span style="color: #ff6600;">Step 1<br />
</span></h3>
<p>Create a view based application in xCode. Call it whatever.</p>
<h3><span style="color: #ff6600;">Step 2<br />
</span></h3>
<p>In your view controller class header file add:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSTimer</span> <span style="color: #002200;">*</span>myTimer;</pre></td></tr></table></div>

<h3><span style="color: #ff6600;">Step 3<br />
</span></h3>
<p>In your view controller class, uncomment out the viewDidLoad method and fill in the following code:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad
<span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
&nbsp;
      CGRect workingFrame;
      workingFrame.origin.x <span style="color: #002200;">=</span> <span style="color: #2400d9;">15</span>;
      workingFrame.origin.y <span style="color: #002200;">=</span> <span style="color: #2400d9;">400</span>;
      workingFrame.size.width <span style="color: #002200;">=</span> <span style="color: #2400d9;">40</span>;
      workingFrame.size.height <span style="color: #002200;">=</span> <span style="color: #2400d9;">40</span>;
&nbsp;
      <span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> i <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; i <span style="color: #002200;">&amp;</span>lt; <span style="color: #2400d9;">6</span>; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
      <span style="color: #002200;">&#123;</span>
           UIView <span style="color: #002200;">*</span>myView <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>workingFrame<span style="color: #002200;">&#93;</span>;
           <span style="color: #002200;">&#91;</span>myView setTag<span style="color: #002200;">:</span>i<span style="color: #002200;">&#93;</span>;
           <span style="color: #002200;">&#91;</span>myView setBackgroundColor<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIColor blueColor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
           workingFrame.origin.x <span style="color: #002200;">=</span> workingFrame.origin.x <span style="color: #002200;">+</span> workingFrame.size.width <span style="color: #002200;">+</span> <span style="color: #2400d9;">10</span>;
           <span style="color: #002200;">&#91;</span>self.view addSubview<span style="color: #002200;">:</span>myView<span style="color: #002200;">&#93;</span>;
      <span style="color: #002200;">&#125;</span>
&nbsp;
      myTimer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSTimer</span> scheduledTimerWithTimeInterval<span style="color: #002200;">:</span>.1 target<span style="color: #002200;">:</span>self selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>moveACar<span style="color: #002200;">&#41;</span> userInfo<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> repeats<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<h3><span style="color: #ff6600;">Step 4<br />
</span></h3>
<h3><span style="color: #ff6600;"> </span></h3>
<p>In your view controller class, add the following method:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>moveACar
<span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">int</span> r <span style="color: #002200;">=</span> <span style="color: #a61390;">rand</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">%</span> <span style="color: #2400d9;">6</span>;
      NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;My number is %d&quot;</span>, r<span style="color: #002200;">&#41;</span>;
&nbsp;
      <span style="color: #a61390;">for</span><span style="color: #002200;">&#40;</span>UIView <span style="color: #002200;">*</span>aView <span style="color: #a61390;">in</span> <span style="color: #002200;">&#91;</span>self.view subviews<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>
      <span style="color: #002200;">&#123;</span>
           <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>aView tag<span style="color: #002200;">&#93;</span> <span style="color: #002200;">==</span> r<span style="color: #002200;">&#41;</span>
           <span style="color: #002200;">&#123;</span>
                <span style="color: #a61390;">int</span> movement <span style="color: #002200;">=</span> <span style="color: #a61390;">rand</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">%</span> <span style="color: #2400d9;">100</span>;
                CGRect workingFrame <span style="color: #002200;">=</span> aView.frame;
                workingFrame.origin.y <span style="color: #002200;">=</span> workingFrame.origin.y <span style="color: #002200;">-</span> movement;
&nbsp;
                <span style="color: #002200;">&#91;</span>UIView beginAnimations<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> context<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>UIView setAnimationDuration<span style="color: #002200;">:</span>.2<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>aView setFrame<span style="color: #002200;">:</span>workingFrame<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#91;</span>UIView commitAnimations<span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #a61390;">if</span><span style="color: #002200;">&#40;</span>workingFrame.origin.y <span style="color: #002200;">&amp;</span>lt; <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>
                <span style="color: #002200;">&#123;</span>
                    <span style="color: #002200;">&#91;</span>myTimer invalidate<span style="color: #002200;">&#93;</span>;
                <span style="color: #002200;">&#125;</span>
           <span style="color: #002200;">&#125;</span>
      <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<h1><span style="color: #ff6600;">Conclusion</span></h1>
<p>So that is it. Timers are really cool and come in handy for all sorts of small problems in a project. Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/07/23/nstimer-the-poor-mans-threading-code-snapshot/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>EyeCue relaunched!</title>
		<link>http://icodeblog.com/2009/05/11/eyecue-relaunched/</link>
		<comments>http://icodeblog.com/2009/05/11/eyecue-relaunched/#comments</comments>
		<pubDate>Mon, 11 May 2009 21:55:13 +0000</pubDate>
		<dc:creator><![CDATA[rhou]]></dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[EyeCue]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[itunes]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=784</guid>
		<description><![CDATA[EyeCue relaunched on iTunes! EyeCue has received tremendous amount of success since its original launch. We have had thousands of downloads on the daily basis. Unfortunately, quite a few users experienced crashes due to the compatibility issues in iPhone SDK 2.1 and iPhone SDK 2.2.]]></description>
				<content:encoded><![CDATA[<div class="preface">
<p>EyeCue has received tremendous amount of success since its original launch.  We have had thousands of downloads on the daily basis.  Unfortunately, quite a few users experienced crashes due to the compatibility issues in iPhone SDK 2.1 and iPhone SDK 2.2.</p>
<p>In an effort the combat the incompatibility issue, we&#8217;ve recompiled the code and re-released the new and updated version in iTunes.</p>
<p>I have even made a video for it.  Check it out <a href="http://www.youtube.com/watch?v=-JxZpfzhV2Y">here</a></p>
<p>Get your copy <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=308416341&amp;mt=8">here</a></p>
<p>Giddy up!</p></div>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/05/11/eyecue-relaunched/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>iPhone Game Programming Tutorial Part 2- User Interaction, Simple AI, Game Logic</title>
		<link>http://icodeblog.com/2009/02/18/iphone-game-programming-tutorial-part-2-user-interaction-simple-ai-game-logic/</link>
		<comments>http://icodeblog.com/2009/02/18/iphone-game-programming-tutorial-part-2-user-interaction-simple-ai-game-logic/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 22:35:25 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[iPhone Game Programming]]></category>
		<category><![CDATA[iphone game tutorial]]></category>
		<category><![CDATA[itennis]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=656</guid>
		<description><![CDATA[Ok folks, here it is. The next tutorial in our iPhone game programming tutorial (sorry for the delay).  Today, I will be discussing the basics of player interaction, simple game AI, and game logic.  We will also be exploring how to do simple collision detection so we know when the ball hits a paddle. Per popular request, I will be adding &#8220;Challenges&#8221; to the bottom of the tutorials from now on to give some more advanced ideas for  ...]]></description>
				<content:encoded><![CDATA[<p>Ok folks, here it is. The next tutorial in our iPhone game programming tutorial (sorry for the delay).  Today, I will be discussing the basics of player interaction, simple game AI, and game logic.  We will also be exploring how to do simple collision detection so we know when the ball hits a paddle. Per popular request, I will be adding &#8220;Challenges&#8221; to the bottom of the tutorials from now on to give some more advanced ideas for improvement. Let&#8217;s begin. Start by opening your code from part 1&#8230;</p>
<h3>User Interaction</h3>
<p>The first thing we will implement is user interaction.  All we really want to do is move the paddle&#8217;s X location to the X location of the touch from the user.  This will be a very simple implementation and could be much better (I will add this as a challenge at the bottom of the tutorial).  Open <strong>iTennisViewController.m </strong>and add the following code.</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/screenshot_012.jpg"><img class="alignnone size-full wp-image-657" title="screenshot_01" src="/wp-content/uploads/2009/02/screenshot_012.jpg" alt="screenshot_01" width="442" height="218" /></a></p>
<p style="text-align: left; ">Just as we did in a previous tutorial, we are overriding the <strong>touchesMoved</strong> method.  This will detect when the user &#8220;drags&#8221; their finger on the screen.  First, I added the &#8220;else if&#8221; statement inside of <strong>touchesBegan</strong> that simply forwards all events to <strong>touchesMoved</strong> if the game is in a running state.</p>
<p style="text-align: left; ">The first 2 lines inside of <strong>touchesMoved </strong>simply detect the location of the user&#8217;s touch.  Next, we need to create a new CGPoint from the X location of the touch and the Y location of the yellow racquet (player racquet).  Objective-C won&#8217;t simply let us say racquet_yellow.center.x = location.x.  This is probably because CGPoint is immutable (not editable).</p>
<p style="text-align: left; ">Finally, the center of the player&#8217;s racquet is set to our new location.</p>
<h3>Collision Detection</h3>
<p>*Update, the user Naren has pointed out a much simpler collision detection.  The code has been updated to reflect it. Inside the gameLoop method of iTennisViewController.m add the following code</p>
<p style="text-align: center; "><span style="color: #0000ee; text-decoration: underline;"><a href="/wp-content/uploads/2009/02/picture-11.png"></a><a href="/wp-content/uploads/2009/02/screenshot_0111.jpg"><img class="alignnone size-full wp-image-677" title="screenshot_011" src="/wp-content/uploads/2009/02/screenshot_0111.jpg" alt="screenshot_011" width="370" height="175" /></a></span></p>
<p style="text-align: left; ">So, Apple has provided us with a very handy methods to check if to object frames collide.  Its called <strong>CGRectIntersectsRect.</strong>  We simply hand this method the frame of our ball and racquet.  When the ball collides with the racquet, we want to reverse its Y velocity.  The next if statement is required because sometimes we get in a state where the ball gets &#8220;trapped&#8221; on a paddle bouncing back and for and not going anywhere.  So, we want to ensure the ball&#8217;s velocity only gets reversed if it is front of each racquet. (Note, the NSlog is not needed, it was just for debugging)</p>
<h3>Simple Game AI</h3>
<p style="text-align: left; ">Next, we are going to discuss how simple AI can be added to allow a computer player to play iTennis with you.  Many of you might not know just how much is involved in a decent Artificial intelligence.  I could go on and on with nerdy math, philosophy, heuristics and the like, but I&#8217;m not.  I will show you some super NOOB, very easy to understand game AI.  Basically, the computer will &#8220;watch&#8221; the ball and move in the direction of it in hopes of hitting it.  Let&#8217;s get started&#8230; </p>
<p style="text-align: left; ">We first need to define a constant that will define how fast the computer player can move.  Add the following define to the top of iTennisViewController.m</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/picture-21.png"><img class="alignnone size-full wp-image-660" title="picture-2" src="/wp-content/uploads/2009/02/picture-21.png" alt="picture-2" width="156" height="20" /></a></p>
<p style="text-align: left; ">As you start testing, you can adjust this number.  This is basically defining how fast the computer player can move in order to get to the ball.  The higher you make this number, the &#8220;better&#8221; the computer player will be.  You could actually make your computer unbeatable if this number were high enough.  Now, add the following code right under your collision detection code:</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/picture-31.png"><img class="alignnone size-full wp-image-661" title="picture-3" src="/wp-content/uploads/2009/02/picture-31.png" alt="picture-3" width="663" height="174" /></a></p>
<p style="text-align: left; ">The first &#8220;if&#8221; statement is to add some difficulty for the computer.  It basically checks to see if the ball is on &#8220;his&#8221; side of the court.  The computer will not move or respond to the ball unless it&#8217;s on his side.  It could be omitted, but makes for a more interesting game.  The next if statements check to see if the X coordinates of the center of the ball are different than the X coordinates of the center of the racquet.  If the ball is to the right of the computer&#8217;s racquet, the X coordinate of the computer&#8217;s racquet is increased by <strong>kCompMoveSpeed</strong>. If the ball is to the left of the computer&#8217;s racquet, the X coordinate of the computer&#8217;s racquet is decreased by <strong>kCompMoveSpeed. </strong></p>
<p style="text-align: left; ">It should now be clear how adjusting the kCompMoveSpeed variable, will affect the computer&#8217;s performance&#8230;</p>
<p style="text-align: left; ">Now, you can actually hit Build and Go to see the game in action.  As you can see the computer responds to the ball and hits it most of the time.  There is still one last piece to make the game fun. Scoring!</p>
<h3>Game Mechanics: Scoring</h3>
<p style="text-align: left; ">Now, we need a way to keep score.  This is actually some more simple collision detection.  We are basically checking to see if the ball collides with the back walls.  First, let&#8217;s define a few variables and a method.  Open up iTennisViewController.h.  Add the following highlighted code:</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/picture-41.png"><img class="alignnone size-full wp-image-662" title="picture-4" src="/wp-content/uploads/2009/02/picture-41.png" alt="picture-4" width="398" height="450" /></a></p>
<p style="text-align: left; ">We need integer representations of the score so we can add points when the player and the computer score.  Also, we will need a function called reset that will be called to reset the ball to the center of the screen.  Now we need to define one more variable.  Add the following line to your defines at the top of iTennisViewController.m</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/picture-51.png"><img class="alignnone size-full wp-image-663" title="picture-5" src="/wp-content/uploads/2009/02/picture-51.png" alt="picture-5" width="132" height="18" /></a></p>
<p style="text-align: left; ">This variable is pretty self explanatory, but in case you didn&#8217;t catch on, it defines the amount of points needed to win.  I just made it 5 for a quick game.  Now, let&#8217;s check to see if a player or computer scored.  Right after your AI code, add the following code:</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/picture-61.png"><img class="alignnone size-full wp-image-664" title="picture-6" src="/wp-content/uploads/2009/02/picture-61.png" alt="picture-6" width="346" height="150" /></a></p>
<p style="text-align: left; ">Ok, first we see 2 if statements.  The are basically checking to see if the ball has hit/passed the top or bottom of the screen.  If it passes the top, the player score gets incremented.  If it passes the bottom, the computer score gets incremented.  The next line contains a little bit of fanciness if you are new to programming.  We are calling the reset function, but what is that expression we are passing to it? </p>
<p style="text-align: left; ">Well, if you look at the definition of reset, it takes a BOOL value that determines if the game is over.  So this can either be true or false.  We are simply passing true or false when the expression is evaluated.  So, (player_score_value &gt;= kScoreToWin) will evaluate to false when the player_score_value variable is less than 5.  Once this variable reaches 5, it will return true and pass it into the reset function.</p>
<p style="text-align: left; ">Why do this? Well it saves us lines of code and complexity.  So now you don&#8217;t have to do if(player_score_value &gt;= kScoreToWin) ) [self reset:YES]; }else{[self reset:NO];} . make sense?</p>
<p style="text-align: left; ">Now, let&#8217;s define the reset function. Add the following method to iTennisViewController.m</p>
<p style="text-align: center; "><a href="/wp-content/uploads/2009/02/picture-71.png"><img class="alignnone size-full wp-image-665" title="picture-7" src="/wp-content/uploads/2009/02/picture-71.png" alt="picture-7" width="496" height="272" /></a></p>
<p style="text-align: left; ">The first thing we do is pause the game.  Remember pausing the game causes the &#8220;Tap to Begin&#8221; Message to Display. Next, we center the ball on the screen.  If YES/true was passed in for the newGame variable, we need to do a few things.  First, we check who won by comparing the computer and player scores.  Next, we update the &#8220;tapToBegin&#8221; message to notify the player who won.  You could add another label for this, but I am just recycling this one&#8230; Finally, we reset the player and computer scores to 0 because a new game is starting.</p>
<p style="text-align: left; ">If it is not a new game, we need to reset the tapToBegin message to display &#8220;tapToBegin&#8221;.  This has to be done in case the message was altered to say &#8220;Player/Computer wins!&#8221;. Finally, we update the labels on the screen to reflect the new scores.  Now you should be good to go&#8230;</p>
<p style="text-align: left; ">Click Build and Go and battle the computer in an epic game of iTennis!  If you have any comments or questions, leave them here or <a href="http://twitter.com/brandontreb">ask me on Twitter</a>.  You can also download the source for this tutorial <a href="/wp-content/uploads/2009/02/itennis-22.zip"></a><a href="/wp-content/uploads/2009/02/itennis-211.zip">here</a></p>
<h3>As Promised, Here are some challenges</h3>
<ul>
<li>Improve on user interaction &#8211; Make it so when the user taps, the racquet moves towards the tap rather than moves directly to the tap location</li>
<li>Improve collision detection &#8211; When the ball hits the paddle, use some simple physics to make the speed of the paddle affect the speed (and direction) of the ball</li>
<li>Improve on the AI &#8211; add some randomness to your AI, make it attempt to &#8220;predict&#8221; where the ball is going to be</li>
<li>Improve Scoring &#8211; Make it used tennis scores 15, 30 , etc&#8230;</li>
<li>Improve scoring &#8211; Make it so you must win by 2 points</li>
</ul>
<p style="text-align: left; ">Stay tuned for the next tutorial when I will be going over game audio, splash screen, about, and some other polishing&#8230; Happy iCoding!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2009/02/18/iphone-game-programming-tutorial-part-2-user-interaction-simple-ai-game-logic/feed/</wfw:commentRss>
		<slash:comments>163</slash:comments>
		</item>
		<item>
		<title>Torque Game Engine for iPhone</title>
		<link>http://icodeblog.com/2008/07/25/torque-game-engine-for-iphone/</link>
		<comments>http://icodeblog.com/2008/07/25/torque-game-engine-for-iphone/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 15:22:35 +0000</pubDate>
		<dc:creator><![CDATA[brandontreb]]></dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[engine]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[iPhone Articles]]></category>

		<guid isPermaLink="false">http://icodeblog.com/?p=25</guid>
		<description><![CDATA[<a href="http://www.garagegames.com/products/torque/iPhone/"></a>
An independent game developer known as <a href="http://www.garagegames.com">GarageGames</a> has recently released their tried and true game development engine for the iPhone.  They already have an engine for large platforms such as Mac, Windows, Linux, Wii, Xbox, and now they are expanding to the most up-in-coming mobile platfor ever; the iPhone.
&#8220;Ready to make games for the iPhone?&#8221; is the tagline on their game engine site.  They claim that &#8220;Making games for the iPhone is now a straightforward process  ...]]></description>
				<content:encoded><![CDATA[<p style="text-align: center;"><a href="http://www.garagegames.com/products/torque/iPhone/"><img class="aligncenter size-full wp-image-26 transparent" title="torque iphone game engine" src="/wp-content/uploads/2008/07/torque1.jpg" alt="" width="500" height="360" /></a></p>
<p>An independent game developer known as <a href="http://www.garagegames.com">GarageGames</a> has recently released their tried and true game development engine for the iPhone.  They already have an engine for large platforms such as Mac, Windows, Linux, Wii, Xbox, and now they are expanding to the most up-in-coming mobile platfor ever; the iPhone.</p>
<p>&#8220;Ready to make games for the iPhone?&#8221; is the tagline on their game engine site.  They claim that &#8220;Making games for the iPhone is now a straightforward process using Torque&#8217;s proven 2D and 3D tools for game development&#8221;.</p>
<p>GarageGames also boasts that they have added iPhone specific funtionality to Torque such as</p>
<ul>
<li>Multi-touch Input Support</li>
<li>Touchscreen Gesture Recognition</li>
<li>iPhone Optimized Compressed Texture</li>
<li>Advanced Character and Shape Animations</li>
</ul>
<p>With this release, I hope to see some great (possibly free) games for the iPhone in the near future.  They didn&#8217;t release specific pricing, but they boast that it will be affordable.  So <a href="http://www.garagegames.com/products/torque/iPhone/" target="_blank">check it out</a>, and make WOW for the iPhone!</p>
]]></content:encoded>
			<wfw:commentRss>http://icodeblog.com/2008/07/25/torque-game-engine-for-iphone/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
