使用socket.set 和 socket.get 在存取玩家信息
socket.get('playerinfo', function (err, player) {
if(player == null) {
console.log("[new player]",data.name);
var player = new Player(socket, data);
}
else
{
console.log("[wait player visit again]",data.name);
socket.emit('error', "you have registered");
return ;
}
socket.set('playerinfo', player, function () {
usersWS.push(player);
console.log("[wait player numer]",usersWS.length);
//这在里如果玩家状态和数量满足要求就可以开始游戏了
Physic.CreatePhysicWorld(p1, p2);
//通知client 启动 游戏
…………..
}); //set
}); //get
}) //socket.on
转发 和处理 玩家的输入
socket.on('sync', function (data) {
socket.get('playerinfo', function (err, player) {
if(player != null) {
//var target = usersWS[i].socket;
var room = player.room;
for(var i=0;i<room.players.length;i++)
{
if(room.players[i].id ==player.id)
{
//console.log("this is msg from id:",room.players[i].id)
}
else
{
room.players[i].socket.emit('sync', data);
//console.log("send to id:",room.players[i].id)
}
//room.players[i].socket.emit('sync', data);
}
}//if
else
{
socket.emit('error',"no session");
}
}); //get
}); //socket.on
}); //Network.on
定义一个简单的玩家对象
function Player(socket, data)
{
var newplayer = {
socket: socket,
id: player_next_id++,
tankType: 0,
name: data.name,
isMain: data.isMain,
ip: socket.remoteAddress,
status: '未准备',
// isAI: false, room: null }; newplayer.proto = Player.prototype; return newplayer; }
定义一个游戏房间对象
function Room(title)
{
var newroom = {
id: room_next_id++,
is_in_game: false, // 判断改房间的游戏是否已经开始
players: [],
map: 0,
title: title,
game: null
};
room_list.push(newroom);
newroom.__proto__ = Room.prototype;
return newroom;
}
最后感言: 本人是新手,发篇文章互动一下实属不易。不周之处,还望高手轻点儿拍砖。