IPhone Programming DICE plus

Friday, 25 October 2013

Dice+ImagescreenShot


IPhone Programming DICE plus


I received my DICE+ 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.
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.
First lets create a new, single view, portrait oriented project for iPad called ‘RaceToSpace’ using ARC (Automatic Reference Counting).  After downloading the DICE+ SDK from the website, drag and drop the framework into your project, add the ‘CoreBluetooth’, and QuartzCore frameworks. For DICE+, You will also have to add ‘-all_load’ 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 ‘spaceBackground’. 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 ‘touch up inside’ action onto your ViewController.m file and name it ‘Play’. Now that the basic building blocks are setup, we can get to configuring the software for use with your die.
In your ViewController .h, add the following code to match.
 
#import 
#import 
#import "Player.h"

@interface ViewController : UIViewController 
{
    DPDiceManager* diceManager;
    DPDie* availableDie;
    DPDie* connectedDie;
}
@property (weak, nonatomic) IBOutlet UILabel *player1Score;
@property (weak, nonatomic) IBOutlet UILabel *player2Score;
@property (weak, nonatomic) IBOutlet UIImageView *spaceBackground;
@property (weak, nonatomic) IBOutlet UILabel *status;
@property (nonatomic, retain) NSArray *players;
@property (nonatomic, retain) Player *currentPlayer;
@property (weak, nonatomic) IBOutlet UIButton *play;

@end
In your ViewController.m, add the following code to your viewDidLoad method. This initializes the dice manager, sets the DEV KEY with the [diceManager startScanning] command, and starts scanning for available devices. Also add the #define MaxPoints 25. This defines the winning score.
 
#define MaxPoints 25

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    if (connectedDie != nil) {
        return;
    }
    availableDie = nil;
    diceManager = [DPDiceManager sharedDiceManager];
    diceManager.delegate = self;

    //DICE+ generic development key.
    uint8_t key[8] = {0x83, 0xed, 0x60, 0x0e, 0x5d, 0x31, 0x8f, 0xe7};
    [diceManager setKey:key];

    //Start scanning for an available DICE+.
    [diceManager startScan];
    self.status.text = @"Searching for DICE+...";
}
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.
 
- (void)die:(DPDie *)die didRoll:(DPRoll *)roll error:(NSError *)error
{
    //Roll was valid
    if (roll.flags == DPRollFlagOK) {
      //Stop roll updates just to make sure wrong player doesnt mistakenly roll DICE+.
      [connectedDie stopRollUpdates];
      //Convert roll result (1-6) to binary mask equivalent
      int mask = 1 << (roll.result-1);
      //Blink the top face green showing roll result. DICE+ uses a binary 
      //mask for determinning which face, or faces to light.
 [connectedDie startBlinkAnimationWithMask:mask priority:0 r:0 g:255 b:0 
           onPeriod:100 cyclePeriod:50 blinkCount:5];
        //Move player ship
        [self moveCurrentPlayer:roll.result];

    } else if (roll.flags == DPRollFlagTilt) {
        //DICE+ roll error
        self.status.text = @"Roll Tilted";
        //Blink DICE+ faces red to indicate a roll error occured.
        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    } else if (roll.flags == DPRollFlagTooShort) {
        //DICE+ roll error
        self.status.text = @"Roll too short";
        //Blink dice plus faces red to indicate a roll error occured.
        [connectedDie startBlinkAnimationWithMask:63
                                         priority:1
                                                r:255
                                                g:0
                                                b:0
                                         onPeriod:100
                                      cyclePeriod:200
                                       blinkCount:4];
    }
}

#pragma mark - DPDiceManagerDelegate methods
- (void)centralManagerDidUpdateState:(CBCentralManagerState)state
{
    // See CBCentralManagerDelegate documentation for info about CBCentralManager 
    //state changes
}

- (void)diceManagerStoppedScan:(DPDiceManager *)manager
{
    //Scanning has stopped, restart scan if no available die was found.
    if (availableDie == nil) {
        [diceManager startScan];
        self.status.text = @"Searching for DICE+...";
    }
}

- (void)diceManager:(DPDiceManager *)manager didDiscoverDie:(DPDie *)die
{
    //A DICE+ die was found, not connected yet.
    availableDie = die;
    availableDie.delegate = (id)self;

    [diceManager stopScan];
    //Attempt to connect to available DICE+ found.
    [diceManager connectDie:availableDie];

    self.status.text = @"Connecting DICE+...";
}

- (void)diceManager:(DPDiceManager *)manager didConnectDie:(DPDie *)die
{
    //Available DICE+ connected and is ready for play.
    availableDie = nil;
    connectedDie = die;
    connectedDie.delegate = (id)self;
    self.status.text = @"Press play to begin.";
}

- (void)diceManager:(DPDiceManager *)manager failedConnectingDie:(DPDie *)
  die error:(NSError *)error
{
    //DICE+ failed connection attempt.
    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Connection failed... Searching...";

    [diceManager startScan];
}

- (void)diceManager:(DPDiceManager *)manager didDisconnectDie:(DPDie *)
die error:(NSError *)error
{
    //DICE+ disconnected
    availableDie = nil;
    connectedDie = nil;
    self.status.text = @"Die disconnected... Searching...";

    [diceManager startScan];
}

- (void)dieFailedAuthorization:(DPDie *)die error:(NSError *)error
{
    //DICE+ authorization failed.
    self.status.text = @"Failed authorization";
}
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.
We’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.
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 [diceManager stopScan]. Since we don’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.
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, ‘failedConnectingDie:’ is called. If a die is connected and looses that connection for some reason, the diceManager ‘didDisconnectDie:’ is called. In this example a scan is started again to try and regain a connection.
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 [connectedDie startRollUpdates][connectedDie stopRollUpdates], and the corresponding delegate methods to receive the roll response once a valid roll is done.
- (void)die:(DPDie *)die didRoll:(DPRoll *)roll error:(NSError *)error
The value of the roll is returned in roll.result with roll state in roll.flag that gives information about the roll itself. DPRollFlagOK is returned with a valid roll,DPRollFlagTilt is returned if the die has landed on a tilt, and DPRollFlagTooShort if not enough time was taken to make the roll. These flags are part of the anti cheat error checking done within the die.
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.
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.
Add the following to the Player.h,
@interface Player : NSObject

@property(nonatomic, retain) UIImage *shipImage;
@property(nonatomic) NSInteger score;
@property(nonatomic) NSInteger playerNumber;

- (id)initWithImage:(UIImage *)shipImage;

@end
and this to your Player.m,
- (id)initWithImage:(UIImage *)shipImage;
{
    self = [super init];
    if (self) {
        // Initialization code
        self.shipImage = shipImage;
        self.score = 0;
    }
    return self;
}
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..
 
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //Setup Player 1
Player *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];

//Setup Player 2
Player *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];
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.
- (IBAction)play:(id)sender
{
    //Rest players score to 0 in case this is a replay.
    self.play.hidden = YES;
    [self setupPlayer];
}

- (void)setupPlayer
{
    if (!self.currentPlayer){
        //Its a new game, make current player, player 1.
        self.currentPlayer = [self.players objectAtIndex:0];
    } else {
            //Switch between players
            if (self.currentPlayer.playerNumber == 1){
                //Make current player, player 2.
                self.currentPlayer = [self.players objectAtIndex:1];
            } else {
                //Make current player, player 1.
                self.currentPlayer = [self.players objectAtIndex:0];
            }
        }
self.status.text = [NSString stringWithFormat:@"Player %i's turn", 
self.currentPlayer.playerNumber];
    //Start DICE+ roll updates for current player.
    [connectedDie startRollUpdates];
}

- (void)prepareForNewGame
{
    //Set player scores to 0 and reset ships to start position.
    for (Player *p in self.players){
     p.score = 0;
     UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:p.playerNumber];
     playerShip.center = CGPointMake(playerShip.center.x, 928);
    }

    //Reset some labels
    self.play.hidden = NO;
    self.player1Score.text = @"0 points";
    self.player2Score.text = @"0 points";
    self.status.text = @"Press play to begin.";

    //Animate background back to start position
    [UIView animateWithDuration:.25 animations:^{
        self.spaceBackground.center = CGPointMake(384, 0);
    }];

    //Set current player to nil so new game will start with player 1.
    self.currentPlayer = nil;
}

- (BOOL)currentPlayerIsWinner
{
    //check if current player has matched, or exceeded max points
    if (self.currentPlayer.score >= MaxPoints){
        return YES;
    }
    return NO;
}

- (void)moveCurrentPlayer:(NSInteger)rollValue
{
    //Get UIImageView for players ship and animate p the screen.
    UIImageView *playerShip = (UIImageView *)[self.view viewWithTag:self.
    currentPlayer.playerNumber];

    //Calculate appropriate distance to travel based on MaxPoints, so winner
    //is always near top of screen.
    int offset = (1024 - rintf(1024/6))/MaxPoints;
    int distance = rollValue * offset;
    self.currentPlayer.score = self.currentPlayer.score + rollValue;

    if ([self currentPlayerIsWinner]) {
        //Current player has won. Do something.
        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!";

        //Fly the winning ship the rest of the way off the screen.
        [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];
        }
    }
}

- (void)slideBackground:(NSInteger)distance
{
    //Check if background is able to scroll any further, if so scroll up distace value.
if (self.spaceBackground.center.y + distance < 1024){
[UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.spaceBackground.center = CGPointMake(384, self.spaceBackground.center.y + distance); 
 } completion:^(BOOL finished) {
            //Setup next player when animation is done.
            [self setupPlayer];
        }];
    }
}
When the play button is pressed and the - (IBAction)play:(id)sender callback is called, the play button is hidden and [self setupPlayer] 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′s turn and the DICE+ roll updates are started with [connectedDie startRollUpdates]; The game is now waiting for player 1 to roll. Once a valid roll is made, the die: didRoll: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.

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,
1    2    3    4    5    6  (face)
1    2    4    8    16  32  (decimal value)
0    1    0    0    0    0  (binary mask)
Number for the mask would be 2.
If you wanted faces 1, 2 and 3 to light up, the mask would be,
1    2    3    4    5    6  (face)
1    2    4    8    16  32  (decimal value)
1    1    1     0    0    0  (binary mask)
Number for mask would be 6.
All faces would be represented by the number 63.

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.
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. [self moveCurrentPlayer:roll.result] 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 [self currentPlayerIsWinner] 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 [self slideBackground:roll.result] using a simple UIView animation. Whether the background needed sliding or not, the next step is [self setupPlayer].
[self setupPlayer] determines that the currentPlayer is valid, checks the player’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 [self moveCurrentPlayer] 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.
Add to your ViewController.h so we can know when the user dismisses the winning text and delegate call for the alertView,
@interface ViewController : UIViewController 
and the following in your ViewController.m so we know when it is dismissed.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:
(NSInteger)buttonIndex
{
    //Once cancel is pressed on the alertview, prepare for new game.
    [self prepareForNewGame];
}
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, [self prepareForNewGame] 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.
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.


Regards
Owntutorials | Cameron Thomas
MaximeTech | Best IT solutions Provider | Web Development |Mobile Applications

No comments:

Post a Comment

 

Total Pageviews

Blogroll

Most Reading