我正在写一个多人游戏。我想检查玩家是否离开了游戏室,这样他们就不会开始游戏,除非有两个人。 服务器
socket.on('disconnect', () => {
if (rooms.find('ownerName', nickname)) {
rooms.delete(nickname);
}
console.log(nickname, 'Disconnected!')
// Emit an event when a member leaves a room
rooms.array().forEach(o => {
for (let p of [o.players.array()]) {
console.log(p.nickname === nickname)
if (p[0].nickname === nickname) {
let roomInstance = rooms.get(o.ownerName);
if (roomInstance) {
roomInstance.players.delete(p[0].nickname);
const playersCount = roomInstance.players.size;
console.log('Emitting ' + `room player left ${o.ownerName}`)
return io.sockets.emit(`room player left ${o.ownerName}`, p.nickname, playersCount);
}
}
}
});
lobbyMembers.delete(nickname);
});
好的,当大厅路线的成员正在断开连接时,会发生断开连接事件 大堂前端:
<script type="text/javascript">
$(document).ready(function() {
const socket = io.connect();
let nickname = "<%= nickname %>"
socket.emit('new lobby member', nickname)
//TODO: If owner don't show button
$('#newRoomBtn').click(function(event) {
$('#newRoomBtn').fadeOut('fast');
socket.emit('new room', nickname);
});
socket.on('new room', owner => {
$("#gamesTable tr:last")
.after("<tr><th><%= rooms.size + 1 %></th><th>" + owner.nickname + `</th><th><a class="button" href="game/${owner.nickname}">join</a></th>`);
});
});
</script>
我想检查玩家是否正在与Room路线断开连接 房间前端:
<script type="text/javascript">
$(document).ready(function() {
const socket = io.connect();
let newRoomPlayerEvent = 'new room player <%= room.owner.nickname %>';
let roomPlayerLeft = 'room player left <%= room.owner.nickname %>';
const room = <%- JSON.stringify(room) %>
socket.emit('new room player', room, "<%= nickname %>")
socket.on(newRoomPlayerEvent, function(player, playersCount) {
const Heading = playersCount >= 2 ? "Press ready" : `Waiting for an opponent! (${playersCount})`
if (playersCount >= 2) $('#readyButton').fadeIn('slow');
$('.headingRoom').html(`<h2 class='headingRoom centered is-size-3'>${Heading}</h2>`);
});
socket.on(roomPlayerLeft, function(player, playersCount) {
console.log(player)
const Heading = playersCount >= 2 ? "Press ready" : `Waiting for an opponent! (${playersCount})`
if (playersCount < 2) $('#readyButton').fadeOut('slow');
if (playersCount <= 2) $('#readyButton').fadeIn('slow');
$('.headingRoom').html(`<h2 class='headingRoom centered is-size-3'>${Heading}</h2>`);
});
$('#readyButton').click(function() {
console.log(<%- JSON.stringify([...players.entries()].reduce((acc, val) => ((acc[val[0]] = val[1]), acc), {})) %>)
})
});
</script>