首页 文章

游戏中心多人游戏代码

提问于
浏览
0

根据文档,我正在使用:

- (void) match:(GKMatch*) match player:(NSString*) playerID didChangeState:(GKPlayerConnectionState) state;

进行初始游戏谈判 . 我在以下范围内这样做:

if (matchStarted_ == NO && [match expectedPlayerCount] == 0) { ... }

我需要决定哪个设备负责设置游戏 . 我这样做是通过对 match.playerIDs NSArray实例进行排序,并将 [GKLocalPlayer localPlayer].playerID NSString与排序数组索引0处的playerID NSString进行比较 . 该玩家创建游戏,将数据发送给所有玩家 .

但是,即使expectedPlayerCount为0,playerIDs数组此时也没有条目,这给了我一个数组溢出 . 这是为什么?那么我该怎么做才能做出明确定义的玩家选择以产生游戏?

2 回答

  • 3

    对于决策代码,请查看Apple提供的GKTank示例 - 它们获取设备ID的哈希值,将其发送给其他客户端,并且较低的数字是“主机” . 这似乎是一个非常可靠的决定方式 .

  • 1

    这是做这件事的示例代码

    NSString *uid = [[UIDevice currentDevice] uniqueIdentifier];
    CoinTossID = [uid hash];
    

    现在在委托函数中

    - (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID
        {
            NSMutableArray *ReceivedArray = [[NSMutableArray alloc] init];
            ReceivedArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            int flag = [[ReceivedArray objectAtIndex:0] intValue];
            [ReceivedArray removeObjectAtIndex:0];
    
            int CoinValue = [ReceivedCoinTossID intValue];
            if(CoinValue > CoinTossID)
            {
               isPlayer1 = YES;
            }
            else
            {
                  isPlayer1 = NO;
            }
        }
    

相关问题