Player IDs v7 - nodeGame/nodegame GitHub Wiki
- status: complete
- version: 7.x
- follows from: Player List
To exchange messages between players or between a logic and a player, it is necessary to know the id of the recipient of a message.
The own id is available under:
node.player.id
By default, the list of players' objects is available only to the logic and stored in a PlayerList object under: node.game.pl
.
If players need to get the IDs of other players in the same game room, there are the following possibilities.
Every incoming message contains the ID of the sender under msg.from
.
node.on.data('INCOMING_MSG', function(msg) {
var idOfSender = msg.from;
// Reply "Thanks".
node.say('THANKS', idOfSender);
});
Note: to send a message to the logic, the alias "SERVER" can be used as a recipient's id.
Use the Matcher API to share the ID of a partner (currently the API supports only matching players in pairs). The ID of a player's partner is stored under:
node.game.partner
Adjust the channel configuration to notify players of each others connections.
notify: {
// When a player connects / disconnects.
onConnect: true,
}
The list of players will then be available under node.game.pl, as in logic.
This setting is safe in lab experiments, but it should be used with caution in online experiments.
This is the most flexible option for sharing the IDs, but requires some code on both logic and players.
logic
// Get the ids of all players.
let ids = node.game.pl.id.getAllKeys();
ids.forEach(function(idx, i) {
// Send the other ids to each player.
node.say('PARTNERS', idx, ids.slice(0,i).concat(ids.slice(i+1));
});
player
node.on.data('PARTNERS', function(msg) {
// Store a reference to the ids for later use.
node.game.partners = msg.data;
});
New players connecting to a game room will trigger a "PCONNECT" event on the logic.
node.on.pconnect(function(player) {
var idOfConnectingClient = player.id;
console.log('Somebody connected: ', idOfConnectingClient);
});
Note: players that are placed in a room at creation will not trigger the "PCONNECT" event.
Similarly, the id of disconnecting and reconnecting players is available through the "PDISCONNECT" and "PRECONNECT" events.
node.on.pdisconnect(function(player) {
var idOfDisconnectedClient = player.id;
console.log('Somebody disconnected: ', idOfDisconnectedClient);
});
node.on.preconnect(function(player) {
var idOfReconnectingClient = player.id;
console.log('Somebody reconnected: ', idOfReconnectingClient);
});
The logic has access to the channel registry.
// IDs of all clients (logics, monitors, bots, players) ever connected to any room in the the channel.
channel.registry.getIds();
// IDs of all players (bots and players) ever connected to any room in the channel.
channel.registry.clients.player.getAllKeys();