0

tengo el siguiente código de JavaScript en el cual coloque un temporizador que se inicia al cargar la página, pero quiero que se detenga si se agota el tiempo y vuelva a iniciar cuando de al botón de "Jugar de nuevo" ya sea que haya perdido o ganado, espero alguien pueda ayudarme a solucionarlo en que debo agregar o en que estoy mal.

Soy algo nuevo en esto de JavaScript y aunque estuve agregando las funciones de comenzar y finalizar temporizador, no me dieron resultado. Solo deje el código que es funcional hasta el momento.

Código JavaScript:

var segundosInicio = 30;


window.onload = tiempo;

function tiempo() {

    document.getElementById('countdown').innerHTML = segundosInicio;
    if (segundosInicio == 0) {
        console.log('Final');

        Swal.fire({
            title: "¡Se te acabó el tiempo!",
            html: `<img class="img-fluid" src="../img/perdiste1.png" alt="Ganaste">`,
            confirmButtonText: "Jugar de nuevo",
        })
        for (var j = 0; j < piezas.length; j++) {
            piezas[j].setAttribute("x", Math.floor((Math.random() * 10) + 1));
            piezas[j].setAttribute("y", Math.floor((Math.random() * 409) + 1));
            piezas[i].setAttribute("onmousedown", "seleccionarElemento(evt)");
        }
    } else {
        segundosInicio -= 1;
        var ejecutar = setTimeout("tiempo()", 1000);
    }
}


var piezas = document.getElementsByClassName('movil');

var tamWidh = [134, 192, 134, 163, 134, 163, 134, 192, 134];
var tamHeight = [163, 134, 163, 134, 192, 134, 163, 134, 163];


for (var i = 0; i < piezas.length; i++) {
    piezas[i].setAttribute("width", tamWidh[i]);
    piezas[i].setAttribute("height", tamHeight[i]);
    piezas[i].setAttribute("x", Math.floor((Math.random() * 10) + 1));
    piezas[i].setAttribute("y", Math.floor((Math.random() * 409) + 1));
    piezas[i].setAttribute("onmousedown", "seleccionarElemento(evt)");
}

var elementSelect = 0;
var currentX = 0;
var currentY = 0;
var currentPosX = 0;
var currentPosY = 0;

function seleccionarElemento(evt) {
    elementSelect = reordenar(evt);
    currentX = evt.clientX;
    currentY = evt.clientY;
    currentPosx = parseFloat(elementSelect.getAttribute("x"));
    currentPosy = parseFloat(elementSelect.getAttribute("y"));
    elementSelect.setAttribute("onmousemove", "moverElemento(evt)");
}

function moverElemento(evt) {
    var dx = evt.clientX - currentX;
    var dy = evt.clientY - currentY;
    currentPosx = currentPosx + dx;
    currentPosy = currentPosy + dy;
    elementSelect.setAttribute("x", currentPosx);
    elementSelect.setAttribute("y", currentPosy);
    currentX = evt.clientX;
    currentY = evt.clientY;
    elementSelect.setAttribute("onmouseout", "deseleccionarElemento(evt)");
    elementSelect.setAttribute("onmouseup", "deseleccionarElemento(evt)");
    iman();
}

function deseleccionarElemento(evt) {
    testing();
    if (elementSelect != 0) {
        elementSelect.removeAttribute("onmousemove");
        elementSelect.removeAttribute("onmouseout");
        elementSelect.removeAttribute("onmouseup");
        elementSelect = 0;
    }
}

var entorno = document.getElementById('entorno');

function reordenar(evt) {
    var padre = evt.target.parentNode;
    var clone = padre.cloneNode(true);
    var id = padre.getAttribute("id");
    entorno.removeChild(document.getElementById(id));
    entorno.appendChild(clone);
    return entorno.lastChild.firstChild;
}

var origX = [200, 304, 466, 200, 333, 437, 200, 304, 466];
var origY = [100, 100, 100, 233, 204, 233, 337, 366, 337];

function iman() {
    for (var i = 0; i < piezas.length; i++) {
        if (Math.abs(currentPosx - origX[i]) < 15 && Math.abs(currentPosy - origY[i]) < 15) {
            elementSelect.setAttribute("x", origX[i]);
            elementSelect.setAttribute("y", origY[i]);
        }
    }
}


var win = document.getElementById("win");

function testing() {
    var bien_ubicada = 0;
    var padres = document.getElementsByClassName('padre');
    for (var i = 0; i < piezas.length; i++) {
        var posx = parseFloat(padres[i].firstChild.getAttribute("x"));
        var posy = parseFloat(padres[i].firstChild.getAttribute("y"));
        ide = padres[i].getAttribute("id");
        if (origX[ide] == posx && origY[ide] == posy) {
            bien_ubicada = bien_ubicada + 1;
            if (origX[ide] == posx && origY[ide] == posy) {


            }
        }
    }

    if (bien_ubicada == 9) {
        win.play();
        Swal.fire({
            title: "¡Grandioso. Has ganado!",
            html: `<img class="img-fluid" src="../img/premio.png" alt="Ganaste">`,
            confirmButtonText: "Jugar de nuevo",
        })
        for (var i = 0; i < piezas.length; i++) {
            piezas[i].setAttribute("x", Math.floor((Math.random() * 10) + 1));
            piezas[i].setAttribute("y", Math.floor((Math.random() * 409) + 1));
        }

    }

}

2 respuestas 2

2

Agrego un código que implementa la lógica: se detiene cuando el tiempo termina y se reinicia al presionar un botón:

const tiempoTotal = 5;
var   tiempoActual = tiempoTotal;
var timeout;


var ele = document.getElementById("countdown");


function tiempo(){

  if(tiempoActual == 0) {
    mostrarDialogo();
  }
  else {
    tiempoActual--;
    ele.innerHTML = tiempoActual;
    setTimeout(()=> tiempo(),1000);
  }
}


// iniciar el temporizador cuando carga la página
tiempo();


function reiniciarTemporizador(){
  tiempoActual = tiempoTotal;
  tiempo();
}

function mostrarDialogo(){

   Swal.fire({
            title: "¡Se te acabó el tiempo!",
            icon: "info",
            showCancelButton: true,
            confirmButtonText: 'Jugar de nuevo',
            cancelButtonText: 'cancelar'
        }
    ).then((result) => {
          if (result.value) {
             reiniciarTemporizador();
          }
     })
}
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
</head>
<body>

<label id="countdown"></label>

</body>
</html>

2
  • Tu código me esta ayudando, pero en el que yo tengo desde el mismo JavaScript me manda una ventana en la que presiono un botón y no esta incluido en el HTML como lo hiciste tu. La pregunta ahora es: ¿Cómo puedo cambiar ese botón "reiniciar" del HTML al JavaScript en la parte de "Swal.fire" donde esta "confirmButtonText: "Jugar de nuevo","?
    – freshman
    el 22 ago. 2020 a las 5:51
  • Modifiqué el ejemplo para incluir la demo con Swal.
    – Lobos
    el 22 ago. 2020 a las 15:12
2

Sweet Alert te permite usar promesas y devuelve verdadero solo cuando se hace clic en el botón, por lo que solo debes analizar el valor devuelto para saber qué hacer:

    Swal.fire({
        title: "¡Se te acabó el tiempo!",
        html: `<img class="img-fluid" src="../img/perdiste1.png" alt="Ganaste">`,
        confirmButtonText: "Jugar de nuevo",
    }).then(value => {
        if(!value) {
            // El clic no fue en el botón confirmar
            // Fin del juego
            return;
        }
        // Volver a empezar, supongo que esto es parte de la configuración de inicio            
        for (var j = 0; j < piezas.length; j++) {
            piezas[j].setAttribute("x", Math.floor((Math.random() * 10) + 1));
            piezas[j].setAttribute("y", Math.floor((Math.random() * 409) + 1));
            piezas[i].setAttribute("onmousedown", "seleccionarElemento(evt)");
        }
        // Reiniciar temporizador
        segundosInicio = 30;
        // ¡A jugar!
        setTimeout("tiempo()", 1000);
     });

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.