Unity3D Instance objects as pairs (Memory Game) by applying shuffle

3

I'm doing a memory game where you have to turn two equal cards to score points, otherwise the cards will turn around again.

I have been asked to randomly insert the letters in the form of a grid.

In my code I have a single prefab that instantiates me and just repeats it. To those repeated prefabs, it assigns a random texture, applying in turn the same name to compare if the two selected cards match.

So far so good, but I must make them be installed in pairs. Let's say: if you installed a black K, I must make sure that the pair of that black K is instanced. And in turn, that in the next game, do not repeat the images that I used in that specific game, applying some type of shuffling.

Has anyone encountered something like this?

    
asked by Pablo Palma 21.06.2016 в 00:13
source

1 answer

1

Here basically the problem is that we must guarantee that the cards in the grid are all pairs. We can use the following strategy to place them on the board

Being universoCartas a temporary collection with all the cards in our deck

for(int i =0; i < numCartasUnicas ; i++){ 
    //tomamos aleatoriamente una carta del universo
    carta = universoCartas.get(unRandom(universoCartas.length));
    universoCartas.remove(carta);
    //cartas al tablero
    seleccionCartas.add(carta); 
    seleccionCartas.add(carta.clone()); // y su pareja
}

Now that we have all the cards that will go on the board, we will use the same random trick to select what to put on the board

Currently we should have something like this:

{ G G B B E E C C A A H H } //identificando a cada carta con una letra

Now I guess you have a double cycle to put the cards in the form of a grid

for(int i =0; i < n; i++ ){
    for(int j=0 ; k < m; j++ ){
        carta = seleccionCartas.get(unRandom(seleccionCartas.length));
        seleccionCartas.remove(carta);
        ponerCarta(i,j , carta ) //donde  i y j son coordenas en el grid
    }
}

Note: The number of selected cards must be equal to n * m (grid size)

When removing from collections, we ensure that we do not repeat letters on our board

    
answered by 29.06.2016 в 16:21