If you're seeing this message, it means we're having trouble loading external resources on our website.

Si estás detrás de un filtro de páginas web, por favor asegúrate de que los dominios *.kastatic.org y *.kasandbox.org estén desbloqueados.

Contenido principal

Juego de memoria: hacer puntos y ganar

¡Nuestro juego de "Memoria" está casi completo! Solo le falta una cosa: la puntuación. Aquí está un recordatorio de esa parte de las reglas del juego:
El objetivo del juego es conseguir todas las fichas volteadas boca arriba (es decir, encontrar todos los pares de imágenes que coincidan) en el menor número de intentos. Eso significa que el menor número de intentos es una mejor puntuación.
¿Cómo hacemos un seguimiento del número de intentos? Bueno, un "intento" es cada vez que volteas dos fichas, que corresponde a nuestro bloque if que revisa flippedTiles.length === 2. Podemos agregar una nueva variable global, numTries, que incrementamos dentro de esa condición.
if (flippedTiles.length === 2) {
  numTries++;
  ...
}
Queremos mostrar la puntuación cuando el juego termine, cuando el jugador haya hecho coincidir todas las fichas. ¿Cómo revisamos eso? Puedo pensar en dos opciones:
  1. Iterar a través de nuestro arreglo de fichas y revisar si isMatch es true para todas.
  2. Utilizar una variable global para realizar un seguimiento de cuántas coincidencias encontró el jugador, y después revisar si ha obtenido el número total de posibles coincidencias.
Tuvimos un debate similar antes, y escogí la opción en donde no tenemos que iterar a través de todo el arreglo cada vez. Vamos a escoger eso otra vez, la opción 2.
Primero inicializamos numMatches a 0, en el mismo lugar donde inicializamos todas nuestras variables globales del estado del juego:
var numMatches = 0;
Luego, dentro del bloque if para las fichas que coinciden, incrementamos la variable numMatches:
if (flippedTiles[0].face === flippedTiles[1].face) {
  flippedTiles[0].isMatch = true;
  flippedTiles[1].isMatch = true;
  flippedTiles.length = 0;
  numMatches++;
}
Al final de nuestra función draw, revisamos si el jugador ha encontrado todas las coincidencias y luego mostramos un texto de felicitación al usuario:
if (numMatches === tiles.length/2) {
  fill(0, 0, 0);
  text("¡Los encontraste todos en " + numTries + " intentos",
       20, 360);
}
Puedes probarlo a continuación, pero puedes tardarte un poco en ganar (sin ofender, por supuesto, ¡yo también me tardo!).
Aquí va un consejo para cuando estás probando partes de tu juego que son difíciles de alcanzar: modifica tu juego de forma temporal de modo que sea más rápido llegar allí. Por ejemplo, en este juego, cambiar NUM_ROWS y NUM_COLS a que sean números más pequeños, y podrás terminar mucho más rápido. Ahora, ¡intenta eso a continuación!

¿Quieres unirte a la conversación?

  • Avatar orange juice squid orange style para el usuario Sara
    Primer paso del desafío
    Asignarle los valores a las variables globales:
    var playerTurn = 0;
    var NUM_COLS = 3;
    var NUM_ROWS = 3;
    var SYMBOLS = ["O","X"];

    Segundo paso del desafío
    Saber cuando el mouse está dentro de una casilla:
    Tile.prototype.handleMouseClick = function(x, y) {
    // Check for mouse clicks inside the tile
    if(x >= this.x && x <= this.x + this.size &&
    y >= this.y && y <= this.y + this.size)
    {
    this.onClick();
    }
    };

    Tercer paso del desafío

    Tile.prototype.onClick = function() {
    // If the tile is not empty, exit the function
    if(!this.empty()){
    return;
    }
    // Put the player's symbol on the tile
    this.label = SYMBOLS[playerTurn];

    // Change the turn
    playerTurn++;
    if(playerTurn >= SYMBOLS.length){
    playerTurn = 0;
    }
    };

    si no entiendes una parte dime y si te sirvió dale un voto
    (22 votos)
    Avatar Default Khan Academy avatar para el usuario
  • Avatar winston baby style para el usuario gerardo😅😅😅😅😅
    gracias por divertirme un rato
    (5 votos)
    Avatar Default Khan Academy avatar para el usuario
  • Avatar marcimus red style para el usuario Daniela Muñoz
    no se que hacer en este desafío alguna idea es el desafío del gato llegue a la tercera parte y me sale esto el método onClick solo debe ignorar las tiradas inválidas sobre las casillas que no están vacías, pero parece que tu método está haciendo otra cosa
    var playerTurn=0;
    var NUM_COLS=3;
    var NUM_ROWS=3;
    var SYMBOLS=["X","O"];

    var tiles = [];

    var checkWin = function() {

    };

    var Tile = function(x, y) {
    this.x = x;
    this.y = y;
    this.size = width/NUM_COLS;
    this.label = "";
    };

    Tile.prototype.draw = function() {
    fill(214, 247, 202);
    strokeWeight(2);
    rect(this.x, this.y, this.size, this.size, 10);
    textSize(100);
    textAlign(CENTER, CENTER);
    fill(0, 0, 0);
    text(this.label, this.x+this.size/2, this.y+this.size/2);
    };

    Tile.prototype.empty = function() {
    return this.label === "";
    };

    Tile.prototype.onClick = function() {
    if (!this.empty()) {
    Tile.draw();
    }
    this.label = SYMBOLS[playerTurn];
    playerTurn++ ;
    if ( playerTurn >= SYMBOLS.length) {
    playerTurn = 0;
    }

    // If the tile is not empty, exit the function
    // Put the player's symbol on the tile
    // Change the turn
    };
    Tile.prototype.handleMouseClick = function(x, y) {
    if(x >= this.x && x <=this.x +this.size &&
    y >=this.y && y <=this.y +this.size )
    {
    this.onClick();
    }
    };
    // Check for mouse clicks inside the tile
    for (var i = 0; i < NUM_COLS; i++) {
    for (var j = 0; j < NUM_ROWS; j++) {
    tiles.push(new Tile(i * (width/NUM_COLS-1), j * (height/NUM_ROWS-1)));
    }
    }

    var drawTiles = function() {
    for (var i in tiles) {
    tiles[i].draw();
    }
    };

    mouseReleased = function() {
    for (var i in tiles) {
    tiles[i].handleMouseClick(mouseX, mouseY);
    }
    };

    draw = function() {
    background(143, 143, 143);
    drawTiles();
    };
    (4 votos)
    Avatar Default Khan Academy avatar para el usuario
  • Avatar male robot hal style para el usuario diego bustillo
    ¿alguien sabe que debe haber en la ultima variable del paso 1?
    (2 votos)
    Avatar Default Khan Academy avatar para el usuario
  • Avatar blobby green style para el usuario Evangy
    me ayudab me quede atascado en el segundo paso del desafio
    (2 votos)
    Avatar Default Khan Academy avatar para el usuario
  • Avatar hopper cool style para el usuario SJAH10
    me quede atascada ene el tercer paso del desafió alguien podría ayudarme
    (2 votos)
    Avatar Default Khan Academy avatar para el usuario
  • Avatar starky tree style para el usuario dulio.alcantar
    dame todos los puntos de todas los puntos
    (1 voto)
    Avatar Default Khan Academy avatar para el usuario
¿Sabes inglés? Haz clic aquí para ver más discusiones en el sitio en inglés de Khan Academy.