iPhone开发之GameKit蓝牙实例讲解

移动开发 iOS
iPhone开发应用中关于GameKit蓝牙实例讲解是本文要介绍的内容,主要是来了解并学习GameKit蓝牙实例,具体内容来看本文详解。

iPhone开发应用中关于GameKit蓝牙实例讲解是本文要介绍的内容,主要是来了解并学习GameKit蓝牙实例。介绍一下这个实例实现的是两个带有蓝牙设备的touch之间的一个小游戏,在界面上有个可以响应事件的UIView(之前说过)可以点击,然后看谁新达到WINNING_TAP_COUNT (游戏中一常量可以自己设置)谁先达到谁就赢了,然后通知对方。还要引入GameKit.framework框架
头文件BlueToothViewController.h:

  1. //  
  2. //  
  3. // BlueToothViewController.h  
  4. // BlueTooth  
  5. //  
  6. // Created by mingchun liu on 09-11-24.  
  7. // Copyright sdie 2009. All rights reserved.  
  8. //  
  9.  
  10. #import <UIKit/UIKit.h> 
  11. #import <GameKit/GameKit.h> 
  12.  
  13. #define START_GAME_KEY @"startgame"  
  14. #define END_GAME_KEY @"endgame"  
  15. #define TAP_COUNT_KEY @"taps"  
  16. #define WINNING_TAP_COUNT 50  
  17.  
  18. #define AMIPHD_P2P_SESSION_ID @"amiphdp2p2"//这个是蓝牙协议  
  19.  
  20. @interface BlueToothViewController : UIViewController<GKPeerPickerControllerDelegate,GKSessionDelegate>{  
  21.         BOOL actingAsHost;//是否提供服务,客户端还是服务器端  
  22.         int playerTapCount;//记录玩家点击次数  
  23.         int opponentTapCount;//对方点击次数  
  24.         IBOutlet UILabel *playerTapCountLabel;//显示玩家点击次数  
  25.         IBOutlet UILabel *opponentTapCountLabel;//显示对手点击次数  
  26.         NSString *opponentID;//对方标识符  
  27.         GKSession *gkSession;  
  28.           
  29.         IBOutlet UILabel *startQuitButton;//开始退出按钮  
  30. }  
  31.  
  32. @property BOOL actingAsHost;  
  33. @property int playerTapCount;  
  34. @property int opponentTapCount;  
  35. @property (nonatomic,retain) GKSession *gkSession;  
  36.  
  37. @property (nonatomic,retain) NSString *opponentID;  
  38.  
  39. @property (nonatomic,retain)UILabel *playerTapCountLabel;  
  40. @property (nonatomic,retain)UILabel *opponentTapCountLabel;  
  41.  
  42. @property (nonatomic,retain)UILabel *startQuitButton;  
  43.  
  44. -(IBAction) handleStartQuitTapped;//处理开始退出操作  
  45. -(IBAction) handleTapViewTapped;//处理点击UIView的操作  
  46. -(void) updateTapCountLabels;//更新显示  
  47. -(void) initGame;//初始化游戏  
  48. -(void) hostGame;  
  49. -(void) joinGame;//加入游戏  
  50. -(void) endGame;//结束游戏  
  51. -(void) showEndGameAlert;//弹出结束游戏对话框  
  52. @end  
  53.  
  54. #import "BlueToothViewController.h"  
  55.  
  56. @implementation BlueToothViewController  
  57.  
  58. @synthesize actingAsHost;  
  59. @synthesize playerTapCount;  
  60. @synthesize opponentID;  
  61. @synthesize playerTapCountLabel;  
  62. @synthesize opponentTapCountLabel;  
  63.  
  64. @synthesize startQuitButton;  
  65. @synthesize gkSession;  
  66. @synthesize opponentTapCount;  
  67.  
  68. -(IBAction) handleStartQuitTapped {//建立链接操作,弹出链接窗口显示在线  
  69.         if (! opponentID) {//如果对手ID为空就建立服务端提供服务  
  70.                 actingAsHost = YES;  
  71.                 GKPeerPickerController *peerPickerController =[[GKPeerPickerController alloc] init];  
  72.                 peerPickerController.delegate = self;  
  73.                 peerPickerController.connectionTypesMask =  
  74.                 GKPeerPickerConnectionTypeNearby;  
  75.                 [peerPickerController show];  
  76.         }  
  77. }  
  78. -(IBAction) handleTapViewTapped {//点击操作  
  79.         playerTapCount++;  
  80.         [self updateTapCountLabels];  
  81.         // did we just win?  
  82.         BOOL playerWins = playerTapCount >= WINNING_TAP_COUNT;//当点击达到一定次数时  
  83.         // send tap count to peer  
  84.         NSMutableData *message = [[NSMutableData alloc] init];//传的数据类型为nsdata类型的  
  85.         NSKeyedArchiver *archiver =  
  86.         [[NSKeyedArchiver alloc] initForWritingWithMutableData:message];  
  87.         [archiver encodeInt:playerTapCount forKey: TAP_COUNT_KEY];  
  88.         if (playerWins)  
  89.                 [archiver encodeBool:YES forKey:END_GAME_KEY];  
  90.         [archiver finishEncoding];//打包传数据  
  91.         GKSendDataMode sendMode =  
  92.         playerWins ? GKSendDataReliable : GKSendDataUnreliable;//判断用可靠的链接还是不可靠的链接  
  93.         [gkSession sendDataToAllPeers: message withDataMode:sendMode error:NULL];//发送数据  
  94.         [archiver release];  
  95.         [message release];  
  96.         // also end game locally  
  97.         if (playerWins)  
  98.                 [self endGame];  
  99. }  
  100.  
  101. -(void) updateTapCountLabels {  
  102.         playerTapCountLabel.text =  
  103.         [NSString stringWithFormat:@"%d", playerTapCount];  
  104.         opponentTapCountLabel.text =  
  105.         [NSString stringWithFormat:@"%d", opponentTapCount];  
  106. }  
  107. -(void) initGame {  
  108.         playerTapCount = 0;  
  109.         opponentTapCount = 0;  
  110. }  
  111. -(void) hostGame {  
  112.         [self initGame];  
  113.         NSMutableData *message = [[NSMutableData alloc] init];  
  114.         NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]  
  115.                                                                  initForWritingWithMutableData:message];  
  116.         [archiver encodeBool:YES forKey:START_GAME_KEY];  
  117.         [archiver finishEncoding];  
  118.         NSError *sendErr = nil;  
  119.         [gkSession sendDataToAllPeers: message  
  120.                                          withDataMode:GKSendDataReliable error:&sendErr];  
  121.         if (sendErr)  
  122.                 NSLog (@"send greeting failed: %@", sendErr);  
  123.         // change state of startQuitButton  
  124.         startQuitButton.text = @"Quit";  
  125.         [message release];  
  126.         [archiver release];  
  127.         [self updateTapCountLabels];  
  128. }  
  129. -(void) joinGame {  
  130.         [self initGame];  
  131.         startQuitButton.text = @"Quit";  
  132.         [self updateTapCountLabels];  
  133. }  
  134.  
  135. //一下是代理方法  
  136.  
  137. -(GKSession *) peerPickerController: (GKPeerPickerController*) controller  
  138.                   sessionForConnectionType: (GKPeerPickerConnectionType) type {  
  139.         if (!gkSession) {//如果没有链接时建立连接  
  140.                 gkSession = [[GKSession alloc]  
  141.                                          initWithSessionID:AMIPHD_P2P_SESSION_ID//根据此值判断用的是什么链接  
  142.                                          displayName:nil//在线用户名  
  143.                                          sessionMode:GKSessionModePeer];  
  144.                 gkSession.delegate = self;  
  145.         }  
  146.         return gkSession;  
  147. }  
  148.  
  149. - (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session  
  150. {//当picker接收到数据后将其释放掉,否则进入不了界面  
  151.         [picker dismiss];  
  152.         picker.delegate = nil;  
  153.         [picker autorelease];  
  154. }  
  155. - (void)session:(GKSession *)session  
  156. didReceiveConnectionRequestFromPeer:(NSString *)peerID {//已接受连接请求的代理方法  
  157.         actingAsHost = NO;//设为客户端  
  158. }  
  159.  
  160. - (void)session:(GKSession *)session peer:(NSString *)peerID  
  161. didChangeState:(GKPeerConnectionState)state {//状态改变时触发的代理方法  
  162.         switch (state)  
  163.         {  
  164.                 case GKPeerStateConnected:  
  165.                         [session setDataReceiveHandler: self withContext: nil];  
  166.                         opponentID = peerID;//改变opponentID的值  
  167.                         actingAsHost ? [self hostGame] : [self joinGame];//  
  168.                         break;  
  169.         }  
  170. }  
  171.  
  172. - (void) receiveData: (NSData*) data fromPeer: (NSString*) peerID  
  173.                    inSession: (GKSession*) session context: (void*) context {//接受数据时的代理操作  
  174.         NSKeyedUnarchiver *unarchiver =  
  175.         [[NSKeyedUnarchiver alloc] initForReadingWithData:data];  
  176.         if ([unarchiver containsValueForKey:TAP_COUNT_KEY]) {  
  177.                 opponentTapCount = [unarchiver decodeIntForKey:TAP_COUNT_KEY];  
  178.                 [self updateTapCountLabels];  
  179.         }  
  180.         if ([unarchiver containsValueForKey:END_GAME_KEY]) {  
  181.                 [self endGame];  
  182.         }  
  183.         if ([unarchiver containsValueForKey:START_GAME_KEY]) {  
  184.                 [self joinGame];  
  185.         }  
  186.         [unarchiver release];  
  187. }  
  188. //以上是代理方法  
  189.  
  190. -(void) showEndGameAlert {  
  191.         BOOL playerWins = playerTapCount > opponentTapCount;  
  192.         UIAlertView *endGameAlert = [[UIAlertView alloc]  
  193.                                                                  initWithTitle: playerWins ? @"Victory!" : @"Defeat!"  
  194.                                                                  message: playerWins ? @"Your thumbs have emerged supreme!":  
  195.                                                                  @"Your thumbs have been laid low"  
  196.                                                                  delegate:nil  
  197.                                                                  cancelButtonTitle:@"OK"  
  198.                                                                  otherButtonTitles:nil];  
  199.         [endGameAlert show];  
  200.         [endGameAlert release];  
  201. }  
  202. -(void) endGame {  
  203.         opponentID = nil;  
  204.         startQuitButton.text = @"Find";  
  205.         [gkSession disconnectFromAllPeers];  
  206.         [self showEndGameAlert];  
  207. }  
  208.  
  209. /*  
  210. // The designated initializer. Override to perform setup that is required before the view is loaded.  
  211. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {  
  212.     if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {  
  213.         // Custom initialization  
  214.     }  
  215.     return self;  
  216. }  
  217. */  
  218.  
  219. /*  
  220. // Implement loadView to create a view hierarchy programmatically, without using a nib.  
  221. - (void)loadView {  
  222. }  
  223. */  
  224.  
  225. /*  
  226. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  227. - (void)viewDidLoad {  
  228.     [super viewDidLoad];  
  229. }  
  230. */  
  231.  
  232. /*  
  233. // Override to allow orientations other than the default portrait orientation.  
  234. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {  
  235.     // Return YES for supported orientations  
  236.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
  237. }  
  238. */  
  239.  
  240. - (void)didReceiveMemoryWarning {  
  241.         // Releases the view if it doesn't have a superview.  
  242.     [super didReceiveMemoryWarning];  
  243.           
  244.         // Release any cached data, images, etc that aren't in use.  
  245. }  
  246.  
  247. - (void)viewDidUnload {  
  248.         // Release any retained subviews of the main view.  
  249.         // e.g. self.myOutlet = nil;  
  250. }  
  251.  
  252. - (void)dealloc {  
  253.         [opponentID release];  
  254.         [playerTapCountLabel release];  
  255.         [opponentTapCountLabel release];  
  256.  
  257.  
  258.         [startQuitButton release];  
  259.         [gkSession release];  
  260.     [super dealloc];  

小结:iPhone开发GameKit蓝牙实例讲解的内容介绍完 ,希望通过本文的学习能对你有所帮助!

责任编辑:zhaolei 来源: aisidachina
相关推荐

2011-07-06 16:15:46

iPhone 图片

2011-08-03 16:01:24

iPhone应用开发 自动登陆

2011-07-25 18:02:51

iPhone LibFetion 移植

2013-05-21 09:56:15

2011-08-08 16:56:44

iPhone 字符处理 视图

2011-07-29 13:27:48

iPhone 开发 Nib

2011-08-01 18:27:58

iPhone开发 UISearchBa

2011-08-10 10:10:21

iPhoneUIPopoverCo

2011-08-08 15:56:18

iPhone 震动 NSUserDefa

2011-07-27 11:19:33

iPhone UITableVie

2011-07-28 10:11:54

iPhone开发 备忘

2011-07-07 16:42:38

iPhone Sqlite3 数据库

2011-08-22 15:15:49

iPhone开发NSMutableAr排序

2011-08-08 13:57:19

iPhone开发 打包 DEB

2011-08-11 10:03:43

iPhonecocoaNSRunLoop

2013-07-23 07:34:54

iOS开发学习适配iphone5

2011-08-09 11:36:41

iPhoneUIPickerVieDEMO

2011-07-26 09:58:24

2011-07-28 14:19:12

iPhone 网络编程 聊天程序

2011-08-16 18:42:42

iPhone开发Release
点赞
收藏

51CTO技术栈公众号