4

Tengo una aplicación integrada en Cordova que funciona moviendo los mosaicos para formar palabras. En el navegador se ve correctamente como puedes ver en el ejemplo que muestro código.

El problema surge cuando ejecuto la aplicación en un dispositivo, ya que como el bloque de letras es muy ancho, no se muestra completamente en la pantalla, lo que da una mala impresión al usuario. Vea la captura de pantalla.

Puede ver lo que estoy tratando de decir haciendo que el navegador sea muy estrecho o si tienen un complemento en el navegador para simular dispositivos.

introducir la descripción de la imagen aquí

En el dispositivo, esto se corrige girando el dispositivo horizontalmente, y se puede reproducir perfectamente, pero la primera impresión no es buena ya que no se puede ver todo el bloque de piezas.

introducir la descripción de la imagen aquí

Mi pregunta es si de alguna manera se puede lograr que al abrir la App se muestre el bloque completo en el dispositivo en posición Vertical, y luego rotar el dispositivo para jugar, pero que la primera impresión sea vertical y se muestre todo el código Cómo ¿Puedo conseguir esto?

¿Cómo puedo mostrar en la pantalla vertical y hacer que muestre todo el bloque de mosaicos?

¿Cómo ajustar la pantalla vertical y horizontal en un dispositivo?

EDITO LA PREGUNTA: Como bien me sugirió el usuario @PabloLozano , hice pruebas con CSS @media query, incluso he seguido dos cursos de CSS. Pero por más que lo intento, no consigo corregir el error y que la pagina se adapte al dispositivo móvil, lo más probable es que no este haciendo las cosas mal pero he probado con media query, con Grid y sigue sin funcionar.

 display: grid;
  grid-template-columns: auto auto auto;

Tambien he usado lo siguiente:

.cajon {
  display: grid;
  grid-auto-rows: 22rem;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
}

Sin embargo el bloque de letras sigue saliendo de la pantalla en dispositivos, como se ve en el código. ¿ Que estoy haciendo mal ?

var wordArr, mixedArr, // arrays that hold the original and jumbled letters
  timeLimit = 30 * 1000, // in millisec
  timeLeft,
  timeInt,
  currentTile, // updated when you pickup a tile
  emptySlot; // holds the X position of the empty slot


gsap.timeline() // set initial states
  .set('.app', { width: 900, height: '100%', background: '#333', left: '50%', x: '-50%', userSelect: 'none' })
  .set('.slot', { width: 112, height: 112, borderRadius: 20, background: 'rgba(60,250,60,0.8)', top: 50, left: 100, x: (i) => i * 118 })
  .set('.tile', { width: 100, height: 100, top: 56, left: 106, x: (i) => i * 118, color: 'rgba(20,10,10,0.8)', fontSize: 87, lineHeight: '104px', textAlign: 'center' })

  .set('.tileFront', { pointerEvents: 'none', width: 100, height: 100, borderRadius: 17, overflow: 'hidden', backgroundSize: 'cover', backgroundImage: 'url(images/fichasMio.png)' })
  .set('.tileShade', { pointerEvents: 'none', width: 100, height: 100, backgroundSize: 'cover', backgroundImage: 'url(images/fichas0.png)', y: 2, scale: 1.1, opacity: 0.8 })
  .set('.timeTxt', { left: 715, top: 200, fontSize: 34, opacity: 0 })
  .set('.timePlus', { left: 715, top: 240, fontSize: 24, opacity: 0 })
  .set('.playBtn', { left: 650, top: 200, fontSize: 32, lineHeight: '50px', backgroundColor: 'rgba(255,255,255,1)', color: '#565656', borderRadius: 9, width: 150, height: 50, textAlign: 'center', cursor: 'pointer', overflow: 'hidden' })
  .set('.playTxt', { width: '100%', userSelect: 'none' })
  .set('.correctHead', { left: 100, top: 200, fontSize: 34, opacity: 0 })
  .set('.correctList', { left: 100, top: 240, fontSize: 24, opacity: 0.6 })
  .set('#container', { opacity: 1 })


Draggable.create('.tile', { onPress: (t) => { pickup(t) }, onDrag: drag, onRelease: drop }); // make tiles draggable


$('.playBtn').on('click', () => { // event handlers for 'play' button (which becomes 'replay') 
  gsap.timeline({ defaults: { duration: 0.2 }, onComplete: deal })
    .to('.playBtn', { autoAlpha: 0 }, 0)
    .to('.correctHead, .timeTxt', { opacity: 1 })
})

$('.playBtn').on('mouseenter', () => {
  if (gsap.isTweening('.playTxt')) return;
  gsap.timeline({ defaults: { duration: 0.25 } })
    .to('.playTxt', { opacity: 0, y: -30, ease: 'back.in(4)' })
    .to('.playTxt', { duration: 0.001, y: 35 })
    .to('.playTxt', { opacity: 1, y: 0, ease: 'back.out' })
})


function deal() {
  wordArr = words.splice(gsap.utils.random(0, words.length - 1, 1), 1).toString().toUpperCase().split('') // pull a random word, convert to upper case, then separate chars into an array
  mixedArr = gsap.utils.shuffle(gsap.utils.shuffle(gsap.utils.shuffle([...wordArr]))) // create a second array and triple shuffle its contents

  gsap.timeline()
    .set('.tileFront', { innerHTML: (i) => mixedArr[i], userSelect: 'none' })
    .fromTo('.tile', { x: (i) => i * 118, opacity: 0 }, { duration: 0.1, opacity: 1, stagger: 0.06, ease: 'power1.inOut' }, 0)
    .fromTo('.tile', { y: 50, rotation: 0.05 }, { duration: 0.3, y: 0, rotation: 0, stagger: 0.06, ease: 'power4.out' }, 0)
    .to('.slot', { duration: 0.1, background: 'rgba(0,0,0,0.5)' }, 0)
    .call(function () {
      for (var i = 1; i <= 6; i++) Draggable.get('#t' + i).enable(); //enable tile dragging (disabled on correct answer + time-out)
      checkAnswer(); //check to see if any tiles are already in the correct slot
    }, null, 0.4);



  if (timeInt == undefined) { //start timer
    timeLeft = timeLimit;
    timeInt = setInterval(updateTime, 10);

    // clear correct answers (needed for replay)        
    $('.correctN').html(0);
    $('.correctList').html('');
  }
}


function pickup(t) { // on press, set vars and animate tile lifting up
  currentTile = t.target;
  emptySlot = gsap.getProperty(currentTile, 'x');
  gsap.timeline({ defaults: { duration: 0.2, overwrite: true, ease: 'power3.out' } })
    .to($(currentTile).children('.tileFront')[0], { scale: 1.1 }, 0)
    .to($(currentTile).children('.tileShade')[0], { y: 30, opacity: 0.4, scale: 1 }, 0)
}


function drag() {
  for (var i = 1; i <= 6; i++) { // loop through all 6 tiles...
    if (currentTile.id.substr(-1) != String(i)) { // and only hit-test against the other tiles
      var t = '#t' + i;
      if (!gsap.isTweening(t)) { // also, only hit-test when tile is stationary
        if (Draggable.hitTest(currentTile, t, 30)) { // if at least 30px are overlapping...
          gsap.timeline()
            .to(t, { duration: 0.1, y: () => gsap.getProperty(currentTile, 'y') < 0 ? 66 : -66, ease: 'slow(0.7,0.7)', repeat: 1, yoyo: true, zIndex: 100 }, 0)
            .to(t, { duration: 0.2, x: emptySlot, ease: 'power2.inOut' }, 0); // move tile to empty slot,

          emptySlot = gsap.getProperty(t, 'x'); // then update emptySlot
        }
      }
    }
  }
}


function drop() { // on release, put current tile in the empty slot
  gsap.timeline({ defaults: { duration: 0.1, overwrite: true, ease: 'power1.in' }, onComplete: () => { if (timeInt != undefined) checkAnswer() } })
    .to(currentTile, { x: emptySlot, y: 0 }, 0)
    .to($(currentTile).children('.tileFront')[0], { scale: 1 }, 0)
    .to($(currentTile).children('.tileShade')[0], { y: 2, opacity: 0.8, scale: 1.1 }, 0)
}


function checkAnswer() {
  var arr = new Array(600); // make an array with enough space to place each char at an index based on each tile's X position
  for (var i = 1; i <= 6; i++) arr.splice(gsap.getProperty('#t' + i, 'x'), 1, $('#t' + i).children('.tileFront').html()); // then populate that array

  for (var j = 0; j < 6; j++) { // turn correct slots green
    if (wordArr.join('').charAt(j) == arr.join('').charAt(j)) gsap.to('#s' + (j + 1), { duration: 0.33, ease: 'bounce.out', background: 'rgba(60,250,60,0.8)' });
    else gsap.to('#s' + (j + 1), { duration: 0.3, background: 'rgba(0,0,0,0.5)' });
  }

  if (wordArr.join('') == arr.join('')) { // compare original word and current answer by converting arrays to strings
    currentTile = emptySlot = undefined
    for (var i = 1; i <= 6; i++) Draggable.get('#t' + i).disable(); // disable all tiles

    var n = Number($('.correctN').html());
    $('.correctN').html(n += 1); // add to correct number tally
    $('.correctList').append(arr.join('') + '<br>'); // add to list of correct words

    timeLeft += 3000; // 3-sec bonus

    gsap.timeline({ onComplete: deal }) // success animation, then deal() new letter tiles
      .to('.timePlus', { duration: 0.1, opacity: 1, yoyo: true, repeat: 1, repeatDelay: 0.4 }, 0)
      .fromTo('.timePlus', { scale: 0, rotation: 0.1 }, { duration: 0.3, scale: 1, rotation: 0, ease: 'back.out(3)' }, 0)
      .to('.slot', { duration: 0.2, background: 'rgba(0,0,0,0.5)', overwrite: true }, 0)
      .to('.tile', { duration: 0.35, scale: 1.16, ease: 'back.inOut(7)' }, 0.1)
      .to('.tile', { duration: 0.2, opacity: 0, scale: 1, ease: 'power1.inOut' }, 0.8)
  }
}


function updateTime() {
  if (timeLeft > 0) {
    timeLeft -= 10;
    var mil = Math.floor(timeLeft % 1000 / 10);
    var sec = Math.floor(timeLeft / 1000);
    if (mil < 10) mil = "0" + mil;
    if (sec < 10) sec = "0" + sec;
    var t = sec + ":" + mil;
    gsap.set('.timeTxt', { innerHTML: t });
  }

  else { // Game over
    clearInterval(timeInt);
    timeInt = currentTile = emptySlot = undefined;

    for (var i = 1; i <= 6; i++) Draggable.get('#t' + i).disable(); // disable all tiles

    gsap.timeline({ defaults: { duration: 0.001, overwrite: true } })
      // auto-solve the last word
      .to('.slot', { duration: 0.2, ease: 'power1.inOut', background: 'rgba(60,250,60,0.8)' }, 0)
      .to('.tile', { scale: 1, y: 0, x: (i) => i * 118 }, 0.1)
      .to('.tileFront', { scale: 1, innerHTML: (i) => wordArr[i], userSelect: 'none' }, 0.1)
      .to('.tileShade', { y: 2, opacity: 0.8, scale: 1.1 }, 0.1)
      // hide timer + display replay button
      .to('.timeTxt', { duration: 0.3, opacity: 0 }, 0)
      .to('.playTxt', { duration: 0.3, innerHTML: 'Replay', userSelect: 'none' }, 0)
      .to('.playBtn', { duration: 0.3, autoAlpha: 1, ease: 'power1.inOut' }, 0.3)
  }
}
html, body, #container {
  /* display: grid;
  grid-template-columns: auto auto auto; */
  display:block; float:left;
  width:100%;
  height:100%;
  background:#444;
  color:#fff;
  font-family: 'Signika Negative', sans-serif;
  overflow:hidden;

} 
div {
  /* display: grid;
  grid-template-columns: auto auto auto; */
  position: absolute; 
} 

/* .cajon {
  display: grid;
  grid-auto-rows: 22rem;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
} */
 


/* html, body, div #container {
  width:100%;
  height:100%;
  display: grid;
  grid-auto-rows: 22rem ;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
  color: rgb(82, 72, 72);
} */

/* Escritorio extra grande 
/* @media only screen and (min-width: 1200px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}
/ Escritorio grande 
@media only screen and (min-width: 992px) and (max-width: 1199px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}

/Escritorio pequeño / tablet 
@media only screen and (min-width: 768px) and (max-width: 991px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}

Tablets y phablets 
@media only screen and (min-width: 576px) and (max-width: 767px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}

 Teléfonos 
@media only screen and (max-width: 575px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
 
} */

@media only screen and (max-width: 600px) {
  .app .slot {
    grid-template-columns: auto;
  }
}

@media only screen and (max-width: 300px) {
  .app .slot {
    grid-template-columns: auto;
  }
}

@media only screen and (max-width: 300px) {

  .tile {
    grid-template-columns: auto;
  }
}
<html>
<head>
  <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">
  <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
  <meta name="color-scheme" content="light dark">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.1/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.1/Draggable.min.js"></script>
  <script src="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@600&amp;display=swap"></script>
  <link rel="stylesheet" href="css/encuentra.css">
  <title>Encuentra las Palbras</title>
</head>

<body>

  <form action="index.html">
    <button class="button secondary-button ">Menu</button>
  </form>
  <div id="container" style="opacity:0">

    <div class="app">

      <div class="timeTxt">30:00</div>
      <div class="timePlus">+3 sec</div>
      <div class="playBtn">
        <div class="playTxt">Play</div>
      </div>

      <div class="correctHead">Correct: <span class="correctN">0</span></div>
      <div class="correctList"></div>

      <div class="slot" id="s1"></div>
      <div class="slot" id="s2"></div>
      <div class="slot" id="s3"></div>
      <div class="slot" id="s4"></div>
      <div class="slot" id="s5"></div>
      <div class="slot" id="s6"></div>

      <div class="tile" id="t1">
        <div class="tileShade"></div>
        <div class="tileFront">M</div>
      </div>
      <div class="tile" id="t2">
        <div class="tileShade"></div>
        <div class="tileFront">I</div>
      </div>
      <div class="tile" id="t3">
        <div class="tileShade"></div>
        <div class="tileFront">X</div>
      </div>
      <div class="tile" id="t4">
        <div class="tileShade"></div>
        <div class="tileFront"><img width="100" height="100"
            src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIBAMAAABfdrOtAAAAJFBMVEUAAABHcEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADmfSdFAAAADHRSTlPMAMCvnBx0M2BLC4rujjL5AAAErklEQVR4Ae3ahY/jRhQG8Cfb8l0U0VPioMDFJcFiSVCmVOQtVxSXW1Fd5ub4xHtMIpeZuX9c0er6azzezOzMlOYJD3/rz/DGnkdsoRziEIc45B+KOMQhDnGIQxziEIc45L3cAtJesYH4iQWEFmwglNpAAhsIbdhA6JgNJLSB0MgG4icWEFqwgVBqAwlmQQZ33/3O3e888GEuRXz4zttU1MYMSPviotbWfshmesafvnFt9eKLYyrKO7Yz0qLt8n/Y2bgQE2GFcgjR5Uk9MXiQpusLSYSCWiX6kirKT+SQeiX6nCprThahMBci+0lQ+2QRccd7mkTVlEbox2rjIxLXSBrxsiqjG9cg/j5JRNAmxlRT84kEIr7y3xYLeOz1SO2VHy3XIRusgNCc6MoSX1wSiOD4+1RXqSQiOJRJnbHAiggeSq/O8BNVBA9lqw65nndEeo/+UT99vYyHkgjvQ/+Obx999ADeVGIEq4u94hr+szax5/ye5JCKOiaF8KD0lIUVwnVUqqtwIXElyyGMfe+LytM+z4AEuSzCUfln3stFPQU9DZGUpRH8obPi+JahPQGywAoI30nbtchcOsXFGQDEz1QQOMnNqZskyBEZsRoy/Gs2UVy+FgAJWQnB5nTZdvjFfQeId0wZ6UBe8GxMEdlgZYS3F1d+Do+UkAEJeBdIG46kJWjKbUp3g/By+ZyMS8cFSINVEWy1+6AlXoan7pgqgr3WZ+a3RGvRASsjcBXvgasg0PVRDbtlimlpQrAT+tiujmlGeDKdVpN1I+0irR52Y71IFE+llelCIK85eO6HrAuBvPZBWisGkCgOsLlnBhCeLDLzMqalHRkeg85yvRGEIS0vMYYswxLMCAJpmUIgLVPIANIyhAyhuRtCtvB9TT+CaTXYEAJpGUIgrdwUEsWQlhmkDWl19xlBJpBWa49uBNIq1hO+dgTSKlZfX+hGIK1iPdHQj3QJ08JnpCakBWn18I7UhYwxLXwSa0L6kNYfqy8v14zgS0kPu6MuBF9KNrFz6UHgpaS0Vs20IpuYVvW6vp+znrdfgrVqoHOyoFOdFtEXGicLJpBWJPwisaCK4Glv4qVGqbbJgi34qgaXQYhIkCsi8IHwGP7G1PeuK1WRMaaF3/L8BBDvmBryNuErHOZFe3VMFsAH86xiW2NDw2TBuGpnC7YwfwTEz+SRZwjSqtqY8J4sI9SQRu6q3naIYvj9b3Y1WfAKlash3D65LZGdLIju/qNeeOkrgton3gi65IkX7n4bP1HVI62LPS+OPeGGpmBLS3WyACudeU8rVEaaErtzP6oiqcQ+o5+oIaHUjumcGjJ1MgfX1Sn7VJA5YVPWMFmAG1cSgY3kkVS85NMzWSBueN1lMbI3kUSaws4ca5ssCDIW1bsiZcRyiLhvixXZyQJvH9fV+8ui20QC8esN5u6X1XeVBLKU8U41uBDvarJg/Yd8plG1h1cB+WKWyYKjv9a5c+deeA6IuopeOnv0hPxkgXwN4Wo0PKK4weaRILeApGweabB5xE8sINezeSRk84h3zAKyweaRJltAUgtIg80jncwC0s3NI1gOcYhDHOIQhzjEIQ5xiEMc4hDj9Qv4E/e/tIWihwAAAABJRU5ErkJggg==">
        </div>
      <div class="tile" id="t5">
        <div class="tileShade"></div>
        <div class="tileFront">U</div>
      </div>
      <div class="tile" id="t6">
        <div class="tileShade"></div>
        <div class="tileFront">P</div>
      </div>
      </div>
    </div>
</body>

</html>

5
  • 4
    Puedes usar @media (max-width: 600px) { ...} para declarar estilos cuando las pantallas son estrechas, busca información sobre "CSS media query" el 1 dic. 2021 a las 9:14
  • Gracias por su consejo @PabloLozano . He seguido algún curso de CSS para tratar de entender las media querys, pero no consigo hacerlo funcionar. Seguramente no haya entendido el funcionamiento correcto o me este confundiendo en algo, pero no funciona. Revise mi código si es tan amable y me diga que hago mal. Gracias
    – juan José
    el 13 dic. 2021 a las 8:07
  • 1
    Creo que el problema es porque estás usando posiciones absolutas; los recuadros salen del flujo de despliegue, no importa si es grid, flex u otro y, además, primero deberías solucionar solo con CSS y después intentar hacer los efectos con Javascript.
    – Triby
    el 14 dic. 2021 a las 18:24
  • 1
    El problema no está en el estilo CSS. Ni siquiera magia no ara una mejora en CSS porque en el script se declaran muchos estilos, en gsap.timeline(). Haz el ajuste o cambio en esos .set para ver qué tal el 14 dic. 2021 a las 18:27
  • Ya imagino @Trby, el problema es que si no utilizo position: absolute las fichas de letras se descolocan por toda la pantalla. Respecto a js, gsap.timeline() , no se como modificarlo, como dice Narciso Aifuz ese puede ser el problema. Ese código no es mio
    – juan José
    el 14 dic. 2021 a las 20:13

2 respuestas 2

0

Usas una anchura de app de 900, lo que se refiere en pixels. Un dispositivo normal tiene menos de 500px de anchura [1]. Para poder usar lo mismo código en muchas diferentes dispositivos, una opción es de utilizar anchura tipo vw en donde 1vw es 1 porcentaje de anchura de pantalla.

Para hacer las letras en quadrados, no se si sera posible usar lo mismo vw para definir también altura...otra opción es hacerlos tan pequeños que caben en anchura de pantalla sin ningún pixel entre letras y quando hay mas espació, lo añades entre letras con método vw. La idea en último caso sera de hacerlo funcionar primero con la pantalla mas pequeño y aumentarlo en algún manera para ver bien en los mas grandes también.

Aunque parece loco de dar el valor vw para altura, lo sera lo más fácil para hacer quadrados. Puede ser difícil sin esta manera cumplir las dos cosas: Caber en pantalla y aún tener objetos quadrados en algún proporción de los limites dados.


Fuentes de información:

[1] https://worship.agency/mobile-screen-sizes-for-2021

[2] https://greensock.com/forums/topic/24585-update-height-property-of-tween-when-resizing-window/

1
  • Gracias @mico , ya me dijeron que el problema estaba en js y estoy buscando la manera de corregir esto. Estudiare tu idea, pero el problema es que no se como hacerlo para que cambie de tamaño cuando giro el dispositivo horizontal .
    – juan José
    el 15 dic. 2021 a las 20:18
0

Puedes aplicar

display:block; float:left;

y dejar de usar el

display:grid;

De la siguiente manera:

var wordArr, mixedArr, // arrays that hold the original and jumbled letters
  timeLimit = 30 * 1000, // in millisec
  timeLeft,
  timeInt,
  currentTile, // updated when you pickup a tile
  emptySlot; // holds the X position of the empty slot


gsap.timeline() // set initial states
  .set('.app', { width: 900, height: '100%', background: '#333', left: '50%', x: '-50%', userSelect: 'none' })
  .set('.slot', { width: 112, height: 112, borderRadius: 20, background: 'rgba(60,250,60,0.8)', top: 50, left: 100, x: (i) => i * 118 })
  .set('.tile', { width: 100, height: 100, top: 56, left: 106, x: (i) => i * 118, color: 'rgba(20,10,10,0.8)', fontSize: 87, lineHeight: '104px', textAlign: 'center' })

  .set('.tileFront', { pointerEvents: 'none', width: 100, height: 100, borderRadius: 17, overflow: 'hidden', backgroundSize: 'cover', backgroundImage: 'url(images/fichasMio.png)' })
  .set('.tileShade', { pointerEvents: 'none', width: 100, height: 100, backgroundSize: 'cover', backgroundImage: 'url(images/fichas0.png)', y: 2, scale: 1.1, opacity: 0.8 })
  .set('.timeTxt', { left: 715, top: 200, fontSize: 34, opacity: 0 })
  .set('.timePlus', { left: 715, top: 240, fontSize: 24, opacity: 0 })
  .set('.playBtn', { left: 650, top: 200, fontSize: 32, lineHeight: '50px', backgroundColor: 'rgba(255,255,255,1)', color: '#565656', borderRadius: 9, width: 150, height: 50, textAlign: 'center', cursor: 'pointer', overflow: 'hidden' })
  .set('.playTxt', { width: '100%', userSelect: 'none' })
  .set('.correctHead', { left: 100, top: 200, fontSize: 34, opacity: 0 })
  .set('.correctList', { left: 100, top: 240, fontSize: 24, opacity: 0.6 })
  .set('#container', { opacity: 1 })


Draggable.create('.tile', { onPress: (t) => { pickup(t) }, onDrag: drag, onRelease: drop }); // make tiles draggable


$('.playBtn').on('click', () => { // event handlers for 'play' button (which becomes 'replay') 
  gsap.timeline({ defaults: { duration: 0.2 }, onComplete: deal })
    .to('.playBtn', { autoAlpha: 0 }, 0)
    .to('.correctHead, .timeTxt', { opacity: 1 })
})

$('.playBtn').on('mouseenter', () => {
  if (gsap.isTweening('.playTxt')) return;
  gsap.timeline({ defaults: { duration: 0.25 } })
    .to('.playTxt', { opacity: 0, y: -30, ease: 'back.in(4)' })
    .to('.playTxt', { duration: 0.001, y: 35 })
    .to('.playTxt', { opacity: 1, y: 0, ease: 'back.out' })
})


function deal() {
  wordArr = words.splice(gsap.utils.random(0, words.length - 1, 1), 1).toString().toUpperCase().split('') // pull a random word, convert to upper case, then separate chars into an array
  mixedArr = gsap.utils.shuffle(gsap.utils.shuffle(gsap.utils.shuffle([...wordArr]))) // create a second array and triple shuffle its contents

  gsap.timeline()
    .set('.tileFront', { innerHTML: (i) => mixedArr[i], userSelect: 'none' })
    .fromTo('.tile', { x: (i) => i * 118, opacity: 0 }, { duration: 0.1, opacity: 1, stagger: 0.06, ease: 'power1.inOut' }, 0)
    .fromTo('.tile', { y: 50, rotation: 0.05 }, { duration: 0.3, y: 0, rotation: 0, stagger: 0.06, ease: 'power4.out' }, 0)
    .to('.slot', { duration: 0.1, background: 'rgba(0,0,0,0.5)' }, 0)
    .call(function () {
      for (var i = 1; i <= 6; i++) Draggable.get('#t' + i).enable(); //enable tile dragging (disabled on correct answer + time-out)
      checkAnswer(); //check to see if any tiles are already in the correct slot
    }, null, 0.4);



  if (timeInt == undefined) { //start timer
    timeLeft = timeLimit;
    timeInt = setInterval(updateTime, 10);

    // clear correct answers (needed for replay)        
    $('.correctN').html(0);
    $('.correctList').html('');
  }
}


function pickup(t) { // on press, set vars and animate tile lifting up
  currentTile = t.target;
  emptySlot = gsap.getProperty(currentTile, 'x');
  gsap.timeline({ defaults: { duration: 0.2, overwrite: true, ease: 'power3.out' } })
    .to($(currentTile).children('.tileFront')[0], { scale: 1.1 }, 0)
    .to($(currentTile).children('.tileShade')[0], { y: 30, opacity: 0.4, scale: 1 }, 0)
}


function drag() {
  for (var i = 1; i <= 6; i++) { // loop through all 6 tiles...
    if (currentTile.id.substr(-1) != String(i)) { // and only hit-test against the other tiles
      var t = '#t' + i;
      if (!gsap.isTweening(t)) { // also, only hit-test when tile is stationary
        if (Draggable.hitTest(currentTile, t, 30)) { // if at least 30px are overlapping...
          gsap.timeline()
            .to(t, { duration: 0.1, y: () => gsap.getProperty(currentTile, 'y') < 0 ? 66 : -66, ease: 'slow(0.7,0.7)', repeat: 1, yoyo: true, zIndex: 100 }, 0)
            .to(t, { duration: 0.2, x: emptySlot, ease: 'power2.inOut' }, 0); // move tile to empty slot,

          emptySlot = gsap.getProperty(t, 'x'); // then update emptySlot
        }
      }
    }
  }
}


function drop() { // on release, put current tile in the empty slot
  gsap.timeline({ defaults: { duration: 0.1, overwrite: true, ease: 'power1.in' }, onComplete: () => { if (timeInt != undefined) checkAnswer() } })
    .to(currentTile, { x: emptySlot, y: 0 }, 0)
    .to($(currentTile).children('.tileFront')[0], { scale: 1 }, 0)
    .to($(currentTile).children('.tileShade')[0], { y: 2, opacity: 0.8, scale: 1.1 }, 0)
}


function checkAnswer() {
  var arr = new Array(600); // make an array with enough space to place each char at an index based on each tile's X position
  for (var i = 1; i <= 6; i++) arr.splice(gsap.getProperty('#t' + i, 'x'), 1, $('#t' + i).children('.tileFront').html()); // then populate that array

  for (var j = 0; j < 6; j++) { // turn correct slots green
    if (wordArr.join('').charAt(j) == arr.join('').charAt(j)) gsap.to('#s' + (j + 1), { duration: 0.33, ease: 'bounce.out', background: 'rgba(60,250,60,0.8)' });
    else gsap.to('#s' + (j + 1), { duration: 0.3, background: 'rgba(0,0,0,0.5)' });
  }

  if (wordArr.join('') == arr.join('')) { // compare original word and current answer by converting arrays to strings
    currentTile = emptySlot = undefined
    for (var i = 1; i <= 6; i++) Draggable.get('#t' + i).disable(); // disable all tiles

    var n = Number($('.correctN').html());
    $('.correctN').html(n += 1); // add to correct number tally
    $('.correctList').append(arr.join('') + '<br>'); // add to list of correct words

    timeLeft += 3000; // 3-sec bonus

    gsap.timeline({ onComplete: deal }) // success animation, then deal() new letter tiles
      .to('.timePlus', { duration: 0.1, opacity: 1, yoyo: true, repeat: 1, repeatDelay: 0.4 }, 0)
      .fromTo('.timePlus', { scale: 0, rotation: 0.1 }, { duration: 0.3, scale: 1, rotation: 0, ease: 'back.out(3)' }, 0)
      .to('.slot', { duration: 0.2, background: 'rgba(0,0,0,0.5)', overwrite: true }, 0)
      .to('.tile', { duration: 0.35, scale: 1.16, ease: 'back.inOut(7)' }, 0.1)
      .to('.tile', { duration: 0.2, opacity: 0, scale: 1, ease: 'power1.inOut' }, 0.8)
  }
}


function updateTime() {
  if (timeLeft > 0) {
    timeLeft -= 10;
    var mil = Math.floor(timeLeft % 1000 / 10);
    var sec = Math.floor(timeLeft / 1000);
    if (mil < 10) mil = "0" + mil;
    if (sec < 10) sec = "0" + sec;
    var t = sec + ":" + mil;
    gsap.set('.timeTxt', { innerHTML: t });
  }

  else { // Game over
    clearInterval(timeInt);
    timeInt = currentTile = emptySlot = undefined;

    for (var i = 1; i <= 6; i++) Draggable.get('#t' + i).disable(); // disable all tiles

    gsap.timeline({ defaults: { duration: 0.001, overwrite: true } })
      // auto-solve the last word
      .to('.slot', { duration: 0.2, ease: 'power1.inOut', background: 'rgba(60,250,60,0.8)' }, 0)
      .to('.tile', { scale: 1, y: 0, x: (i) => i * 118 }, 0.1)
      .to('.tileFront', { scale: 1, innerHTML: (i) => wordArr[i], userSelect: 'none' }, 0.1)
      .to('.tileShade', { y: 2, opacity: 0.8, scale: 1.1 }, 0.1)
      // hide timer + display replay button
      .to('.timeTxt', { duration: 0.3, opacity: 0 }, 0)
      .to('.playTxt', { duration: 0.3, innerHTML: 'Replay', userSelect: 'none' }, 0)
      .to('.playBtn', { duration: 0.3, autoAlpha: 1, ease: 'power1.inOut' }, 0.3)
  }
}
html, body, #container {
  /* display: grid;
  grid-template-columns: auto auto auto; */
  display:grid;
  width:100%;
  height:100%;
  background:#444;
  color:#fff;
  font-family: 'Signika Negative', sans-serif;
  overflow:hidden;

} 
div {
  /* display: grid;
  grid-template-columns: auto auto auto; */
  position: absolute; 
} 

/* .cajon {
  display: grid;
  grid-auto-rows: 22rem;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
} */
 


/* html, body, div #container {
  width:100%;
  height:100%;
  display: grid;
  grid-auto-rows: 22rem ;
  grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
  color: rgb(82, 72, 72);
} */

/* Escritorio extra grande 
/* @media only screen and (min-width: 1200px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}
/ Escritorio grande 
@media only screen and (min-width: 992px) and (max-width: 1199px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}

/Escritorio pequeño / tablet 
@media only screen and (min-width: 768px) and (max-width: 991px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}

Tablets y phablets 
@media only screen and (min-width: 576px) and (max-width: 767px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
  div { position: absolute; } 
}

 Teléfonos 
@media only screen and (max-width: 575px){
  html, body, #container {
    width:100%;
    height:100%;
    background:#444;
    color:#fff;
    font-family: 'Signika Negative', sans-serif;
    overflow:hidden;
  } 
 
} */

@media only screen and (max-width: 600px) {
  .app .slot {
    grid-template-columns: auto;
  }
}

@media only screen and (max-width: 300px) {
  .app .slot {
    grid-template-columns: auto;
  }
}

@media only screen and (max-width: 300px) {

  .tile {
    grid-template-columns: auto;
  }
}
<html>
<head>
  <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">
  <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
  <meta name="color-scheme" content="light dark">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.1/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.1/Draggable.min.js"></script>
  <script src="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@600&amp;display=swap"></script>
  <link rel="stylesheet" href="css/encuentra.css">
  <title>Encuentra las Palbras</title>
</head>

<body>

  <form action="index.html">
    <button class="button secondary-button ">Menu</button>
  </form>
  <div id="container" style="opacity:0">

    <div class="app">

      <div class="timeTxt">30:00</div>
      <div class="timePlus">+3 sec</div>
      <div class="playBtn">
        <div class="playTxt">Play</div>
      </div>

      <div class="correctHead">Correct: <span class="correctN">0</span></div>
      <div class="correctList"></div>

      <div class="slot" id="s1"></div>
      <div class="slot" id="s2"></div>
      <div class="slot" id="s3"></div>
      <div class="slot" id="s4"></div>
      <div class="slot" id="s5"></div>
      <div class="slot" id="s6"></div>

      <div class="tile" id="t1">
        <div class="tileShade"></div>
        <div class="tileFront">M</div>
      </div>
      <div class="tile" id="t2">
        <div class="tileShade"></div>
        <div class="tileFront">I</div>
      </div>
      <div class="tile" id="t3">
        <div class="tileShade"></div>
        <div class="tileFront">X</div>
      </div>
      <div class="tile" id="t4">
        <div class="tileShade"></div>
        <div class="tileFront"><img width="100" height="100"
            src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIBAMAAABfdrOtAAAAJFBMVEUAAABHcEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADmfSdFAAAADHRSTlPMAMCvnBx0M2BLC4rujjL5AAAErklEQVR4Ae3ahY/jRhQG8Cfb8l0U0VPioMDFJcFiSVCmVOQtVxSXW1Fd5ub4xHtMIpeZuX9c0er6azzezOzMlOYJD3/rz/DGnkdsoRziEIc45B+KOMQhDnGIQxziEIc45L3cAtJesYH4iQWEFmwglNpAAhsIbdhA6JgNJLSB0MgG4icWEFqwgVBqAwlmQQZ33/3O3e888GEuRXz4zttU1MYMSPviotbWfshmesafvnFt9eKLYyrKO7Yz0qLt8n/Y2bgQE2GFcgjR5Uk9MXiQpusLSYSCWiX6kirKT+SQeiX6nCprThahMBci+0lQ+2QRccd7mkTVlEbox2rjIxLXSBrxsiqjG9cg/j5JRNAmxlRT84kEIr7y3xYLeOz1SO2VHy3XIRusgNCc6MoSX1wSiOD4+1RXqSQiOJRJnbHAiggeSq/O8BNVBA9lqw65nndEeo/+UT99vYyHkgjvQ/+Obx999ADeVGIEq4u94hr+szax5/ye5JCKOiaF8KD0lIUVwnVUqqtwIXElyyGMfe+LytM+z4AEuSzCUfln3stFPQU9DZGUpRH8obPi+JahPQGywAoI30nbtchcOsXFGQDEz1QQOMnNqZskyBEZsRoy/Gs2UVy+FgAJWQnB5nTZdvjFfQeId0wZ6UBe8GxMEdlgZYS3F1d+Do+UkAEJeBdIG46kJWjKbUp3g/By+ZyMS8cFSINVEWy1+6AlXoan7pgqgr3WZ+a3RGvRASsjcBXvgasg0PVRDbtlimlpQrAT+tiujmlGeDKdVpN1I+0irR52Y71IFE+llelCIK85eO6HrAuBvPZBWisGkCgOsLlnBhCeLDLzMqalHRkeg85yvRGEIS0vMYYswxLMCAJpmUIgLVPIANIyhAyhuRtCtvB9TT+CaTXYEAJpGUIgrdwUEsWQlhmkDWl19xlBJpBWa49uBNIq1hO+dgTSKlZfX+hGIK1iPdHQj3QJ08JnpCakBWn18I7UhYwxLXwSa0L6kNYfqy8v14zgS0kPu6MuBF9KNrFz6UHgpaS0Vs20IpuYVvW6vp+znrdfgrVqoHOyoFOdFtEXGicLJpBWJPwisaCK4Glv4qVGqbbJgi34qgaXQYhIkCsi8IHwGP7G1PeuK1WRMaaF3/L8BBDvmBryNuErHOZFe3VMFsAH86xiW2NDw2TBuGpnC7YwfwTEz+SRZwjSqtqY8J4sI9SQRu6q3naIYvj9b3Y1WfAKlash3D65LZGdLIju/qNeeOkrgton3gi65IkX7n4bP1HVI62LPS+OPeGGpmBLS3WyACudeU8rVEaaErtzP6oiqcQ+o5+oIaHUjumcGjJ1MgfX1Sn7VJA5YVPWMFmAG1cSgY3kkVS85NMzWSBueN1lMbI3kUSaws4ca5ssCDIW1bsiZcRyiLhvixXZyQJvH9fV+8ui20QC8esN5u6X1XeVBLKU8U41uBDvarJg/Yd8plG1h1cB+WKWyYKjv9a5c+deeA6IuopeOnv0hPxkgXwN4Wo0PKK4weaRILeApGweabB5xE8sINezeSRk84h3zAKyweaRJltAUgtIg80jncwC0s3NI1gOcYhDHOIQhzjEIQ5xiEMc4hDj9Qv4E/e/tIWihwAAAABJRU5ErkJggg==">
        </div>
      <div class="tile" id="t5">
        <div class="tileShade"></div>
        <div class="tileFront">U</div>
      </div>
      <div class="tile" id="t6">
        <div class="tileShade"></div>
        <div class="tileFront">P</div>
      </div>
      </div>
    </div>
</body>

</html>

1
  • 1
    Gracias @LaFortuna por detalle, pero eso no funciona. Puede comprobarlo usted mismo ya que añadi el fragmento de código a mi ejemplo.
    – juan José
    el 14 dic. 2021 a las 17:46

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.