联网对战游戏开源实例分享之《斗兽棋》

逻辑星轨
• 阅读 3171

本次,Matchvs为大家带来的是一款回合制休闲游戏的开源案例 。玩家双方在一个4X4的棋盘上,遵循食物链的规则玩法下进行翻牌与追逐,最终以场上存活的一方为获胜者。

体验地址: http://demo.matchvs.com/Anima...

源码地址::https://github.com/matchvs/An...

首先你需要下载Cocos Creator 和Matchvs JavaScript SDK。本次游戏设计的实现步骤主要拆分为用户登录、随机匹配和创建房间、以及同屏游戏三个部分完成。

用户登录

​ 使用Cocos Creator(以下简称CC)创建游戏登录场景

​ 使用CC 拖动控件, 还原设计稿 , 依托CC的良好的工作流,使得这部分的工作可以由游戏策划或者UI设计者来完成,程序开发者只需要在场景中挂载相应的游戏逻辑脚本. 举个例子,在登录按钮挂在一个uiLogin.js的脚本完成用户登录功能.

uilogin.fire

联网对战游戏开源实例分享之《斗兽棋》

新建一个uiLogin.js,按 1,2,3 三个步骤挂载到场景中.

新建js脚本文件

选中场景任一控件

添加组件,选中刚新建的脚本,

在脚本的on'Load函数中给按钮添加点击监听,触发登录操作

onLoad() {
     this.nodeDict["start"].on("click", Game.GameManager.matchVsInit, Game.GameManager);
}

实现this.startGame函数. 登录之前需要初始化Matchvs SDK:

uiLogin.js

uiLogin.js
---

var uiPanel = require("uiPanel");
cc.Class({
    extends: uiPanel,
    properties: {},

    onLoad() {
        this._super();
    },

    start() {
        if (window.wx) {
            this.nodeDict["start"].active = false;
            wx.getSystemInfo({
                success: function(data) {
                    Game.GameManager.getUserInfoBtn = wx.createUserInfoButton({
                        type: 'text',
                        text: '开始多人游戏',
                        style: {
                            left: data.screenWidth * 0.2,
                            top: data.screenHeight * 0.73,
                            width: data.screenWidth * 0.65,
                            height: data.screenHeight * 0.07,
                            lineHeight: data.screenHeight * 0.07,
                            backgroundColor: '#fe714a',
                            color: '#ffffff',
                            textAlign: 'center',
                            fontSize: data.screenHeight * 0.025,
                            borderRadius: 8
                        }
                    });
                    Game.GameManager.getUserInfoBtn.onTap(function(res) {
                        if (Game.GameManager.isClickCd) {
                            return;
                        }
                        Game.GameManager.isClickCd = true;
                        setTimeout(function() {
                            Game.GameManager.isClickCd = false;
                        }, 1000);
                        Game.GameManager.nickName = res.userInfo.nickName;
                        Game.GameManager.avatarUrl = res.userInfo.avatarUrl;
                        Game.GameManager.matchVsInit();
                        Game.GameManager.getUserInfoBtn.hide();
                    });
                }
            });
        } else {
            this.nodeDict["start"].on("click", Game.GameManager.matchVsInit, Game.GameManager);
        }
    },

    onEnable() {
        if (Game.GameManager.getUserInfoBtn) {
            Game.GameManager.getUserInfoBtn.show();
        }
    },

    onDisable() {
        if (Game.GameManager.getUserInfoBtn) {
            Game.GameManager.getUserInfoBtn.hide();
        }
    }
});

初始化需要的几个参数在Matchvs官网注册即可得到.

 //Glb.js
 //--------
 channel: 'MatchVS',
    platform: 'alpha',
    gameId: 201554,
    gameVersion: 1,
    appKey: 'd4e29d00bd3a48e2acf4f6e7a5ffe270',
    secret: 'f0f7bd601d9f43db840091ac08a17002',

开始游戏,跳转场景uiGamePanel:

startGame: function() {
        console.log('-----startGame-----')
        if(this.isLoadGame) return;
        this.isLoadGame = true;
        this.readyCnt = 0;
        cc.director.loadScene('game', function() {
            clientEvent.dispatch(clientEvent.eventType.clearChess);
            uiFunc.openUI("uiGamePanel", function(panel) {
                panel.getComponent("uiGamePanel").timeLabelInit();

                this.sendReadyMsg();
            }.bind(this));
        }.bind(this));
    },

随机匹配和创建房间

使用CC创建大厅场景(uiLobbyPanel.fire)给用户选择匹配方式,创建匹配场景(uiMatching1v1.fire) 给用户反馈比配进度,与登录功能的实现步骤类似:写一个 uiMatching1v1.js脚本挂在到场景中的控件上.

uiMatching1v1.js

   randomRoom: function() {
        Game.GameManager.blockInput();

        GLB.matchType = GLB.RANDOM_MATCH; // 修改匹配方式为随机匹配
        console.log('开始随机匹配');
        if (GLB.gameType === GLB.COOPERATION) {
            if (GLB.MAX_PLAYER_COUNT > 1) {
                if (cc.Canvas.instance.designResolution.height > cc.Canvas.instance.designResolution.width) {
                    uiFunc.openUI("uiMatchingVer", function(obj) {
                        var matching = obj.getComponent("uiMatching");
                        matching.joinRandomRoom();
                    });
                } else {
                    uiFunc.openUI("uiMatching", function(obj) {
                        var matching = obj.getComponent("uiMatching");
                        matching.joinRandomRoom();
                    });
                }
            } else {
                cc.director.loadScene('game');
            }
        } else if (GLB.gameType === GLB.COMPETITION) {
            if (GLB.MAX_PLAYER_COUNT === 2) {
                if (cc.Canvas.instance.designResolution.height > cc.Canvas.instance.designResolution.width) {
                    uiFunc.openUI("uiMatching1v1Ver", function(obj) {
                        var matching = obj.getComponent("uiMatching1v1Ver");
                        matching.joinRandomRoom();
                    });
                } else {
                    uiFunc.openUI("uiMatching1v1", function(obj) {
                        var matching = obj.getComponent("uiMatching1v1");
                        matching.joinRandomRoom();
                    });
                }
            } else if (GLB.MAX_PLAYER_COUNT === 4) {
                if (cc.Canvas.instance.designResolution.height > cc.Canvas.instance.designResolution.width) {
                    uiFunc.openUI("uiMatching2v2Ver", function(obj) {
                        var matching = obj.getComponent("uiMatching2v2Ver");
                        matching.joinRandomRoom();
                    });
                } else {
                    uiFunc.openUI("uiMatching2v2Ver", function(obj) {
                        var matching = obj.getComponent("uiMatching2v2Ver");
                        matching.joinRandomRoom();
                    });
                }
            }
        }
    },

通过监听joinRoomResponse和joinRoomNotify匹配结果

uiMatchvsing1v1.js

joinRandomRoom: function() {

    var result = null;
    if (GLB.matchType === GLB.RANDOM_MATCH) {
        result = mvs.engine.joinRandomRoom(GLB.MAX_PLAYER_COUNT, '');
        if (result !== 0) {
            console.log('进入房间失败,错误码:' + result);
        }
    } else if (GLB.matchType === GLB.PROPERTY_MATCH) {
        var matchinfo = new mvs.MatchInfo();
        matchinfo.maxPlayer = GLB.MAX_PLAYER_COUNT;
        matchinfo.mode = 0;
        matchinfo.canWatch = 0;
        matchinfo.tags = GLB.tagsInfo;
        result = mvs.engine.joinRoomWithProperties(matchinfo, "joinRoomWithProperties");
        if (result !== 0) {
            console.log('进入房间失败,错误码:' + result);
        }
    }
},

监听进房间操作的服务器回复和房间玩家进出情况的消息:

joinRoomResponse: function(data) {
        if (data.status !== 200) {
            console.log('进入房间失败,异步回调错误码: ' + data.status);
        } else {
            console.log('进入房间成功');
            console.log('房间号: ' + data.roomInfo.roomID);
        }
        GLB.roomId = data.roomInfo.roomID;
        var userIds = [GLB.userInfo.id]
        console.log('房间用户: ' + userIds);

        var playerIcon = null;
        for (var j = 0; j < data.roomUserInfoList.length; j++) {
            playerIcon = this.playerIcons[j].getComponent('playerIcon');
            if (playerIcon && !playerIcon.userInfo) {
                playerIcon.setData(data.roomUserInfoList[j]);
                if (GLB.userInfo.id !== data.roomUserInfoList[j].userId) {
                    userIds.push(data.roomUserInfoList[j].userId);
                }
            }
        }

        for (var i = 0; i < this.playerIcons.length; i++) {
            playerIcon = this.playerIcons[i].getComponent('playerIcon');
            if (playerIcon && !playerIcon.userInfo) {
                playerIcon.setData(GLB.userInfo);
            }
        }
        GLB.playerUserIds = userIds;
        if (userIds.length >= GLB.MAX_PLAYER_COUNT) {
            var result = mvs.engine.joinOver("");
            console.log("发出关闭房间的通知");
            if (result !== 0) {
                console.log("关闭房间失败,错误码:", result);
            }

            GLB.playerUserIds = userIds;
        }
    },

    joinRoomNotify: function(data) {
        console.log("joinRoomNotify, roomUserInfo:" + JSON.stringify(data.roomUserInfo));
        var playerIcon = null;
        for (var j = 0; j < this.playerIcons.length; j++) {
            playerIcon = this.playerIcons[j].getComponent('playerIcon');
            if (playerIcon && !playerIcon.userInfo) {
                playerIcon.setData(data.roomUserInfo);
                break;
            }
        }

游戏同步与发布上线

还是按照上给你面的套路,新建场景(uiGamePanel.fire),挂在脚本(uiGamePanel.js).

攻击的动作使用Matchvs 的 sendEventEx发出,如回合开始播放动画:

roundStart () {
        console.log('------roundStart------')
        this.timeLabelInit();
        clearInterval(this.interval);
        this.playerFlag = GLB.PLAYER_FLAG.RED;
        // this.getTurn(this.playerFlag);
        user.init();
        this.headColorInit();
        clientEvent.dispatch(clientEvent.eventType.getMap);
        this.playReadyGo();
        this.setTimeNumFont();
        this.setHeadIcon();
    },

另一方的客户端收到后处理游戏中的各种事件消息;开发完成后, 再通过CC的一键发布微信小游戏功能上线微信。

 clientEvent.on(clientEvent.eventType.updateTime, this.updateTime, this);
        clientEvent.on(clientEvent.eventType.countTime, this.countTime, this);
        clientEvent.on(clientEvent.eventType.changeFlag, this.changeFlag, this);
        clientEvent.on(clientEvent.eventType.roundStart, this.roundStart, this);
        clientEvent.on(clientEvent.eventType.gameOver, this.gameOver, this);
        clientEvent.on(clientEvent.eventType.stopTimeWarnAnim, this.stopTimeWarnAnim, this);
点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
7个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这