Ejercicio: Adición de funcionalidad de botón a los botones de los jugadores

Completado

Esta aplicación web no será útil si el entrenador no puede tomar una decisión sobre qué jugadores deben tomarse un descanso para beber y cuáles deben salir a la cancha. Ahora que el entrenador puede ver el valor de PER de cada jugador durante el primer cuarto del partido, queremos ayudarle a visualizar cuál sería el promedio de PER de una alineación inicial según cómo elija mover a los jugadores entre la cancha y el banquillo.

Escritura de funcionalidad para mover a los jugadores

En esta unidad se rellena la función movePlayer():

// This function is called each time a player button is selected. A player
// button being selected indicates that the player either is moving to the
// court or moving to the bench for a water break.
function movePlayer() {

}

Pero, primero, queremos asegurarnos de que el entrenador no realiza cambios en los jugadores durante un cuarto del partido. Aunque en un partido de baloncesto real esto no supone ningún problema, en esta versión solo tenemos estadísticas de PER del inicio de cada cuarto del partido, por lo que queremos limitar la funcionalidad.

    // Don't let the coach change players during a quarter.
    if(quarterInPlay) {
        return;
    }

Podemos usar la estructura HTML para averiguar dónde está actualmente el jugador: en el banquillo o en la cancha. Sabemos que los botones se colocaron inicialmente en un div con el identificador playersOnBench. Podemos empezar por probar si el jugador está actualmente en el banquillo, lo que significa que el entrenador está intentando mover al jugador a la cancha.

    // Get the div in which this button currently is (either bench or court).
    var parentDiv = this.parentElement;

    // Check whether the player is currently on the bench.
    if(parentDiv.id == 'playersOnBench') {

En la instrucción if, es necesario realizar una comprobación antes de hacer nada más: Solo puede haber cinco jugadores en la cancha al mismo tiempo, por lo que queremos asegurarnos de que el entrenador no intente agregar más jugadores. En este caso, simplemente avisaremos al entrenador de que en este momento lo que no se permite es agregar más jugadores, no mover al jugador.

        // If there are already five players on the court, don't let the player
        // move to the court; alert the coach that there are enough players.
        if(playersOnCourt >= maxPlayersOnCourt){
            alert('You can only have ' + maxPlayersOnCourt + ' players on the court at a time.');
        }

Si hay espacio en la cancha para el jugador, nos interesa hacer algunas cosas en el código:

  1. Aumentar el número de jugadores en la cancha
  2. Obtener el valor de PER del jugador en el cuarto de partido actual
  3. Calcular el promedio de PER de todos los jugadores que están actualmente en la cancha
  4. Actualizar el valor de PER actual de la cancha
  5. Mover al jugador a la cancha
        else {
            // If there is room on the court, update the number of players on
            // the court, and update the average PER for the quarter based on
            // this player moving to the court.
            playersOnCourt++;
            quarterPER += playerMap.get(this.id)[currentQuarter];
            quarterAvePER = quarterPER / playersOnCourt;
            document.getElementById('currentPER').innerText = 'Current PER: '+ quarterAvePER;
            
            // Move the player to the court
            document.getElementById('playersOnCourt').appendChild(this);
        }

Después, queremos ayudar al entrenador a mover a los jugadores del banquillo a la cancha. Podemos incluir estos pasos en una instrucción else porque solo hay dos lugares en los que puede estar un jugador: la cancha o el banquillo. Por lo tanto, realizaremos algunas acciones en la instrucción else que crearemos a continuación:

  1. Disminuir el número de jugadores en la cancha
  2. Calcular el valor de PER de los jugadores que quedan en la cancha (si no queda ninguno, lo estableceremos en 0)
  3. Mostrar el valor de PER al entrenador
  4. Mover al jugador al banquillo
    } else {
        // If the player is being taken off the court for a water break, decrement
        // the number of players on the bench and remove the player's PER from the
        // average.
        playersOnCourt--;

        if(playersOnCourt != 0) {
            quarterPER -= playerMap.get(this.id)[currentQuarter];
            quarterAvePER = quarterPER / playersOnCourt;
        } else {
            // If there are no more players on the court, set the values to 0.
            quarterPER = 0;
            quarterAvePER = 0;
        }

        // Update the PER average. This might result in a zero value if your team is particularly tired.
        document.getElementById('currentPER').innerText = 'Current PER: '+ quarterAvePER;

        // Move the player to the bench.
        document.getElementById('playersOnBench').appendChild(this);
    }

Revisión del código movePlayers final

La función movePlayer() completa debe tener un aspecto similar al de este código:

// This function is called each time a player button is selected. A player's
// button being selected indicates that the player either moving to the
// court or moving to the bench for a water break.
function movePlayer() {
    // Don't let the coach change players during a quarter.
    if(quarterInPlay) {
        return;
    }

    // Get the div where this button currently is (either bench or court).
    var parentDiv = this.parentElement;

    // Check whether the player is currently on the bench.
    if(parentDiv.id == 'playersOnBench') {
        // If there are already five players on the court, don't let the player
        // move to the court, and alert the coach that there are enough players.
        if(playersOnCourt >= maxPlayersOnCourt){
            alert('You can only have ' + maxPlayersOnCourt + ' players on the court at a time.');
        } else {
            // If there is room on the court, update the number of players on
            // the court, and update the average PER for the quarter based on
            // this player moving to the court.
            playersOnCourt++;
            quarterPER += playerMap.get(this.id)[currentQuarter];
            quarterAvePER = quarterPER / playersOnCourt;
            document.getElementById('currentPER').innerText = 'Current PER: '+ quarterAvePER.toPrecision(4);
            
            // Move the player to the court.
            document.getElementById('playersOnCourt').appendChild(this);
        }
    } else {
        // If the player is being taken off the court for a water break, decrement
        // the number of players on the bench and remove the player's PER from the
        // average.
        playersOnCourt--;

        if(playersOnCourt != 0) {
            quarterPER -= playerMap.get(this.id)[currentQuarter];
            quarterAvePER = quarterPER / playersOnCourt;
        } else {
            // If there are no more players on the court, set the values to 0.
            quarterPER = 0;
            quarterAvePER = 0;
        }

        // Update the PER average. This might result in a zero value if your team is particularly tired.
        document.getElementById('currentPER').innerText = 'Current PER: '+ quarterAvePER.toPrecision(4);

        // Move the player to the bench.
        document.getElementById('playersOnBench').appendChild(this);
    }
}

Prueba de la funcionalidad para mover jugadores

Ahora puede actualizar la aplicación web local en el explorador y probar la funcionalidad que ha creado. Debería poder seleccionar hasta cinco reproductores que se encuentren en el banquillo y moverlos a la cancha:

Screenshot that shows moving players to the court.

Debe probar esta funcionalidad:

  • Intente agregar más de cinco jugadores a la cancha y asegúrese de que aparece una alerta.
  • Agregue jugadores a la cancha y, luego, muévalos de nuevo al banquillo.
  • Asegúrese de que el promedio de PER de los jugadores en la cancha sea preciso en función de las estadísticas de los jugadores durante un cuarto del partido específico.

© 2021 Warner Bros. Ent. Todos los derechos reservados