1.获取wx和游戏服务
start() {
this.wx = window['wx'];//避开ts语法检测
this.svr = this.wx.getGameServerManager()
}
登录游戏服务器
// 1登录游戏服务器
loginServiceStart() {
this.svr.login().then((res) => {
console.warn('游戏服务登录成功',res)
}).catch(err => {
console.warn('游戏服务登录失败', err)
})
}
创建房间
startStateService(){
// 创建房间 将房间信息添加到后台
this.svr.createRoom({
maxMemberNum: 2,
startPercent: 100,
needUserInfo: true,//需要昵称头像
gameLastTime:60,//60一句游戏
roomExtInfo:"只有咱俩哦",
memberExtInfo:"我是你呀",
}).then(res => {
console.log("房间创建结果",res.data)
this.roomId=res.data.accessInfo
var data={
roomId:this.roomId,
roomNum:1,
roomTotalNum:2,
roomStatus:1,
}
var url="/addYxRoomInfo";
HttpUtil.POST(url, "", data, (res, data) => {
});
});
}
加入房间并监听房间成员变化
// 3加入房间监听房间信息变更虎丘房间详情
postMessage(){
var accessInfo=this.roomId;
console.log("房间",accessInfo);
//加入房间
// this.svr.joinRoom({
// 'accessInfo':accessInfo,
// 'memberExtInfo':'哈哈',
// complete:res=>{
// console.log("加入房间结果",res);
// }
// });
this.svr.joinRoom({
'accessInfo':accessInfo
}).then(res => {
console.log("加入房间的结果",res);
// this.svr.startGame();
}).catch(e=> {
console.log(e);
});
//监听房间信息变更
this.svr.onRoomInfoChange(function (res) {
console.log('监听房间信息变更',res)
})
// 获取房间详情
this.svr.getRoomInfo().then((res) => {
console.log("获取房间详情",res)
})
}
获取最新的房间(用java在后台写的接口,和前面将房间存到后台对应)
getFriendsStateData(){
// ziyu_test.getFriendsStateData(this.svr);
var data={
}
var url="/getLastRoomInfo";
HttpUtil.POST(url, "", data, (res, data) => {
data = JSON.parse(data)
data=data.data;
var roomId=data.roomId
this.roomId=roomId;
console.log("拉取在线好友列表",data.roomId)
this.svr.joinRoom({
'accessInfo':roomId
}).then(res => {
console.log("加入房间的结果11",res);
// this.svr.startGame();
}).catch(e=> {
console.log(e);
});
});
}
给房间推送广播
// 4
onMessage(){
// 推送消息给房间成员
this.svr.broadcastInRoom({
msg: "MSG",
success:res=>{
console.log("推送消息给房间成员成功",res);
},
fail:res=>{
console.log("推送消息给房间成员失败",res);
}
});
}
监听房间广播信息
onBroadcast(){
this.svr.onBroadcast(res=>{
console.log("监听广播信息",res);
});
}
对应的资源链接 大家可下载资源