iPhone開(kāi)發(fā)之GameKit藍(lán)牙實(shí)例講解
iPhone開(kāi)發(fā)應(yīng)用中關(guān)于GameKit藍(lán)牙實(shí)例講解是本文要介紹的內(nèi)容,主要是來(lái)了解并學(xué)習(xí)GameKit藍(lán)牙實(shí)例。介紹一下這個(gè)實(shí)例實(shí)現(xiàn)的是兩個(gè)帶有藍(lán)牙設(shè)備的touch之間的一個(gè)小游戲,在界面上有個(gè)可以響應(yīng)事件的UIView(之前說(shuō)過(guò))可以點(diǎn)擊,然后看誰(shuí)新達(dá)到WINNING_TAP_COUNT (游戲中一常量可以自己設(shè)置)誰(shuí)先達(dá)到誰(shuí)就贏了,然后通知對(duì)方。還要引入GameKit.framework框架
頭文件BlueToothViewController.h:
- //
- //
- // BlueToothViewController.h
- // BlueTooth
- //
- // Created by mingchun liu on 09-11-24.
- // Copyright sdie 2009. All rights reserved.
- //
- #import <UIKit/UIKit.h>
- #import <GameKit/GameKit.h>
- #define START_GAME_KEY @"startgame"
- #define END_GAME_KEY @"endgame"
- #define TAP_COUNT_KEY @"taps"
- #define WINNING_TAP_COUNT 50
- #define AMIPHD_P2P_SESSION_ID @"amiphdp2p2"//這個(gè)是藍(lán)牙協(xié)議
- @interface BlueToothViewController : UIViewController<GKPeerPickerControllerDelegate,GKSessionDelegate>{
- BOOL actingAsHost;//是否提供服務(wù),客戶端還是服務(wù)器端
- int playerTapCount;//記錄玩家點(diǎn)擊次數(shù)
- int opponentTapCount;//對(duì)方點(diǎn)擊次數(shù)
- IBOutlet UILabel *playerTapCountLabel;//顯示玩家點(diǎn)擊次數(shù)
- IBOutlet UILabel *opponentTapCountLabel;//顯示對(duì)手點(diǎn)擊次數(shù)
- NSString *opponentID;//對(duì)方標(biāo)識(shí)符
- GKSession *gkSession;
- IBOutlet UILabel *startQuitButton;//開(kāi)始退出按鈕
- }
- @property BOOL actingAsHost;
- @property int playerTapCount;
- @property int opponentTapCount;
- @property (nonatomic,retain) GKSession *gkSession;
- @property (nonatomic,retain) NSString *opponentID;
- @property (nonatomic,retain)UILabel *playerTapCountLabel;
- @property (nonatomic,retain)UILabel *opponentTapCountLabel;
- @property (nonatomic,retain)UILabel *startQuitButton;
- -(IBAction) handleStartQuitTapped;//處理開(kāi)始退出操作
- -(IBAction) handleTapViewTapped;//處理點(diǎn)擊UIView的操作
- -(void) updateTapCountLabels;//更新顯示
- -(void) initGame;//初始化游戲
- -(void) hostGame;
- -(void) joinGame;//加入游戲
- -(void) endGame;//結(jié)束游戲
- -(void) showEndGameAlert;//彈出結(jié)束游戲?qū)υ捒?
- @end
- #import "BlueToothViewController.h"
- @implementation BlueToothViewController
- @synthesize actingAsHost;
- @synthesize playerTapCount;
- @synthesize opponentID;
- @synthesize playerTapCountLabel;
- @synthesize opponentTapCountLabel;
- @synthesize startQuitButton;
- @synthesize gkSession;
- @synthesize opponentTapCount;
- -(IBAction) handleStartQuitTapped {//建立鏈接操作,彈出鏈接窗口顯示在線
- if (! opponentID) {//如果對(duì)手ID為空就建立服務(wù)端提供服務(wù)
- actingAsHost = YES;
- GKPeerPickerController *peerPickerController =[[GKPeerPickerController alloc] init];
- peerPickerController.delegate = self;
- peerPickerController.connectionTypesMask =
- GKPeerPickerConnectionTypeNearby;
- [peerPickerController show];
- }
- }
- -(IBAction) handleTapViewTapped {//點(diǎn)擊操作
- playerTapCount++;
- [self updateTapCountLabels];
- // did we just win?
- BOOL playerWins = playerTapCount >= WINNING_TAP_COUNT;//當(dāng)點(diǎn)擊達(dá)到一定次數(shù)時(shí)
- // send tap count to peer
- NSMutableData *message = [[NSMutableData alloc] init];//傳的數(shù)據(jù)類型為nsdata類型的
- NSKeyedArchiver *archiver =
- [[NSKeyedArchiver alloc] initForWritingWithMutableData:message];
- [archiver encodeInt:playerTapCount forKey: TAP_COUNT_KEY];
- if (playerWins)
- [archiver encodeBool:YES forKey:END_GAME_KEY];
- [archiver finishEncoding];//打包傳數(shù)據(jù)
- GKSendDataMode sendMode =
- playerWins ? GKSendDataReliable : GKSendDataUnreliable;//判斷用可靠的鏈接還是不可靠的鏈接
- [gkSession sendDataToAllPeers: message withDataMode:sendMode error:NULL];//發(fā)送數(shù)據(jù)
- [archiver release];
- [message release];
- // also end game locally
- if (playerWins)
- [self endGame];
- }
- -(void) updateTapCountLabels {
- playerTapCountLabel.text =
- [NSString stringWithFormat:@"%d", playerTapCount];
- opponentTapCountLabel.text =
- [NSString stringWithFormat:@"%d", opponentTapCount];
- }
- -(void) initGame {
- playerTapCount = 0;
- opponentTapCount = 0;
- }
- -(void) hostGame {
- [self initGame];
- NSMutableData *message = [[NSMutableData alloc] init];
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]
- initForWritingWithMutableData:message];
- [archiver encodeBool:YES forKey:START_GAME_KEY];
- [archiver finishEncoding];
- NSError *sendErr = nil;
- [gkSession sendDataToAllPeers: message
- withDataMode:GKSendDataReliable error:&sendErr];
- if (sendErr)
- NSLog (@"send greeting failed: %@", sendErr);
- // change state of startQuitButton
- startQuitButton.text = @"Quit";
- [message release];
- [archiver release];
- [self updateTapCountLabels];
- }
- -(void) joinGame {
- [self initGame];
- startQuitButton.text = @"Quit";
- [self updateTapCountLabels];
- }
- //一下是代理方法
- -(GKSession *) peerPickerController: (GKPeerPickerController*) controller
- sessionForConnectionType: (GKPeerPickerConnectionType) type {
- if (!gkSession) {//如果沒(méi)有鏈接時(shí)建立連接
- gkSession = [[GKSession alloc]
- initWithSessionID:AMIPHD_P2P_SESSION_ID//根據(jù)此值判斷用的是什么鏈接
- displayName:nil//在線用戶名
- sessionMode:GKSessionModePeer];
- gkSession.delegate = self;
- }
- return gkSession;
- }
- - (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
- {//當(dāng)picker接收到數(shù)據(jù)后將其釋放掉,否則進(jìn)入不了界面
- [picker dismiss];
- picker.delegate = nil;
- [picker autorelease];
- }
- - (void)session:(GKSession *)session
- didReceiveConnectionRequestFromPeer:(NSString *)peerID {//已接受連接請(qǐng)求的代理方法
- actingAsHost = NO;//設(shè)為客戶端
- }
- - (void)session:(GKSession *)session peer:(NSString *)peerID
- didChangeState:(GKPeerConnectionState)state {//狀態(tài)改變時(shí)觸發(fā)的代理方法
- switch (state)
- {
- case GKPeerStateConnected:
- [session setDataReceiveHandler: self withContext: nil];
- opponentID = peerID;//改變opponentID的值
- actingAsHost ? [self hostGame] : [self joinGame];//
- break;
- }
- }
- - (void) receiveData: (NSData*) data fromPeer: (NSString*) peerID
- inSession: (GKSession*) session context: (void*) context {//接受數(shù)據(jù)時(shí)的代理操作
- NSKeyedUnarchiver *unarchiver =
- [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
- if ([unarchiver containsValueForKey:TAP_COUNT_KEY]) {
- opponentTapCount = [unarchiver decodeIntForKey:TAP_COUNT_KEY];
- [self updateTapCountLabels];
- }
- if ([unarchiver containsValueForKey:END_GAME_KEY]) {
- [self endGame];
- }
- if ([unarchiver containsValueForKey:START_GAME_KEY]) {
- [self joinGame];
- }
- [unarchiver release];
- }
- //以上是代理方法
- -(void) showEndGameAlert {
- BOOL playerWins = playerTapCount > opponentTapCount;
- UIAlertView *endGameAlert = [[UIAlertView alloc]
- initWithTitle: playerWins ? @"Victory!" : @"Defeat!"
- message: playerWins ? @"Your thumbs have emerged supreme!":
- @"Your thumbs have been laid low"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [endGameAlert show];
- [endGameAlert release];
- }
- -(void) endGame {
- opponentID = nil;
- startQuitButton.text = @"Find";
- [gkSession disconnectFromAllPeers];
- [self showEndGameAlert];
- }
- /*
- // 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 {
- [super viewDidLoad];
- }
- */
- /*
- // 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 {
- [opponentID release];
- [playerTapCountLabel release];
- [opponentTapCountLabel release];
- [startQuitButton release];
- [gkSession release];
- [super dealloc];
- }
小結(jié):iPhone開(kāi)發(fā)之GameKit藍(lán)牙實(shí)例講解的內(nèi)容介紹完 ,希望通過(guò)本文的學(xué)習(xí)能對(duì)你有所幫助!