var Remote = function (socket) {
var game;
var bindEvents = function () {
document.getElementById('left').onclick = function () {
game.left();
}
document.getElementById('down').onclick = function () {
game.down();
}
document.getElementById('right').onclick = function () {
game.right();
}
document.getElementById('rotate').onclick = function () {
game.rotate();
}
document.getElementById('fall').onclick = function () {
game.fall();
}
document.getElementById('fixed').onclick = function () {
game.fixed();
}
document.getElementById('performNext').onclick = function () {
game.performNext(2, 2);
}
document.getElementById('checkGameOver').onclick = function () {
game.checkGameOver();
}
document.getElementById('setTime').onclick = function () {
game.setTime(20);
}
document.getElementById('addScore').onclick = function () {
game.addScore(10);
}
document.getElementById('gameOver').onclick = function () {
game.gameOver(true);
}
document.getElementById('addBotLine').onclick = function () {
game.addBotLine([
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
]);
}
}
var start = function (type, dir) {
var doms = {
gameDiv: document.getElementById('remote_game'),
nextDiv: document.getElementById('remote_next'),
timeDiv: document.getElementById('remote_time'),
scoreDiv: document.getElementById('remote_score'),
resultDiv: document.getElementById('remote_gameover')
}
game = new Game();
game.init(doms, type, dir);
}
// 导出
this.start = start;
this.bindEvents = bindEvents;
}
创建wsServer.js文件
var app = require('HTTP').createServer();
var io = require('socket.io')(app);
var PORT = 3000;
// 客户端计数
var clientCount = 0;
// 保存客户端socket
var socketMap = {};
app.listen(PORT);
io.on('connection', function (socket) {
// 用户连接进来后先进行客户加1
clientCount++;
socket.clientNum = clientCount;
socketMap[clientCount] = socket;
// 是单数个进来的用户需要等待
if (clientCount % 2 == 1) {
// 发送wait消息
socket.emit('wait', 'waiting for another person');
} else {
socket.emit('start');
socketMap[(clientCount - 1)].emit('start');
}
socket.on('disconnect', function () {});
});
console.log('websocket listening on port' + PORT);
script.js中传入socket对象
var socket = io('ws://localhost:3000');
// 创建local对象并调用,传入socket对象
var local = new Local(socket);
var remote = new Remote(socket);
socket.on('waiting', function (str) {
document.getElementById('waiting').innerHTML = str;
});