Commit f34df367 authored by limingzhe's avatar limingzhe

fix: key

parent d40f2950
{"ver":"1.1.2","uuid":"c35bb2f6-f24a-4850-ae44-643f2fdc7541","isBundle":false,"bundleName":"","priority":1,"compressionType":{},"optimizeHotUpdate":{},"inlineSpriteFrames":{},"isRemoteBundle":{"ios":false,"android":false},"subMetas":{}} {
\ No newline at end of file "ver": "1.1.2",
"uuid": "c35bb2f6-f24a-4850-ae44-643f2fdc7541",
"isBundle": false,
"bundleName": "",
"priority": 1,
"compressionType": {},
"optimizeHotUpdate": {},
"inlineSpriteFrames": {},
"isRemoteBundle": {
"ios": false,
"android": false
},
"subMetas": {}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
{
"type": "software",
"scope": "game",
"name": "GameOBESDK",
"version": "1.1.5.300",
"playbook": ""
}
\ No newline at end of file
{
"ver": "1.0.0",
"uuid": "0614d8cf-dd45-41f8-87d4-bee49ddea0f3",
"subMetas": {}
}
\ No newline at end of file
{ {
"ver": "1.1.2", "ver": "1.1.2",
"uuid": "821c2d0d-9578-4d1c-9d43-1432e2e9a23c", "uuid": "7ad93cad-25ac-4bb2-9957-8a31330f3a09",
"isBundle": false, "isBundle": false,
"bundleName": "", "bundleName": "",
"priority": 1, "priority": 1,
......
export as namespace Play;
declare class EventEmitter<T> {
on<K extends keyof T>(event: K, listener: (payload: T[K]) => any): this;
on(evt: string, listener: Function): this;
once<K extends keyof T>(event: K, listener: (payload: T[K]) => any): this;
once(evt: string, listener: Function): this;
off<K extends keyof T>(evt: K | string, listener?: Function): this;
emit<K extends keyof T>(evt: K | string, ...args: any[]): boolean;
}
export enum Event {
/** 断开连接 */
DISCONNECTED = 'disconnected',
/** 加入到大厅 */
LOBBY_JOINED = 'lobbyJoined',
/** 大厅房间列表变化 */
LOBBY_ROOM_LIST_UPDATED = 'lobbyRoomListUpdate',
/** 有新玩家加入房间 */
PLAYER_ROOM_JOINED = 'newPlayerJoinedRoom',
/** 有玩家离开房间 */
PLAYER_ROOM_LEFT = 'playerLeftRoom',
/** 玩家活跃属性变化 */
PLAYER_ACTIVITY_CHANGED = 'playerActivityChanged',
/** 主机变更 */
MASTER_SWITCHED = 'masterSwitched',
/** 离开房间 */
ROOM_LEFT = 'roomLeft',
/** 被踢出房间 */
ROOM_KICKED = 'roomKicked',
/** 房间系统属性变化 */
ROOM_SYSTEM_PROPERTIES_CHANGED = 'roomSystemPropertiesChanged',
/** 房间自定义属性变化 */
ROOM_CUSTOM_PROPERTIES_CHANGED = 'roomCustomPropertiesChanged',
/** 玩家自定义属性变化 */
PLAYER_CUSTOM_PROPERTIES_CHANGED = 'playerCustomPropertiesChanged',
/** 自定义事件 */
CUSTOM_EVENT = 'customEvent',
/** 错误事件 */
ERROR = 'error',
}
export enum ReceiverGroup {
/** 其他人(除了自己之外的所有人) */
Others,
/** 所有人(包括自己) */
All,
/** 主机客户端 */
MasterClient,
}
interface CustomProperties {
[key: string]: any;
}
interface CustomEventData {
[key: string]: any;
}
interface ErrorEvent {
code: number;
detail: string;
}
declare interface PlayEvent {
connected: void;
connectFailed: ErrorEvent;
disconnected: void;
lobbyJoined: void;
lobbyLeft: void;
lobbyRoomListUpdate: void;
roomCreated: void;
roomCreateFailed: ErrorEvent;
roomJoined: void;
roomJoinFailed: ErrorEvent;
newPlayerJoinedRoom: {
newPlayer: Player;
};
playerLeftRoom: {
leftPlayer: Player;
};
playerActivityChanged: {
player: Player;
};
masterSwitched: {
newMaster: Player;
};
roomLeft: void;
roomKicked: {
code: number;
msg: string;
};
roomCustomPropertiesChanged: {
changedProps: CustomProperties;
};
roomSystemPropertiesChanged: {
changedProps: CustomProperties;
};
playerCustomPropertiesChanged: {
player: Player;
changedProps: CustomProperties;
};
customEvent: {
eventId: number;
eventData: CustomEventData;
senderId: number;
};
error: ErrorEvent;
}
export class LobbyRoom {
readonly roomName: string;
readonly maxPlayerCount: number;
readonly expectedUserIds: string[];
readonly emptyRoomTtl: number;
readonly playerTtl: number;
readonly playerCount: number;
readonly customRoomPropertiesForLobby: CustomProperties;
}
export class Player {
readonly userId: string;
readonly actorId: number;
readonly isLocal: boolean;
readonly isMaster: boolean;
readonly isActive: boolean;
setCustomProperties(
properties: CustomProperties,
opts?: {
expectedValues?: CustomProperties;
}
): Promise<void>;
readonly customProperties: CustomProperties;
}
export class Room {
readonly name: string;
readonly open: boolean;
readonly visible: boolean;
readonly maxPlayerCount: number;
readonly master: Player;
readonly masterId: number;
readonly expectedUserIds: string[];
readonly playerList: Player[];
getPlayer(actorId: number): Player;
setCustomProperties(
properties: CustomProperties,
opts?: {
expectedValues?: CustomProperties;
}
): Promise<void>;
readonly customProperties: CustomProperties;
setOpen(open: boolean): Promise<void>;
setVisible(visible: boolean): Promise<void>;
setRoomMaxPlayerCount(count: number): Promise<void>;
setRoomExpectedUserIds(expectedUserIds: string[]): Promise<void>;
clearRoomExpectedUserIds(): Promise<void>;
addRoomExpectedUserIds(expectedUserIds: string[]): Promise<void>;
removeRoomExpectedUserIds(expectedUserIds: string[]): Promise<void>;
setMaster(newMasterId: number): Promise<void>;
sendEvent(
eventId: number,
eventData?: CustomEventData,
options?: {
receiverGroup?: ReceiverGroup;
targetActorIds?: number[];
}
): Promise<void>;
kickPlayer(
actorId: number,
opts?: {
code?: number;
msg?: string;
}
): Promise<void>;
leave(): Promise<void>;
}
export class Client extends EventEmitter<PlayEvent> {
readonly room: Room;
readonly player: Player;
readonly lobbyRoomList: LobbyRoom[];
userId: string;
constructor(opts: {
appId: string;
appKey: string;
userId: string;
ssl?: boolean;
feature?: string;
gameVersion?: string;
playServer?: string;
});
connect(): Promise<Client>;
reconnect(): Promise<Client>;
reconnectAndRejoin(): Promise<Room>;
close(): Promise<void>;
joinLobby(): Promise<void>;
leaveLobby(): Promise<void>;
createRoom(opts?: {
roomName?: string;
roomOptions?: Object;
expectedUserIds?: string[];
}): Promise<Room>;
joinRoom(
roomName: string,
opts?: {
expectedUserIds?: string[];
}
): Promise<Room>;
rejoinRoom(roomName: string): Promise<Room>;
joinOrCreateRoom(
roomName: string,
opts?: {
roomOptions?: Object;
expectedUserIds: string[];
}
): Promise<Room>;
joinRandomRoom(opts?: {
matchProperties?: Object;
expectedUserIds?: string[];
}): Promise<Room>;
matchRandom(
piggybackPeerId: string,
opts?: { matchProperties?: Object; expectedUserIds?: string[] }
): Promise<LobbyRoom>;
setRoomOpen(open: boolean): Promise<void>;
setRoomVisible(visible: boolean): Promise<void>;
setRoomMaxPlayerCount(count: number): Promise<void>;
setRoomExpectedUserIds(expectedUserIds: string[]): Promise<void>;
clearRoomExpectedUserIds(): Promise<void>;
addRoomExpectedUserIds(expectedUserIds: string[]): Promise<void>;
removeRoomExpectedUserIds(expectedUserIds: string[]): Promise<void>;
setMaster(newMasterId: number): Promise<void>;
sendEvent(
eventId: number,
eventData?: CustomEventData,
options?: {
receiverGroup?: ReceiverGroup;
targetActorIds?: number[];
}
): Promise<void>;
leaveRoom(): Promise<void>;
kickPlayer(
actorId: number,
opts?: {
code?: number;
msg?: string;
}
): Promise<void>;
pauseMessageQueue(): void;
resumeMessageQueue(): void;
}
export enum CreateRoomFlag {
FixedMaster = 1,
MasterUpdateRoomProperties = 2,
}
export function setAdapters(newAdapters: { WebSocket: Function }): void;
export enum LogLevel {
Debug = 'Debug',
Warn = 'Warn',
Error = 'Error',
}
export function setLogger(logger: {
Debug: (...args: any[]) => any;
Warn: (...args: any[]) => any;
Error: (...args: any[]) => any;
}): void;
export enum PlayErrorCode {
OPEN_WEBSOCKET_ERROR = 10001,
SEND_MESSAGE_STATE_ERROR = 10002,
}
export function registerType<T>(
type: T,
typeId: number,
serializeMethod: (obj: T) => Uint8Array,
deserializeMethod: (bytes: Uint8Array) => T
): void;
export function serializeObject(obj: Object): Uint8Array;
export function deserializeObject(bytes: Uint8Array): Object;
{ {
"ver": "2.0.0", "ver": "2.0.0",
"uuid": "758b0cbc-9597-4f72-b7d7-eafd5bfa5684", "uuid": "def7a5ea-e306-4527-a575-dd078a3e6a7d",
"subMetas": {} "subMetas": {}
} }
\ No newline at end of file
This diff is collapsed.
{ {
"ver": "1.0.8", "ver": "1.0.8",
"uuid": "f8a6fa03-d3af-4c33-8c3b-2f21e7c5e175", "uuid": "5fbb2878-d748-459f-97ed-95067bd1642b",
"isPlugin": true, "isPlugin": true,
"loadPluginInWeb": true, "loadPluginInWeb": true,
"loadPluginInNative": true, "loadPluginInNative": true,
......
...@@ -276,7 +276,12 @@ cc.Class({ ...@@ -276,7 +276,12 @@ cc.Class({
for(let i=0;i<this.data.images.length;i++){ for(let i=0;i<this.data.images.length;i++){
let image=this.data.images[i]; let image=this.data.images[i];
let tooth=await this.getSprNodeByUrl(image.img); let tooth=await this.getSprNodeByUrl(image.img);
parent.addChild(tooth); // parent.addChild(tooth);
parent.parent.addChild(tooth, 5);
tooth.x += parent.x;
tooth.y += parent.y;
// tooth.color = cc.Color.WHITE; // tooth.color = cc.Color.WHITE;
tooth.painted = null; tooth.painted = null;
} }
...@@ -470,12 +475,13 @@ cc.Class({ ...@@ -470,12 +475,13 @@ cc.Class({
console.log('~~~~~~~ 4'); console.log('~~~~~~~ 4');
this.networkHelper.startFrameSync(() => { // this.networkHelper.startFrameSync(() => {
}); // });
this.checkGameStart(); this.checkGameStart();
this.checkIsTeacher();
}, },
...@@ -492,8 +498,9 @@ cc.Class({ ...@@ -492,8 +498,9 @@ cc.Class({
console.log('this.isTeacher: ' , this.isTeacher); console.log('this.isTeacher: ' , this.isTeacher);
if (this.isTeacher) { if (this.isTeacher) {
// this.networkHelper.closeRoom(); this.networkHelper.closeRoom().then(() => {
this.addAiUser(); this.addAiUser();
});
} else { } else {
this.checkGameStart(); this.checkGameStart();
...@@ -515,16 +522,20 @@ cc.Class({ ...@@ -515,16 +522,20 @@ cc.Class({
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
const aiId = id + i; const aiId = id + i;
const data = { id: aiId, name: this.playerInfoData[i].name } const data = { playerId: aiId.toString(), name: this.playerInfoData[i].name }
this.sendServerEvent('add_ai', data); this.sendServerEvent('add_ai', data);
} }
}, },
checkIsTeacher(room) { checkIsTeacher() {
this.isTeacher = this.networkHelper.checkIsOwner(); // this.isTeacher = this.networkHelper.checkIsOwner();
return;
console.log("this.networkHelper.room.ownerId : ", this.networkHelper.room.ownerId );
console.log("this.playerId: ", this.playerId);
this.isTeacher = this.networkHelper.room.ownerId == this.playerId;
return
const playerList = this.networkHelper.room.roomInfo.playerList; const playerList = this.networkHelper.room.roomInfo.playerList;
...@@ -569,7 +580,9 @@ cc.Class({ ...@@ -569,7 +580,9 @@ cc.Class({
initServerAllUser(room) { initServerAllUser(room) {
// const roomInfo = room.roomInfo // const roomInfo = room.roomInfo
// this.serverAllUser = roomInfo.playerList; // this.serverAllUser = roomInfo.playerList;
this.serverAllUser = this.networkHelper.getOnlinePlayers(); this.serverAllUser = this.networkHelper.room.players;
console.log('this.serverAllUser: ', this.serverAllUser.toString());
console.log('this.serverAllUser.length: ', this.serverAllUser.length);
}, },
addNetworkListener(nh) { addNetworkListener(nh) {
...@@ -581,7 +594,7 @@ cc.Class({ ...@@ -581,7 +594,7 @@ cc.Class({
// } // }
this.log("playerJoin", (event)); this.log("playerJoin", (event));
this.onPlayerJoin(event.data); this.onPlayerJoin(event);
}); });
nh.on('playerLeave', (event) => { nh.on('playerLeave', (event) => {
...@@ -592,7 +605,9 @@ cc.Class({ ...@@ -592,7 +605,9 @@ cc.Class({
}); });
nh.on('frameEvent', (event) => { nh.on('frameEvent', (event) => {
const frameInfo = event.frameInfo; console.log(' on frameEvent``', event);
const frameInfo = event?.data?.frame?.items;
if (!frameInfo || frameInfo.length == 0) { if (!frameInfo || frameInfo.length == 0) {
return; return;
} }
...@@ -600,7 +615,7 @@ cc.Class({ ...@@ -600,7 +615,7 @@ cc.Class({
frameInfo.forEach((frameData) => { frameInfo.forEach((frameData) => {
frameData.data = JSON.parse(frameData.data); // frameData.data = JSON.parse(frameData.data);
const res = frameData.data; const res = frameData.data;
switch (res.type) { switch (res.type) {
...@@ -628,6 +643,11 @@ cc.Class({ ...@@ -628,6 +643,11 @@ cc.Class({
this.onAddAi(res.data); this.onAddAi(res.data);
return; return;
case 'refresh_player_list':
console.log(' on refresh_player_list')
this.onRefreshPlayerList(res.data);
return;
} }
}) })
...@@ -638,19 +658,25 @@ cc.Class({ ...@@ -638,19 +658,25 @@ cc.Class({
onPlayerJoin(data) { onPlayerJoin(data) {
let user = { id: data.joinPlayerId };
console.log(" in onPlayerJoin : ", data);
let user = { playerId: data.playerId };
console.log(' in onPlayerJoin 1 ', JSON.stringify(user)); console.log(' in onPlayerJoin 1 ', JSON.stringify(user));
const len = this.serverAllUser.length;
user.name = this.playerInfoData[len].name;
const playerList = data.roomInfo.playerList; const playerList = this.networkHelper.room.players;
console.log('playerList: ', playerList);
for (let i = 0; i < playerList.length; i++) { for (let i = 0; i < playerList.length; i++) {
if (playerList[i].id == user.id) { if (playerList[i].playerId == user.id) {
user.name = playerList[i].name; user.name = playerList[i].name;
console.log('in playerlist');
} }
} }
const len = this.serverAllUser.length;
user.name = this.playerInfoData[len].name;
console.log(' in onPlayerJoin 2 ', JSON.stringify(user)); console.log(' in onPlayerJoin 2 ', JSON.stringify(user));
...@@ -659,9 +685,16 @@ cc.Class({ ...@@ -659,9 +685,16 @@ cc.Class({
onAddAi(data) { onAddAi(data) {
console.log(' in onAddAi '); console.log(' in onAddAi data: ', data);
this.addUser({ id: data.id, name: data.name, isAi: true }) this.addUser({ playerId: data.playerId, name: data.name, isAi: true })
},
onRefreshPlayerList(data) {
console.log('onRefreshPlayerList data: ', data);
for (let i=0; i<data.length; i++) {
this.addUser(data[i]);
}
}, },
setPlayerResult(data) { setPlayerResult(data) {
...@@ -669,7 +702,7 @@ cc.Class({ ...@@ -669,7 +702,7 @@ cc.Class({
this.gameEndData[uuid] = data; this.gameEndData[uuid] = data;
for (let i = 0; i < this.serverAllUser.length; i++) { for (let i = 0; i < this.serverAllUser.length; i++) {
if (this.serverAllUser[i].id == uuid) { if (this.serverAllUser[i].playerId == uuid) {
this.serverAllUser[i].result = data; this.serverAllUser[i].result = data;
} }
} }
...@@ -797,7 +830,7 @@ cc.Class({ ...@@ -797,7 +830,7 @@ cc.Class({
console.log('this.serverAllUser[i].id: ', this.serverAllUser[i]); console.log('this.serverAllUser[i].id: ', this.serverAllUser[i]);
console.log('uuid: ', uuid); console.log('uuid: ', uuid);
if (this.serverAllUser[i].id == uuid) { if (this.serverAllUser[i].playerId == uuid) {
return this.serverAllUser[i].name; return this.serverAllUser[i].name;
} }
} }
...@@ -973,7 +1006,7 @@ cc.Class({ ...@@ -973,7 +1006,7 @@ cc.Class({
} }
const aiArr = this.getAiArr(); const aiArr = this.getAiArr();
if (aiArr.length == 0) { if (aiArr.length == 0 || true) {
this.teacherEnd(); this.teacherEnd();
return; return;
} }
...@@ -1335,9 +1368,9 @@ cc.Class({ ...@@ -1335,9 +1368,9 @@ cc.Class({
for (let i = 0; i < this.serverAllUser.length; i++) { for (let i = 0; i < this.serverAllUser.length; i++) {
const user = this.serverAllUser[i]; const user = this.serverAllUser[i];
const isSelf = user.id == this.playerId; const isSelf = user.playerId == this.playerId;
let headUrl = playerData[i].headUrl; let headUrl = playerData[i].headUrl;
if (isSelf) { if (isSelf && false) {
user.name = user.nick_name user.name = user.nick_name
headUrl = user.playerInfo.avatar; headUrl = user.playerInfo.avatar;
console.log('avatar: ', user.playerInfo.avatar) console.log('avatar: ', user.playerInfo.avatar)
...@@ -1389,8 +1422,10 @@ cc.Class({ ...@@ -1389,8 +1422,10 @@ cc.Class({
return; return;
} }
console.log('this.serverAllUser: ', this.serverAllUser);
console.log('user: ', user);
for (let i = 0; i < this.serverAllUser.length; i++) { for (let i = 0; i < this.serverAllUser.length; i++) {
if (this.serverAllUser[i].id == user.id) { if (this.serverAllUser[i].playerId == user.playerId) {
console.log(' 该用户已经存在 无需再加入。') console.log(' 该用户已经存在 无需再加入。')
return; return;
} }
...@@ -1401,15 +1436,20 @@ cc.Class({ ...@@ -1401,15 +1436,20 @@ cc.Class({
const len = this.serverAllUser.length; const len = this.serverAllUser.length;
const isSelf = this.playerId == user.id; const isSelf = this.playerId == user.playerId;
this.loadingScript.addPlayer(user.name, isSelf, this.playerInfoData[len - 1].headUrl); this.loadingScript.addPlayer(user.name, isSelf, this.playerInfoData[len - 1].headUrl);
// if (this.isTeacher) {
// setTimeout(() => { console.log('isSelf: ', isSelf);
// console.log(' aaa addUser, '); console.log('this.isTeacher: ', this.isTeacher);
// this.gameServer.addUser(user); console.log('user.isAi: ', user.isAi);
// }, 2000); if (this.isTeacher && !user.isAi) {
// } setTimeout(() => {
this.sendServerEvent('refresh_player_list', this.serverAllUser);
// this.gameServer.addUser(user);
}, 1);
}
}, },
...@@ -1448,6 +1488,10 @@ cc.Class({ ...@@ -1448,6 +1488,10 @@ cc.Class({
this.log("bg:"+bg1.name); this.log("bg:"+bg1.name);
bg1.getComponent(cc.Sprite).spriteFrame=spriteFrame; bg1.getComponent(cc.Sprite).spriteFrame=spriteFrame;
let bg2=this.paint2.getChildByName("alligator_img"); let bg2=this.paint2.getChildByName("alligator_img");
bg2.getComponent(cc.Sprite).spriteFrame=spriteFrame; bg2.getComponent(cc.Sprite).spriteFrame=spriteFrame;
...@@ -1537,6 +1581,8 @@ cc.Class({ ...@@ -1537,6 +1581,8 @@ cc.Class({
// this.gameEndData = JSON.parse( data ); // this.gameEndData = JSON.parse( data );
// } // }
this.isTimingShow = false;
if (this.isGameEnd) { if (this.isGameEnd) {
return; return;
} }
...@@ -1710,6 +1756,8 @@ cc.Class({ ...@@ -1710,6 +1756,8 @@ cc.Class({
rt.destroy(); rt.destroy();
} }
console.log('data~ : ', data);
if (data[3] > 0) { if (data[3] > 0) {
return true; return true;
} else { } else {
...@@ -1732,6 +1780,7 @@ cc.Class({ ...@@ -1732,6 +1780,7 @@ cc.Class({
}, },
sendResult() { sendResult() {
return;
const data = { teethDataArr: this.teethDataArr, uuid: this.playerId }; const data = { teethDataArr: this.teethDataArr, uuid: this.playerId };
if (window && window.courseware) { if (window && window.courseware) {
...@@ -1743,6 +1792,9 @@ cc.Class({ ...@@ -1743,6 +1792,9 @@ cc.Class({
console.log("sendServerEvent key: ", key); console.log("sendServerEvent key: ", key);
console.log("sendServerEvent data: ", data); console.log("sendServerEvent data: ", data);
// this.networkHelper.sendFrame({type:"aaaa", data:{a:"1"}});
this.networkHelper.sendFrame({ this.networkHelper.sendFrame({
type: key, type: key,
data data
......
This diff is collapsed.
import {asyncDelay} from './util.js'
export class NetworkHelper {
_eventListeners: any = {};
client: any;
playerId: any;
currentPlayer: any;
room: any;
roomType: any;
maxPlayers: any;
startFrameSyncCallback: any;
isStartFrameSync: any;
userInfo: any;
tempRoomPlayer: any;
ctor() {
}
on(eventName, func) {
this._eventListeners[eventName] = func;
}
async init(roomType: string, maxPlayers: number) {
// 人数只支持2~10个 ~~
this.userInfo = await this.initUserInfo();
console.log('this.userInfo: ', this.userInfo);
this.maxPlayers = maxPlayers;
this.roomType = roomType;
await this.initEngine();
this.initTempRoomPlayer();
// await this.initRoom();
return this.userInfo.id;
}
initTempRoomPlayer() {
const playerInfo = this.initPlayerInfo();
this.userInfo.playerInfo = playerInfo;
this.tempRoomPlayer = [ this.userInfo ];
}
initUserInfo() {
return new Promise((resolve, reject) => {
if ( cc.find('middleLayer') && cc.find('middleLayer').getComponent('middleLayer')?.getUserInfo ) {
cc.find('middleLayer').getComponent('middleLayer').getUserInfo().then((res)=> {
resolve(res);
})
} else {
setTimeout(() => {
const userInfo = {
nick_name: '拼读达人',
avatar_url: '1',
id: 'id_' + new Date().getTime()
};
resolve(userInfo);
}, 100);
}
})
}
async initEngine() {
const client = new window.GOBE.Client({
clientId: '860627598634404416',// 客户端ID
clientSecret: '83B0DCE6407CBEFAD5786BAC07A73EBAF8E688E2CABA779724FC000C0714C8E7',// 客户端密钥
appId: '105878157',// 应用的ID
openId: this.userInfo.id,// 玩家ID
});
this.client = client;
return new Promise((resolve, reject) => {
client.init().then(() => {
// 初始化成功
console.log(' 华为 对战联机引擎 初始化成功')
console.log('``client: ', client);
this.playerId = client.playerId;
resolve('');
}).catch((e) => {
// 初始化失败
console.log(' 华为 对战联机引擎 初始化失败')
reject();
});
})
}
async initRoom() {
console.log('初始化 房间')
const playerInfo = this.initPlayerInfo();
return new Promise((resolve, reject) => {
this.client.matchRoom({
matchParams: {
matchRule: 'match_rule_' + this.maxPlayers,
// matchRule2: 'xxxx',
},
roomType: this.roomType,
customRoomProperties: 'customRoomProperties_xxx',
// roomStatus: ROOM_STATE_IDLE,
maxPlayers: this.maxPlayers,
},{customPlayerStatus: 0, customPlayerProperties: JSON.stringify(playerInfo)}).then((room) => {
// 房间匹配成功
console.log('房间匹配成功: ', room);
this.currentPlayer = room.player;
this.room = room;
this.addRoomListener(room);
this.initRoomPlayerInfo();
resolve('');
}).catch((e) => {
// 房间匹配失败
console.log(' in initRoom error:', e)
reject();
});
})
}
initRoomPlayerInfo() {
const players = this.room.players;
players.forEach(p => {
this.setCustomPlayerProperties(p);
})
}
initPlayerInfo() {
// 初始化玩家基础数据
const nick_name = this.userInfo?.nick_name || '拼读达人';
const avatar_url = this.userInfo?.avatar_url || '1';
const avatar = this.getAvatar(avatar_url);
const playerInfo = {
playerId: this.playerId,
matchParams: {
level: 1,
},
name: nick_name,
avatar,
customPlayerStatus: 0,
};
if (this.userInfo) {
this.userInfo.playerId = this.playerId;
}
return playerInfo;
}
getAvatar(avatar_url) {
let avatar = 'http://staging-teach.cdn.ireadabc.com/0751c28419a0e8ffb1f0e84435b081ce.png';
if (cc.find('middleLayer') && cc.find('middleLayer').getComponent('middleLayer')?.getHeadUrl) {
avatar = cc.find('middleLayer').getComponent('middleLayer').getHeadUrl(avatar_url);
}
return avatar;
}
addRoomListener(room) {
// 添加房间玩家进入监听
room.onJoin((playerInfo) => {
//有玩家加入房间,做相关游戏逻辑处理
console.log(' onJoin :', playerInfo);
this.playerJoin(playerInfo);
});
// 添加帧同步开始通知回调
room.onStartFrameSync(() => {
// 接收帧同步开始通知,处理游戏逻辑
console.log("接收帧同步 开始")
if (this.startFrameSyncCallback) {
this.startFrameSyncCallback.call();
}
this.isStartFrameSync = true;
});
// 添加帧同步停止通知回调
room.onStopFrameSync(() => {
// 接收帧同步停止通知,处理游戏逻辑
console.log("接收帧同步 停止")
});
// 添加接收帧同步信息回调
room.onRecvFrame((msg) => {
// 处理帧数据msg
if (this._eventListeners['frameEvent']) {
this._eventListeners['frameEvent'](msg);
}
});
// 离开房间事件
room.onLeave((playerInfo) => {
// 有玩家离开房间,做相关游戏逻辑处理
console.log(' onLeave :', playerInfo);
this.updateRoom();
if (this._eventListeners['playerLeave']) {
this._eventListeners['playerLeave'](playerInfo);
}
});
}
playerJoin(data) {
// 有玩家加入
this.updateRoom(() => {
const playerData = this.getRoomPlayerById(data.playerId);
if (!playerData) {
return;
}
this.setCustomPlayerProperties(playerData);
this._eventListeners['playerJoin'](playerData);
});
}
setCustomPlayerProperties(playerData) {
// 兼容老模板
if ( !playerData.playerInfo) {
console.log('string : ', playerData.customPlayerProperties);
playerData.playerInfo = JSON.parse(playerData.customPlayerProperties);
}
}
leaveRoom() {
// 离开房间
this.client.leaveRoom().then((client) => {
// 退出房间成功
console.log(' 退出房间成功 ')
console.log(' client: ', client);
}).catch((e) => {
// 退出房间失败
console.log(' 退出房间失败 ')
});
}
updateRoom(cb = null) {
console.log('in updateRoom');
// 更新一下房间数据
this.room.update().then(() => {
// 更新玩家房间信息成功,做相关的游戏处理逻辑
console.log('update this.room: ', this.room);
// this.checkCanStart();
cb && cb();
}).catch(() => {
// 更新玩家房间信息失败
});
}
getOnlinePlayers() {
return this.tempRoomPlayer;
// 获取房间中 还在线上的玩家列表
const onlinePlayers = [];
const players = this.room.config.players;
for (let i=0; i<players.length; i++) {
if (players[i].status == 1) {
onlinePlayers.push(players[i]);
}
}
return onlinePlayers
}
checkIsOwner() {
return true;
// 检查是不是房主 之前房主随时有掉线的可能
const onlinePlayers = this.getOnlinePlayers();
const firstPlayer = onlinePlayers[0];
return firstPlayer.playerId == this.playerId;
}
getRoomPlayerById(id) {
return this.tempRoomPlayer[0]
// 获取房间中特定id的玩家
const players = this.room.config.players;
const player = players.find(p => {
return p.playerId == id;
})
return player;
}
startFrameSync(cb=null) {
cb();
return;
console.log('开启帧同步 ..');
if (this.isStartFrameSync) {
console.log('开启帧同步 .. 1');
return;
}
if (this.startFrameSyncCallback) {
return;
}
// 开启帧同步
if (cb) {
this.startFrameSyncCallback = cb;
}
this.room.startFrameSync();
}
stopGame() {
console.log('停止帧同步 ..');
// 向联机对战后端发送停止帧同步请求
this.room.stopFrameSync();
}
sendFrame(data: any) {
const frameInfo = [{data: JSON.stringify(data)}];
this._eventListeners['frameEvent']({frameInfo});
return;
// 发送帧数据
this.room.sendFrame(JSON.stringify(data), err => {
if (err.code != 0) {
console.log("err", err)
}
});
}
}
\ No newline at end of file
{
"ver": "1.0.8",
"uuid": "24e2eb8f-4ebd-4080-978f-371087a3f7f9",
"isPlugin": false,
"loadPluginInWeb": true,
"loadPluginInNative": true,
"loadPluginInEditor": false,
"subMetas": {}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment