этот раз,MatchvsМы предлагаем вам пошаговую казуальную игру с открытым исходным кодом. Оба игрока шлепаются и гоняются на доске 4X4 и следуют правилам пищевой цепи, В конце концов, тот, кто выживает на поле, становится победителем.
Сначала вам нужно скачать Cocos Creator и Matchvs JavaScript SDK. Этапы реализации этого игрового дизайна в основном разделены на три части: вход пользователя в систему, случайное сопоставление и создание комнаты, а также игра на одном экране.
Логин пользователя
Используйте Cocos Creator (далее CC) для создания сцены входа в игру.
Используйте CC, чтобы перетаскивать элементы управления, восстанавливать проект дизайна и полагаться на хороший рабочий процесс CC, так что эту часть работы может выполнить планировщик игры или дизайнер пользовательского интерфейса, а разработчику программы нужно только смонтировать соответствующий сценарий игровой логики в сцене.Например,кнопка входа висит на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();
},
Клиент другой стороны получает и обрабатывает различные сообщения о событиях в игре, после завершения разработки функция мини-игры WeChat будет запущена онлайн через функцию 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);