Files
peko-ios/YuMi/Modules/YMRoom/View/LittleGame/View/XPRoomLittleGameContainerView.m
2024-03-20 20:43:06 +08:00

868 lines
32 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// XPRoomLittleGameContainerView.m
// xplan-ios
//
// Created by 冯硕 on 2022/2/14.
//
#import "XPRoomLittleGameContainerView.h"
///Third
#import <Masonry/Masonry.h>
#import <SudMGP/SudMGP.h>
#import <NIMSDK/NIMSDK.h>
///Tool
#import "Api+LittleGame.h"
#import "AccountInfoStorage.h"
#import "SudCommon.h"
#import "SudGameConfig.h"
///Model
#import "RoomInfoModel.h"
#import "MicroQueueModel.h"
#import "UserInfoModel.h"
#import "MicroExtModel.h"
#import "AttachmentModel.h"
#import "XPKickUserModel.h"
#import "GuildSuperAdminInfoModel.h"
///P
#import <SudMGP/ISudFSMMG.h>
#import <SudMGP/ISudFSTAPP.h>
#import <SudMGP/SudMGP.h>
#import <SudMGP/ISudFSMStateHandle.h>
#import <SudMGP/SudMGP-umbrella.h>
@interface XPRoomLittleGameContainerView ()<RoomGuestDelegate,ISudFSMMG>
///当前小游戏ID
@property (nonatomic, assign) int64_t currentmgId;
///小游戏code
@property (nonatomic, copy) NSString *code;
///
@property (nonatomic,weak) id<RoomHostDelegate> hostDelegate;
@property (nonatomic, strong) id<ISudFSTAPP> fsmAPP2MG;
/// 你画我猜专用,游戏中选中的关键词,会回调出来,通过 DrawSomethingKeyWord 进行保存。
@property (nonatomic, copy) NSString * DrawSomethingKeyWord;
/// 你画我猜,进入猜词环节,用来公屏识别关键字的状态标识
@property (nonatomic, assign) BOOL keyWordHiting;
///游戏状态
@property (nonatomic, assign) LittleGamePlayStatus sudGameStatus;
@end
@implementation XPRoomLittleGameContainerView
- (instancetype)initWithDelegate:(id<RoomHostDelegate>)delegate
{
self = [super init];
if (self) {
self.hostDelegate = delegate;
}
return self;
}
#pragma mark - Private Method
- (void)updateSudGame {
RoomInfoModel * roomInfo = self.hostDelegate.getRoomInfo;
if (roomInfo.type == RoomType_MiniGame) {
if (self.currentmgId == 0) {//第一次加载游戏
self.currentmgId = roomInfo.mgId;
if (self.currentmgId != 0) {//房间信息已加载
NSLog(@"initLittleGame---%lld", self.currentmgId);
[self initLittleGame];
}
} else {
if (self.currentmgId != roomInfo.mgId) {
//切换游戏玩法
self.currentmgId = roomInfo.mgId;
NSLog(@"updateLittleGame---%lld", self.currentmgId);
if (self.currentmgId != 0) {
[self.fsmAPP2MG destroyMG];
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
[self gameSetUp];
}
}
}
}
}
- (void)initLittleGame {
[Api getSudGameCode:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code == 200) {
NSString * gameCode = data.data[@"code"];
self.code = gameCode;
[self gameSetUp];
} else {
[XNDJTDDLoadingTool showErrorWithMessage:msg];
}
} uid:[AccountInfoStorage instance].getUid];
}
- (void)gameSetUp {
NSLog(@"小游戏的版本号是:%@", [SudMGP getVersion]);
BOOL isTestEnv = NO;
#ifdef DEBUG
isTestEnv = YES;
#else
isTestEnv = NO;
#endif
[SudMGP initSDK:KeyWithType(KeyType_SudGameAppID) appKey:KeyWithType(KeyType_SudGameAppKey) isTestEnv:isTestEnv listener:^(int retCode, const NSString *retMsg) {
if (retCode == 0) {
if (!self.currentmgId) {
return;
}
NSString * userId = [AccountInfoStorage instance].getUid;
NSString * roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.uid];
NSLog(@"用户ID%@房间ID%@, 游戏ID%lld, code:%@", userId, roomId, self.currentmgId, self.code);
//
NSString *language = [NSLocale preferredLanguages].firstObject;
if ([language hasPrefix:@"zh"]) {
if ([language rangeOfString:@"Hans"].location != NSNotFound) {
language = @"zh-Hans"; // 简体中文
} else {
language = @"zh-Hant"; // 繁體中文
}
}else{
language = @"zh-Hant"; // 繁體中文
}
self.fsmAPP2MG = [SudMGP loadMG:userId roomId:roomId code:self.code mgId:self.currentmgId language:[language isEqualToString:@"zh-Hant"]? @"zh-TW" : @"zh-CN" fsmMG:self rootView:self];
} else {
/// 初始化失败, 可根据业务重试
NSLog(@"ISudFSMMG:initGameSDKWithAppID:初始化sdk失败 :%@",retMsg);
}
}];
}
//判断是否在麦上
- (BOOL)isOnMicro:(NSInteger)uid{
NSArray *chatRoomMicSequences = [self.hostDelegate.getMicroQueue allValues] ;
if (chatRoomMicSequences != nil && chatRoomMicSequences.count > 0) {
for (int i = 0; i < chatRoomMicSequences.count; i ++) {
MicroQueueModel *chatRoomMicSequence = chatRoomMicSequences[i];
if (chatRoomMicSequence.userInfo.uid == uid) {
return YES;
}
}
}
return NO;
}
- (NSString *)findFreePosition{
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
if (micQueue != nil && micQueue.allKeys.count > 0) {
NSArray *keys = [micQueue allKeys];
if (keys.count > 0) {
///重新排序,按照升序
NSArray *resultArr = [keys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1 compare:obj2];
}];
for (NSString *key in resultArr) {
UserInfoModel *userInfo = [[micQueue objectForKey:key] userInfo];
if ( !userInfo) {
return key;
}
}
}
}
return nil;
}
//通过uid判断麦位
- (NSString *)findThePositionByUid:(NSInteger)uid{
if (uid > 0) {
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
NSArray *keys = [micQueue allKeys];
if (keys.count > 0) {
for (NSString *key in keys) {
UserInfoModel *userInfo = [[micQueue objectForKey:key] userInfo];
if (userInfo.uid == uid) {
return key;
}
}
}
}
return nil;
}
//上麦以加入游戏
- (void)upMicToJoinGame {
NSString *position = [self findFreePosition];
if (position.length > 0) {
NSString * userId = [AccountInfoStorage instance].getUid;
UserInfoModel * userInfo = self.hostDelegate.getUserInfo;
//清空该uid之前在队列中的信息
if ([self isOnMicro:userId.integerValue]) {
if (position) {
NSString *findOldPosition = [self findThePositionByUid:userInfo.uid];
NIMChatroomQueueRemoveRequest *request = [[NIMChatroomQueueRemoveRequest alloc]init];
request.key = findOldPosition;
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
if (findOldPosition) {
[[NIMSDK sharedSDK].chatroomManager removeChatroomQueueObject:request completion:^(NSError * _Nullable error, NSDictionary<NSString *,NSString *> * _Nullable element) {
if (error == nil) {
NIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc]init];
request.key = position;
request.value = [[self userInfoToQueueExt:userInfo] toJSONString];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.transient = YES;
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request completion:^(NSError * _Nullable error) {
[self notifySelfInState:YES seatIndex:-1];
}];
}
}];
}
}
}else{
NIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc]init];
request.key = position;
request.value = [[self userInfoToQueueExt:userInfo] toJSONString];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.transient = YES;
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request completion:^(NSError * _Nullable error) {
[self notifySelfInState:YES seatIndex:-1];
}];
}
}
}
- (void)updateMicInfoWithGameStatus:(LittleGamePlayStatus)status {
NSString * position = [self findThePositionByUid:[AccountInfoStorage instance].getUid.integerValue];
if (position != nil) {
UserInfoModel * userInfo = self.hostDelegate.getUserInfo;
userInfo.gameStatus = status;
NIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc]init];
request.key = position;
request.value = [[self userInfoToQueueExt:userInfo] toJSONString];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.transient = YES;
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request completion:^(NSError * _Nullable error) {
}];
}
}
/**
* 麦位更新扩展字段。
*/
- (NSDictionary *)userInfoToQueueExt:(UserInfoModel *)userInfo {
MicroExtModel * extModel = [[MicroExtModel alloc] init];
extModel.gender = userInfo.gender;
extModel.avatar = userInfo.avatar;
extModel.uid = userInfo.uid;
extModel.nick = userInfo.nick;
extModel.gameStatus = userInfo.gameStatus;
extModel.headWearUrl = userInfo.headwearEffect.length > 0 ? userInfo.headwearEffect : userInfo.headwearPic;
extModel.preventKick = userInfo.userVipInfoVO.preventKick;
extModel.enterHide = userInfo.userVipInfoVO.enterHide;
return [extModel model2dictionary];
}
//自己是否在游戏中
- (BOOL)isInSudGame {
BOOL isGamePlaying = NO;
if (self.hostDelegate.getRoomInfo.type == RoomType_MiniGame) {
for (int i = -1; i<5; i++) {
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
MicroQueueModel *micSequence = [micQueue objectForKey:[NSString stringWithFormat:@"%d", i]];
if (micSequence == nil || micSequence.userInfo == nil) {
continue;
}
if (micSequence.userInfo.uid == [AccountInfoStorage instance].getUid.integerValue && micSequence.userInfo.gameStatus == LittleGamePlayStatus_Plying) {
isGamePlaying = YES;
break;
}
}
}
return isGamePlaying;
}
//游戏状态
- (LittleGamePlayStatus)getCurrentUserSudGameStatus {
LittleGamePlayStatus gameStatus = LittleGamePlayStatus_NoIn;
for (int i = -1; i<5; i++) {
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
MicroQueueModel *micSequence = [micQueue objectForKey:[NSString stringWithFormat:@"%d", i]];
if (micSequence == nil || micSequence.userInfo == nil) {
continue;
}
if (micSequence.userInfo.uid == [AccountInfoStorage instance].getUid.integerValue) {
gameStatus = micSequence.userInfo.gameStatus;
break;
}
}
return gameStatus;
}
///下麦
- (void)onDownMic:(NSInteger)uid {
if (uid == [AccountInfoStorage instance].getUid.integerValue) {//自己下麦
[self notifyIsPlayingState:false];
[self nofityPlayerPlaying:NO];
[self notifySetReady:false];
/// 下游戏麦
[self notifySelfInState:false seatIndex:-1];
}
}
#pragma mark =======ISudFSMMG Delegate=======
/**
* 游戏日志
*/
-(void)onGameLog:(NSString*)dataJson {
NSLog(@"ISudFSMMG:onGameLog:%@", dataJson);
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
NSString * msg_string = [dic objectForKey:@"msg"];
if (!msg_string) {
return;
}
}
/**
* 游戏开始
*/
-(void)onGameStarted {
NSLog(@"ISudFSMMG:onGameStarted:游戏开始");
}
/**
* 游戏销毁
*/
-(void)onGameDestroyed {
NSLog(@"ISudFSMMG:onGameDestroyed:游戏开始");
}
/**
* Code过期
* @param dataJson {"code":"value"}
*/
-(void)onExpireCode:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson {
NSLog(@"ISudFSMMG:onExpireCode:Code过期");
// 请求业务服务器刷新令牌
[Api getSudGameCode:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code == 200) {
NSString * gameCode = data.data[@"code"];
self.code = gameCode;
[self.fsmAPP2MG updateCode:gameCode listener:^(int retCode, const NSString *retMsg, const NSString *dataJson) {
NSLog(@"ISudFSMMG:updateGameCode retCode=%@ retMsg=%@ dataJson=%@", @(retCode), retMsg, dataJson);
}];
// 回调结果
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@(0), @"ret_code", @"return form APP onExpireCode", @"ret_msg", nil];
[handle success:[SudCommon dictionaryToJson:dict]];
} else {
[XNDJTDDLoadingTool showErrorWithMessage:msg];
}
} uid:[AccountInfoStorage instance].getUid];
}
/**
* 获取游戏View信息
* @param handle 回调句柄
* @param dataJson {}
*/
-(void)onGetGameViewInfo:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson {
CGRect rect = [[UIScreen mainScreen] bounds];
CGFloat scale = [[UIScreen mainScreen] nativeScale];
CGFloat top = (kNavigationHeight+105) * scale;
CGFloat bottom;
if (iPhoneXSeries) {
bottom = (47+kSafeAreaBottomHeight+30 + 70) * scale;
} else {
bottom = (47+10+70 ) * scale;
}
CGFloat width = rect.size.width * scale;
CGFloat height = rect.size.height * scale;
NSDictionary *rectDict = [NSDictionary dictionaryWithObjectsAndKeys:@(top), @"top", @(0), @"left", @(bottom), @"bottom", @(0), @"right", nil];
NSDictionary *viewDict = [NSDictionary dictionaryWithObjectsAndKeys:@(width), @"width", @(height), @"height", nil];
NSDictionary *dataDict = [NSDictionary dictionaryWithObjectsAndKeys:@(0), @"ret_code", @"return form APP onGetGameViewInfo", @"ret_msg", viewDict, @"view_size", rectDict, @"view_game_rect", nil];
/// 回调
[handle success:[SudCommon dictionaryToJson:dataDict]];
}
/**
* 获取游戏配置
* @param handle 回调句柄
* @param dataJson {}
*/
-(void)onGetGameCfg:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"ret_code"] = @(0);
dict[@"ret_msg"] = @"return form APP onGetGameCfg";
dict[@"ui"] = @{
@"join_btn" : @{@"custom": @(YES), @"hide": @(NO)},//加入游戏
@"start_btn" : @{@"custom": @(YES), @"hide": @(NO)},//开始游戏
@"lobby_players" : @{@"custom": @(YES), @"hide": @(NO)},//游戏中坑位点击
@"level" : @{@"custom": @(YES), @"hide" : @(YES)},//段位信息
};
NSString *dataJsonRet = @"";
NSData *dataJsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
if (dataJsonData != nil) {
dataJsonRet = [[NSString alloc]initWithData:dataJsonData encoding:NSUTF8StringEncoding];
}
[handle success:dataJsonRet];
}
/**
* 游戏状态变化
* @param handle 回调句柄
* @param state 游戏状态
* @param dataJson 回调json
*/
-(void)onGameStateChange:(id<ISudFSMStateHandle>) handle state:(NSString*) state dataJson:(NSString*) dataJson {
if ([state isEqualToString:MG_COMMON_PUBLIC_MESSAGE]) {
NSLog(@"ISudFSMMG:onGameStateChange:游戏->APP:公屏消息");
} else if ([state isEqualToString:MG_COMMON_KEY_WORD_TO_HIT]) {
NSDictionary *dic = [SudCommon turnStringToDictionary:dataJson];
NSString *word = [dic objectForKey:@"word"];
NSLog(@"ISudFSMMG:onGameStateChange:游戏->APP:你画我猜关键词获取:%@",word);
/// 记录你画我猜关键字
self.DrawSomethingKeyWord = word;
if (word == (id) [NSNull null] || [word isEqualToString:@""]) {
/// 关闭公屏关键词hit状态
self.keyWordHiting = NO;
} else {
/// 开启公屏关键词hit状态
self.keyWordHiting = YES;
}
}else if ([state isEqualToString:MG_COMMON_SELF_CLICK_JOIN_BTN]) {//加入游戏按钮点击
NSDictionary *dic = [SudCommon turnStringToDictionary:dataJson];
int seatIndex = -1;
if ([dic objectForKey:@"seatIndex"]) {
seatIndex = [[dic objectForKey:@"seatIndex"] intValue];
}
if (seatIndex == -1) {
NSLog(@"来自加入按钮%d",seatIndex);
}else {
NSLog(@"来自麦位+入%d",seatIndex);
}
if ([self isOnMicro:[AccountInfoStorage instance].getUid.integerValue]) {//判断是否在麦上
[self notifySelfInState:YES seatIndex:seatIndex];
} else {
//不在麦上
[self upMicToJoinGame];
}
} else if([state isEqualToString:MG_COMMON_SELF_CLICK_START_BTN]) {//开始游戏按钮点击
[self notifyIsPlayingState:YES];
} else if ([state isEqualToString:MG_COMMON_SELF_CLICK_CANCEL_JOIN_BTN]) {
/// 取消加入游戏(退出游戏按钮点击)
[self handleSelfInExitEvent];
} else {
/// 其他状态
NSLog(@"ISudFSMMG:onGameStateChange:游戏->APP:state:%@",MG_COMMON_PUBLIC_MESSAGE);
}
}
/**
* 游戏玩家状态变化
* @param handle 回调句柄
* @param userId 用户id
* @param state 玩家状态
* @param dataJson 回调JSON
*/
-(void)onPlayerStateChange:(nullable id<ISudFSMStateHandle>) handle userId:(NSString*) userId state:(NSString*) state dataJson:(NSString*) dataJson {
NSLog(@"ISudFSMMG:onPlayerStateChange:游戏->APP:游戏玩家状态变化:userId: %@ --state: %@ --dataJson: %@", userId, state, dataJson);
/// 状态解析
NSString *dataStr = @"";
if ([state isEqualToString:MG_COMMON_PLAYER_IN]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView0");
[self handleState_MG_COMMON_PLAYER_IN_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_COMMON_PLAYER_READY]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView1");
[self handleState_MG_COMMON_PLAYER_READY_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_COMMON_PLAYER_CAPTAIN]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView2");
[self handleState_MG_COMMON_PLAYER_CAPTAIN_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_COMMON_PLAYER_PLAYING]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView3");
[self handleState_MG_COMMON_PLAYER_PLAYING_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_SELECTING]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView4");
[self handleState_MG_DG_SELECTING_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_PAINTING]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView5");
[self handleState_MG_DG_PAINTING_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_ERRORANSWER]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView6");
[self handleState_MG_DG_ERRORANSWER_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_TOTALSCORE]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView7");
[self handleState_MG_DG_TOTALSCORE_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_SCORE]) {
dataStr = YMLocalizedString(@"XPRoomLittleGameContainerView8");
[self handleState_MG_DG_SCORE_WithUserId:userId dataJson:dataJson];
}else {
NSLog(@"ISudFSMMG:onPlayerStateChange:未做解析状态:%@", MG_DG_SCORE);
}
NSLog(@"ISudFSMMG:onPlayerStateChange:dataStr:%@", dataStr);
/// 回调
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@(0), @"ret_code", @"return form APP onPlayerStateChange", @"ret_msg", nil];
[handle success:[SudCommon dictionaryToJson:dict]];
}
/// 退出游戏
- (void)handleSelfInExitEvent {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
return;
}
/// 正在游戏中,只退出游戏
if ([self getCurrentUserSudGameStatus] == LittleGamePlayStatus_Plying) {
[self notifyIsPlayingState:false];
[self nofityPlayerPlaying:NO];
[self notifySetReady:false];
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
} else if ([self getCurrentUserSudGameStatus] == LittleGamePlayStatus_Ready) { /// 非游戏状态下
/// 如果已经准备先退出准备状态
[self notifySetReady:false];
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
} else {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
}
/// 下游戏麦
[self notifySelfInState:false seatIndex:-1];
}
/// 准备游戏
- (void)handleSelfReadyEvent {
[self notifySetReady:true];
}
/// 取消准备
- (void)handleSelfCancelReadyEvent {
[self notifySetReady:false];
}
/// 开始游戏
- (void)handleGameStartEvent {
[self notifyIsPlayingState:YES];
}
#pragma mark =======APP->游戏状态处理=======
/// 状态通知app to mg
/// @param state 状态名称
/// @param dataJson 需传递的json
- (void)notifyStateChange:(NSString *) state dataJson:(NSString*) dataJson {
[self.fsmAPP2MG notifyStateChange:state dataJson:dataJson listener:^(int retCode, const NSString *retMsg, const NSString *dataJson) {
NSLog(@"ISudFSMMG:notifyStateChange:retCode=%@ retMsg=%@ dataJson=%@", @(retCode), retMsg, dataJson);
RoomInfoModel * roomInfo = self.hostDelegate.getRoomInfo;
if (retCode == 0 && [state isEqualToString:APP_COMMON_SELF_PLAYING]) {//开始游戏
//上报游戏开始
NSString *mgid = [NSString stringWithFormat:@"%lld", self.currentmgId];
if (mgid.length <= 0) {
return;
}
[Api startGameCheck:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code != 200) {
[XNDJTDDLoadingTool showErrorWithMessage:msg];
}
} roomUid:[NSString stringWithFormat:@"%ld", roomInfo.uid] mgId:mgid];
} else if (retCode == 0 && [state isEqualToString:APP_COMMON_SELF_END]) {//结束游戏
}
}];
}
/// 加入,退出游戏
/// @param isIn YES:加入 NO:退出
- (void)notifySelfInState:(BOOL)isIn uid:(NSInteger)uid {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isIn), @"isIn", @(1), @"teamId", nil];
[self notifyStateChange:APP_COMMON_SELF_IN dataJson:[SudCommon dictionaryToJson:dic]];
}
/// 加入,退出游戏
/// @param isIn YES:加入 NO:退出
- (void)notifySelfInState:(BOOL)isIn seatIndex:(int)seatIndex {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(seatIndex), @"seatIndex", @(isIn), @"isIn", @(1), @"teamId", nil];
[self notifyStateChange:APP_COMMON_SELF_IN dataJson:[SudCommon dictionaryToJson:dic]];
}
/// 踢出用户
/// @param userId 踢出用户id
- (void)notifyKickStateWithUserId:(NSString *)userId {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:userId, @"kickedUID", nil];
[self notifyStateChange:APP_COMMON_SELF_KICK dataJson:[SudCommon dictionaryToJson:dic]];
}
/// 设置用户为队长
/// @param userId 被设置用户id
- (void)notifySetCaptainStateWithUserId:(NSString *)userId {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:userId, @"curCaptainUID", nil];
[self notifyStateChange:APP_COMMON_SELF_CAPTAIN dataJson:[SudCommon dictionaryToJson:dic]];
}
/// 命中 关键词状态 (你画我猜)
- (void)notifyChangeTextHitState:(NSString *)keyWord {
if([keyWord isKindOfClass:[NSNull class]])return;
if (keyWord.length && [keyWord containsString:self.DrawSomethingKeyWord]) {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(true), @"isHit", self.DrawSomethingKeyWord, @"keyWord", self.DrawSomethingKeyWord, @"text", nil];
[self notifyStateChange:APP_COMMON_SELF_TEXT_HIT dataJson:[SudCommon dictionaryToJson:dic]];
}
}
/// 是否设置为准备状态
- (void)notifySetReady:(BOOL)isReady {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isReady), @"isReady", nil];
[self notifyStateChange:APP_COMMON_SELF_READY dataJson:[SudCommon dictionaryToJson:dic]];
}
/// 停止游戏状态设置
- (void)notifySetEnd {
[self notifyStateChange:APP_COMMON_SELF_END dataJson:[SudCommon dictionaryToJson:@{}]];
}
/// 游戏中状态设置
- (void)notifyIsPlayingState:(BOOL)isPlaying {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isPlaying), @"isPlaying", nil];
[self notifyStateChange:APP_COMMON_SELF_PLAYING dataJson:[SudCommon dictionaryToJson:dic]];
}
///游戏中退出游戏
- (void)nofityPlayerPlaying:(BOOL)isPlaying {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isPlaying), @"isPlaying", nil];
[self notifyStateChange:MG_COMMON_PLAYER_PLAYING dataJson:[SudCommon dictionaryToJson:dic]];
}
#pragma mark =======游戏->APP状态处理=======
- (void)handleState_MG_COMMON_PLAYER_IN_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
/// 加入状态YES加入NO退出
BOOL isIn = NO;
if (dic) {
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isIn = [[dic objectForKey:@"isIn"] boolValue];
}
if ([userId isEqualToString:[AccountInfoStorage instance].getUid]) {//是当前用户
if (isIn) {//加入了游戏
//判断是否在麦上
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_IsIn];
} else {//不在麦上
[self upMicToJoinGame];
}
//判断是否为房主,房主需要设为队长
if (self.hostDelegate.getRoomInfo.uid == userId.integerValue) {
[self notifySetCaptainStateWithUserId:userId];
}
self.sudGameStatus = LittleGamePlayStatus_IsIn;
}else {//退出了游戏
//判断是否在麦上
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
}
self.sudGameStatus = LittleGamePlayStatus_NoIn;
}
} else {//退出游戏
if (self.sudGameStatus == LittleGamePlayStatus_Plying) {//游戏进行中,用户退出
///自己是公会超管
BOOL meIsSuperAdmin = NO;
for (GuildSuperAdminInfoModel *managerInfo in self.hostDelegate.getRoomSuperAdminList) {
if ([managerInfo.uid isEqualToString:[AccountInfoStorage instance].getUid]) {
meIsSuperAdmin = YES;
break;
}
}
NIMChatroomMembersByIdsRequest *request = [[NIMChatroomMembersByIdsRequest alloc]init];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.userIds = @[[AccountInfoStorage instance].getUid];
[[NIMSDK sharedSDK].chatroomManager fetchChatroomMembersByIds:request completion:^(NSError * _Nullable error, NSArray<NIMChatroomMember *> * _Nullable members) {
if (error == nil) {
NIMChatroomMember *member = members.firstObject;
if (member.type == NIMChatroomMemberTypeManager || member.type == NIMChatroomMemberTypeCreator || meIsSuperAdmin) {
NIMChatroomMembersByIdsRequest *request = [[NIMChatroomMembersByIdsRequest alloc]init];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.userIds = @[userId];
[[NIMSDK sharedSDK].chatroomManager fetchChatroomMembersByIds:request completion:^(NSError * _Nullable error, NSArray<NIMChatroomMember *> * _Nullable members) {
if (error == nil) {
NIMChatroomMember *member = members.firstObject;
[XNDJTDDLoadingTool showErrorWithMessage:[NSString stringWithFormat:YMLocalizedString(@"XPRoomLittleGameContainerView9"), member.roomNickname]];
}
}];
}
}
}];
}
}
}
- (void)handleState_MG_COMMON_PLAYER_READY_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// 玩家是否准备,YES:已准备NO:未准备
BOOL isReady = NO;
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
if (dic) {
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isReady = [[dic objectForKey:@"isReady"] boolValue];
}
if ([userId isEqualToString:[AccountInfoStorage instance].getUid]) {
if (isReady) {
//判断是否在麦上
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_Ready];
}
self.sudGameStatus = LittleGamePlayStatus_Ready;
}else {
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_IsIn];
}
self.sudGameStatus = LittleGamePlayStatus_IsIn;
}
}
}
- (void)handleState_MG_COMMON_PLAYER_CAPTAIN_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// 是否是队长YES是队长 NO不是队长
BOOL isCaptain = NO;
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
if (dic) {
/// 错误处理
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isCaptain = [[dic objectForKey:@"isCaptain"] boolValue];
}
}
- (void)handleState_MG_COMMON_PLAYER_PLAYING_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// 是否正在游戏中
BOOL isPlaying = NO;
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
if (dic) {
/// 错误处理
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isPlaying = [[dic objectForKey:@"isPlaying"] boolValue];
}
if ([userId isEqualToString:[AccountInfoStorage instance].getUid]) {
if (isPlaying) {
//判断是否在麦上
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_Plying];
}
if (self.delegate && [self.delegate respondsToSelector:@selector(hiddenSudGamePostionView)]) {
[self.delegate hiddenSudGamePostionView];
}
self.sudGameStatus = LittleGamePlayStatus_Plying;
}else {
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_IsIn];
}
self.sudGameStatus = LittleGamePlayStatus_IsIn;
}
}
}
- (void)handleState_MG_DG_SELECTING_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
NSLog(@"handleState_MG_DG_SELECTING_WithUserId%@",dataJson);
}
- (void)handleState_MG_DG_PAINTING_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
NSLog(@"handleState_MG_DG_PAINTING_WithUserId%@",dataJson);
/// 设置麦位状态为作画中
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
bool isPainting = NO;
if (dic) {
isPainting = [dic[@"isPainting"] boolValue];
}
}
- (void)handleState_MG_DG_ERRORANSWER_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// 错误答案
NSLog(@"handleState_MG_DG_ERRORANSWER_WithUserId%@",dataJson);
}
- (void)handleState_MG_DG_TOTALSCORE_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// 总积分
NSLog(@"handleState_MG_DG_TOTALSCORE_WithUserId%@",dataJson);
}
- (void)handleState_MG_DG_SCORE_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// 本次积分
NSLog(@"handleState_MG_DG_SCORE_WithUserId%@",dataJson);
}
/// 销毁MG
- (void)destroyMG {
if (self.hostDelegate.getRoomInfo.type == RoomType_MiniGame) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.fsmAPP2MG destroyMG];
});
}
}
#pragma mark - RoomGuestDelegate
- (void)onRoomEntered {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
self.hidden = YES;
return;
} else {
self.hidden = NO;
}
[self updateSudGame];
}
- (void)onRoomUpdate {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
self.hidden = YES;
[self.fsmAPP2MG destroyMG];
} else {
self.hidden = NO;
}
[self updateSudGame];
}
#pragma mark - RoomGuestDelegate
- (void)handleNIMCustomMessage:(NIMMessage *)message {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
return;
}
NIMCustomObject *obj = (NIMCustomObject *)message.messageObject;
if (obj.attachment != nil && [obj.attachment isKindOfClass:[AttachmentModel class]]) {
AttachmentModel *attachment = (AttachmentModel *)obj.attachment;
if (attachment.first == CustomMessageType_Kick_User) {
XPKickUserModel * kickModel = [XPKickUserModel modelWithJSON:attachment.data];
[self onDownMic:kickModel.uid];
} else if(attachment.first == CustomMessageType_Queue && attachment.second == Custom_Message_Sub_Queue_Kick) {
XPKickUserModel * kickModel = [XPKickUserModel modelWithJSON:attachment.data];
[self onDownMic:kickModel.uid];
}
}
}
- (void)handleNIMNotificationMessage:(NIMMessage *)message {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {return;}
NIMNotificationObject *notiMsg = (NIMNotificationObject *)message.messageObject;
NIMChatroomNotificationContent *content = (NIMChatroomNotificationContent *)notiMsg.content;
switch (content.eventType) {
case NIMChatroomEventTypeQueueChange: // 麦序上下麦
{
NSDictionary* data = (NSDictionary *)content.ext;
UserInfoModel* userInfo = [UserInfoModel modelWithJSON:[data objectForKey:NIMChatroomEventInfoQueueChangeItemValueKey]];
NSInteger changeType = [data[NIMChatroomEventInfoQueueChangeTypeKey] integerValue];
if (changeType != 1) {
[self onDownMic:userInfo.uid];
}
}
break;
default:
break;
}
}
- (void)handleNIMTextMessage:(NIMMessage *)message {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {return;}
if (message.from.integerValue == [AccountInfoStorage instance].getUid.integerValue && [self isInSudGame]) {
[self notifyChangeTextHitState:message.text];
}
}
@end