Hello,
i wan’t to make a prototype of a memory game. I got 20 cards. Each of them should pair to a random other card. The clue is, that the cards cannot be chosen twice. So if card number 4 matches with card 17, both of them should not be available for other cards to pair. Hope this is understandable. The Idea is to make have the same objects in the grid, but with each round, the pairs are different.
Can someone help me out here? I tried some stuff but couldn’t figure it out on my own.
Thanks!
I got it figured out somehow. A bit messy but it works quite well.
Here for those who may need it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pairing : MonoBehaviour
{
public List<int> randomList = new List<int>();
public List<int> partnerList = new List<int>();
public Dictionary<int, int> pairs = new Dictionary<int, int>();
private void Start()
{
GenerateRandom();
}
private void GenerateRandom()
{
for(int i = 0; i < 10; i++)
{
int value = Random.Range(1, 21);
Debug.Log("Random created: " + value);
while(randomList.Contains(value))
{
Debug.Log("Random Value already exists: " + value + " Generating new!");
value = Random.Range(1, 21);
Debug.Log("New Value generated: " + value);
}
if(randomList.Contains(value) == false)
{
randomList.Add(value);
Debug.Log("Added Value " + value + " to Random list");
}
}
GeneratePairs();
}
private void GeneratePairs()
{
foreach(int random in randomList)
{
int partner = Random.Range(1, 21);
Debug.Log("Partner Value created: " + partner);
while(partner == random || randomList.Contains(partner) || partnerList.Contains(partner))
{
Debug.Log("Partner Value already exists");
partner = Random.Range(1, 21);
Debug.Log("New Value generated: " + partner);
}
if(partner != random && randomList.Contains(partner) == false && partnerList.Contains(partner) == false)
{
partnerList.Add(partner);
Debug.Log("Added Value: " + partner + " to Partner List");
}
}
FillDictionary();
}
private void FillDictionary()
{
for(int entry = 0; entry < randomList.Count; entry++)
{
pairs.Add(randomList[entry], partnerList[entry]);
}
foreach(KeyValuePair<int, int> pair in pairs)
{
Debug.Log("Dictionary entry created: " + pair);
}
}
}