2014-01-12 2 views
0

WPF에서 간단한 "쌍"게임을 만들고 있습니다. MainWindow에 12 개의 이미지 컨트롤이 있습니다. 내가해야 할 일은 OpenFileDialog를 사용하여 여러 개의 이미지를 선택하고 (모두 6 개 미만일 수 있음) 이미지 컨트롤에 무작위로 배치하는 것입니다. 각 그림은 두 번 나타나야합니다. 어떻게이 일을 성취 할 수 있습니까? 나는 잠시 동안 여기에 갇혀 있으며 지금은 다음 코드 만 가지고있다. 솔루션을 요구하지 않고,이를 처리하는 방법에 대한 몇 가지 지침 만 필요합니다. 고맙습니다.무작위로 여러 이미지 컨트롤에 이미지 배치

> public ObservableCollection<Image> GetImages() 
    { 
     OpenFileDialog dlg = new OpenFileDialog(); 
     dlg.Multiselect = true; 

     ObservableCollection<Image> imagesList = new ObservableCollection<Image>(); 

     if (dlg.ShowDialog() == true) 
     { 
      foreach (String img in dlg.FileNames) 
      { 
       Image image = new Image(); 

       image.Name = ""; 
       image.Location = img; 
       imagesList.Add(image); 
      } 
     } 
     return imagesList; 
    } 
+0

기본 아이디어 : 대화 상자에서 파일 이름을 가져 와서 두 번 (!)을 목록에 넣습니다 (* fileList *라고 부름). 이제 이미지를 생성하는 루프를 실행하십시오. 루프에서 0 ~ * fileList.Count-1 * 범위의 난수를 생성하십시오. * fileList *에서 각 파일 이름 요소를 가져 와서 이미지를 만들고 * fileList *에서 해당 요소를 제거합니다. * fileList *가 비게되면 루프가 끝납니다. – elgonzo

+0

시도해보십시오. 팁 고마워. – cvenko

답변

0

필요한 결과를 얻는 방법은 여러 가지가 있습니다. 좋은 방법은 string 파일 경로의 컬렉션을 반환하는의 Directory.GetFiles method을 사용하는 것입니다 :

string [] filePaths = Directory.GetFiles(targetDirectory); 

그런 다음 컬렉션의 순서를 randomise하는 방법을 사용할 수 있습니다. DotNETPerls에 C# Shuffle Array 페이지에서 :

public string[] RandomizeStrings(string[] arr) 
{ 
    List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>(); 
    // Add all strings from array 
    // Add new random int each time 
    foreach (string s in arr) 
    { 
     list.Add(new KeyValuePair<int, string>(_random.Next(), s)); 
    } 
    // Sort the list by the random number 
    var sorted = from item in list 
      orderby item.Key 
      select item; 
    // Allocate new string array 
    string[] result = new string[arr.Length]; 
    // Copy values to array 
    int index = 0; 
    foreach (KeyValuePair<int, string> pair in sorted) 
    { 
     result[index] = pair.Value; 
     index++; 
    } 
    // Return copied array 
    return result; 
} 

그런 다음, 중복 된 파일 경로를 추가 다시 순서를 다시 randomise 및 항목으로 UI 속성을 채울 : 당신은 또한 할 수 물론

string[] filePathsToUse = new string[filePaths.Length * 2]; 
filePaths = RandomizeStrings(filePaths); 
for (int count = 0; count < yourRequiredNumber; count++) 
{ 
    filePathsToUse.Add(filePaths(count)); 
    filePathsToUse.Add(filePaths(count)); 
} 
// Finally, randomize the collection again: 
ObservableCollection<string> filePathsToBindTo = new 
    ObservableCollection<string>(RandomizeStrings(filePathsToUse)); 

여러 가지면에서 이해하기 쉽고, 좀 더 효율적입니다. 당신이 편하게 느끼는 방법을 선택하십시오.