class Sala { constructor(juego, url) { this.juego = juego; this.url = url; this.timer = null; this.conexion = new Conexion(url, this); this.usuarios = {}; // Usuarios en la sala } poner_away(quien) { $('#jugador_' + quien + ' .away').show(); $('#partido_' + quien + ' .away').show(); $('#nombre_' + quien + ' .away').show(); } quitar_away(quien) { $('#jugador_' + quien + ' .away').hide(); $('#partido_' + quien + ' .away').hide(); $('#nombre_' + quien + ' .away').hide(); } borrar_usuario(usuario) { delete this.usuarios[usuario]; $('#jugador_' + usuario).remove(); this.actualizar_numero('jugadores'); } crear_usuario(jugador) { if (this.usuarios[jugador.nombre]) { this.borrar_usuario(jugador.nombre); } this.usuarios[jugador.nombre] = jugador; const disabled = this.buscar_partidos(jugador.nombre).length > 0 || jugador.nombre == this.juego.jugador.nombre ? 'disabled = "disabled"' : ''; $('#jugadores').append(`
  • ` + jugador.mostrar_jugador() + `
  • `); this.actualizar_numero('jugadores'); } // Busca partidos en juego en los que participe el usuario buscar_partidos(quien) { let partidos = $('li[id="partido_' + quien + '"], li[id^="partido_' + quien + '-"], li[id^="partido_"][id$="-' + quien + '"]'); let partidosFiltrados = []; // Nueva matriz para almacenar los elementos filtrados $.each(partidos, function(index, partido) { let id = partido.id.substring('partido_'.length); // Divide la cadena en dos partes separadas por el guion bajo let jugadores = id.split('-'); // Verifica si ninguna de las partes está vacía if (jugadores[0] && jugadores[1]) { // Si ambos jugadores están presentes, agrega el partido a la nueva matriz partidosFiltrados.push(partido); } }); return partidosFiltrados; } habilitar_sala(habilitar) { if (habilitar) { $('#boton_nuevo').show(); $('#boton_cancelar').hide(); bootbox.hideAll(); this.juego.rival = null; } else { $('#boton_nuevo').hide(); $('#boton_cancelar').show(); } const partidos = $('li[id^="partido_"]'); partidos.get().forEach(p => { const id = p.id.substring("partido_".length).split('-'); if (id[0] != this.juego.jugador.nombre && (id.length == 1 || id[1] != this.juego.jugador.nombre)) { $(p).find("button").prop("disabled", !habilitar); } }); const jugadores = $('li[id^="jugador_"]'); jugadores.get().forEach(j => { const jugador = j.id.substring("jugador_".length); let jugando = this.buscar_partidos(jugador).length > 0; if (jugador != this.juego.jugador.nombre) { $(j).find("button").prop("disabled", jugando || !habilitar); } }); } nuevo_partido(duracion, usuario1 /*opcional*/, usuario2 /*opcional*/) { var disabled = this.juego.rival || this.juego.jugador.nombre == usuario1 || this.juego.jugador.nombre == usuario2 ? 'disabled = "disabled"' : ''; const join = ''; const id = "partido_" + (usuario1 || '') + (usuario1 && usuario2 ? '-' : '') + (usuario2 || ''); var s = '
  • ' + (usuario1 ? this.usuarios[usuario1].mostrar_jugador() : join); s += ' vs ' + (usuario2 ? this.usuarios[usuario2].mostrar_jugador() : join); if (duracion) { s += ' timer' + duracion + ' min'; } if (usuario1 && usuario2) { // Si el partido ha empezado... s += ' '; } s += '
  • '; $('#partidos').append(s); this.actualizar_numero('partidos'); // Deshabilito usuarios if (usuario1) { $('#jugador_' + usuario1 + ' button').prop('disabled', true); } if (usuario2) { $('#jugador_' + usuario2 + ' button').prop('disabled', true); } } usuario_desconectado(usuario) { this.borrar_partido('partido_' + usuario); if (this.juego.rival && usuario == this.juego.rival.nombre) { $('#finalizar').prop('disabled', true); $('#finalizar').text('???msg.waitingOpponent???'); $('#boton_cancelar').show(); $('#boton_cancelar').prop('disabled', false); this.juego.escribir_servidor(usuario, '???connection.disconnected???'.toLowerCase()); clearInterval(this.juego.timer); this.juego.timer = null; } this.borrar_usuario(usuario); } // El partido se ha aceptado -> empezar (tanto blancas como negras) aceptar_partido(c, duracion, rival) { if (rival == '_Bot_') { this.juego.crear_bot(); } else { this.juego.rival = this.usuarios[rival]; this.informar_partido(duracion, c == 'blancas' ? this.juego.jugador.nombre : rival, c == 'negras' ? this.juego.jugador.nombre : rival); } this.habilitar_sala(false); this.juego.empezar(c, duracion); } // Un partido cualquiera se ha iniciado -> informar informar_partido(duracion, usuario1, usuario2) { this.borrar_partido('partido_' + usuario1); this.borrar_partido('partido_' + usuario2); this.nuevo_partido(duracion, usuario1, usuario2); } borrar_partido(id) { $('#' + id).remove(); this.actualizar_numero('partidos'); } // Partido cancelado finalizar_partido(id) { this.borrar_partido(id); clearInterval(this.juego.timer); this.juego.timer = null; } nuevo_observador(quien) { this.juego.escribir_servidor(quien, '???msg.enteredGame???'); } actualizar_numero(id) { const num = $('#' + id + ' li').length; $('#num_' + id).text(num); } opciones_partido(usuario, bot, color, duracion, titulo, disabled, funcionOK, funcionKO) { bootbox.confirm({ title: '' + (disabled ? 'help' : 'settings') + ' ' + titulo, backdrop: true, closeButton: false, message: '
    ' + (bot ? '
    \
    \ ???room.rival???\
    \
    \
    \ \ \
    \
    \ \ \
    \
    \
    ' : '') + '
    \
    \ ???room.color???\
    \
    \
    \ \ \
    \
    \ \ \
    \
    \
    \
    \ ???room.duration???\
    \
    \
    \ \ \
    \
    \ \ \
    \
    \ \ \
    \
    \ \ \
    \
    \ \ \
    \
    \
    \
    ', locale: 'en', swapButtonOrder: true, buttons: { confirm: { className: 'button verde' }, cancel: { className: 'button rojo' } }, callback: (result) => { if (result) { funcionOK($('input[name="bot"]:checked').val(), $('input[name="color"]:checked').val(), $('input[name="duracion"]:checked').val()); } else if (funcionKO) { funcionKO(); } }, onShow: function (e) { // Si está solo, marco el bot por defecto if ($('#num_jugadores').text() == 1) { $('#bot').attr('checked', true); } } }); } // { color, duracion, rival } partido_privado(resp) { if (!this.juego.rival) { this.juego.rival = this.usuarios[resp.rival]; this.opciones_partido(resp.rival, false, resp.color, resp.duracion, '???room.invitationFrom??? '.replace('{0}', resp.rival), 'disabled="disabled "', () => { // Aceptar partido this.partido_click(resp.rival); }, () => { this.conexion.enviar('cancelar_invitacion', resp.rival); }); } } nuevo_usuario(jugador) { this.crear_usuario(jugador); if (this.juego.rival && jugador.nombre == this.juego.rival.nombre) { this.juego.escribir_servidor(jugador.nombre, '???msg.enteredGame???'); $('#boton_cancelar').hide(); this.juego.actualizar_texto_turno(); this.juego.iniciar_cronometros(); } } vaciar_sala() { $('li[id^="partido_"]').remove(); $('li[id^="jugador_"]').remove(); this.usuarios = {}; this.actualizar_numero('jugadores'); this.actualizar_numero('partidos'); } // Entra a la sala por primera vez o tras terminar un partido actualizar_sala(jugadores, partidos) { this.vaciar_sala(); jugadores.forEach(j => { this.nuevo_usuario(new Jugador(j, this.juego)); }); partidos.forEach(p => { const indice = p.indexOf(','); const duracion = p.substring(0, indice); const jugs = p.substring(indice + 1).split("-"); this.nuevo_partido(duracion, jugs[0], jugs[1]); }); this.habilitar_sala(true); } /** SONIDO **/ sonido() { let sonido = obtenerCookie("sonido"); return sonido == null ? true : sonido == 'true'; } mostrar_sonido() { if (this.sonido()) { $('#boton_sonido span').text('check'); } else { $('#boton_sonido span').text('close'); } } toggle_sonido() { crearCookie('sonido', !this.sonido(), Number.MAX_SAFE_INTEGER); } /** ACCIONES RECIBIDAS DEL SERVIDOR **/ // { jugadores, partidos, jugador, rival, color } accion_conexion_abierta(resp) { // Si la sesión ha caducado el nombre no coincidirá if (resp.jugador != '') { location.reload(); } $('.bootbox.modal').modal('hide'); this.actualizar_sala(resp.jugadores, resp.partidos); this.juego.rival = this.usuarios[resp.rival]; this.juego.color = resp.color; // Si el partido ya se ha iniciado, pido la lista de movimientos (como si aceptara el partido otra vez) // Lo hacemos así para que se cree cada cosa a su tiempo if (resp.rival) { this.conexion.enviar('aceptar_partido', resp.rival); } } accion_nuevo_usuario(jugador) { this.nuevo_usuario(new Jugador(jugador, this.juego)); } accion_invitacion_cancelada(quien) { let mio = (quien == this.juego.jugador.nombre || this.juego.rival && quien == this.juego.rival.nombre); const partido = $('li[id="partido_' + quien + '"], li[id^="partido_' + quien + '-"], li[id^="partido_"][id$="-' + quien + '"]'); if (partido.length > 0) { if (mio) { this.finalizar_partido(partido.attr('id')); this.habilitar_sala(true); } else { // Si el partido es de otro habilitamos la sala o no en función de si tenemos una invitación pendiente this.borrar_partido(partido.attr('id')); this.habilitar_sala($('#boton_nuevo').is(':visible')); } } else if (mio) { this.habilitar_sala(true); } } /** EVENTOS **/ nuevo_click() { this.opciones_partido(null, true, 'blancas', 20, '???room.newGame???', '', (bot, color, duracion) => { if (bot) { this.conexion.enviar('partido_privado', color + ',' + duracion + ',' + this.juego.jugador.nombre); } else { this.conexion.enviar('crear_partido', color + ',' + duracion); } this.habilitar_sala(false); }, null); } // El propio usuario cancelar_click() { this.conexion.enviar('cancelar_invitacion', this.juego.jugador.nombre); this.habilitar_sala(true); } invitar_click(usuario) { this.juego.rival = this.usuarios[usuario]; this.opciones_partido(usuario, false, 'blancas', 20, '???room.newGame??? ???room.against??? ' + usuario + '', '', (bot, color, duracion) => { this.conexion.enviar('partido_privado', color + ',' + duracion + ',' + usuario); this.borrar_partido('partido_' + this.juego.jugador.nombre); this.habilitar_sala(false); }, () => { this.juego.rival = null; }); } partido_click(usuario) { this.conexion.enviar('aceptar_partido', usuario); } tab_click(tab) { $('.nav-tabs a[href="#' + tab + '"] span').text(''); if (tab == 'tab_chat') { setTimeout(() => { $('#texto').focus(); }, 10); } } }