排行榜的实现:
在注册时将玩家的账号 密码 最大分数封装到一个对象g_Data中 并分配一个ID
if (data.key == "register") { //data.key为客户端发送注册信息是的标记
if (g_Data[ws.pid]) { //账号已存在
return;
}
else {
g_Data[ws.pid] = {
account: data.account, //账号
password: data.password,//密码
maxScore: 0 //分数
};
}
}
在登录时将客户端发过来的数据与服务端保存的数据做对比,如果存在且密码匹配正确
则向客户端发送一个允许登录的标记
else if (data.key == "login") { //data.key为客户端请求登录时的标记
let loginOk = false;
if (g_Data[ws.pid]) {
if (g_Data[ws.pid].account == data.account) {
if (g_Data[ws.pid].password == data.password) {
loginOk = true;
}
}
}
let info = {
key: "login",
Ok: loginOk
}
ws.send(JSON.stringify(info));
在玩家每次死亡的时候自动上传分数 与之前的分数做对比取最大值
else if (data.key == "upload") { //data.key为客户端上传分数时的标记
if (g_Data[ws.pid]) {
g_Data[ws.pid].maxScore = Math.max(g_Data[ws.pid].maxScore, data.Score);
}
console.log(g_Data[ws.pid]);
}
在每次客户端请求排行版数据的时候,服务端将自己的分数和他人的分数分别打包成一个对象发给客户端,客户端排序后再按顺序显示在屏幕上
else if (data.key == "score") { //data.key为客户端请求排行版时的标记
let selfList = {};
let otherList = [];//所有人的数据
for (let iId in g_Data) {
if (iId == ws.pid) { // 寻找自己的分数数据
selfList["account"] = g_Data[iId].account;
selfList.maxScore = g_Data[iId].maxScore;
}
else {
let rankData = {};//临时保存玩家分数
rankData["account"] = g_Data[iId].account;
rankData["maxScore"] = g_Data[iId].maxScore
otherList.push(rankData); //将对象 rankData加进数组otherList
}
}
let data={ //定义一个对象data储存数据 并加上标记"score"
key:"score",
selfList:selfList,
otherList:otherList
}
ws.send(JSON.stringify(data)); //打包发给客户端
}
//客户端数据处理
otherList.push(selfList); //将自己的数据加进其他人的数组中一起排序
otherList.sort(
(a,b)=>{
return b.maxScore-a.maxScore;
}
)
otherList.splice(10,otherList.length-10); //排行榜保留10位
for (let i of otherList) {
let node = cc.instantiate(this.today); //克隆预制体
content.addChild(node); //添加到content的子节点上
node.getChildByName("rank").getComponent(cc.Label).string = "" + rankNum;//名次
node.getChildByName("account").getComponent(cc.Label).string = "" + i.account;//账号
node.getChildByName("score").getComponent(cc.Label).string = "" + i.maxScore;//分数
rankNum++;
if(selfList.account==i.account){ //如果在前10 寻找自己的位置并改为红色
node.color=cc.color(255,0,0,255);
}
}
if(selfrank>10){ //如果不在前10 则在最后加一行数据 并显示自己的名次
let node = cc.instantiate(this.today);
content.addChild(node);
node.getChildByName("rank").getComponent(cc.Label).string = "" + selfrank;
node.getChildByName("account").getComponent(cc.Label).string = "" + selfList.account;
node.getChildByName("score").getComponent(cc.Label).string = "" + selfList.maxScore;
node.color=cc.color(255,255,0,255);
}
本文介绍了在Cocos Creator中实现游戏排行榜的步骤。包括在注册和登录时处理玩家信息,玩家死亡时自动上传最高分,以及服务端在接收到排行版请求时发送数据到客户端,客户端再进行排序展示。
6154

被折叠的 条评论
为什么被折叠?



