2012-03-25 4 views
0

나는 간단한 지그 소 퍼즐을 만들고 있습니다. 뷰가로드되고 장치가 흔들릴 때 호출되는 메서드가 있습니다. 이 방법은 4 개의 특정 위치에 4 ​​개의 이미지를 저장합니다. 아래 코드는 다음과 같습니다.임의의 자리 표시 자로 이미지 이동

-(void) makePieceHolders { 
//create 4 points where the jigsaw pieces (images) will be placed 
CGPoint holder1 = CGPointMake(80, 80); 
CGPoint holder2 = CGPointMake(200, 80); 
CGPoint holder3 = CGPointMake(80, 200); 
CGPoint holder4 = CGPointMake(200, 200); 

image1.center = holder1; //set the position of the image center to one of the newly created points 
image1.alpha = 0.3;   //set the image opacity back to 0.3 
image2.center = holder2; 
image2.alpha = 0.3; 
image3.center = holder3; 
image3.alpha = 0.3; 
image4.center = holder4; 
image4.alpha = 0.3; 
} 

내가 원하는 것은 4 개의 자리 표시 자에 임의로 이미지를 배치하는 것입니다. 아래에 몇 가지 코드를 작성하여 1에서 4 사이의 임의의 숫자를 얻은 다음 각 이미지의 태그를이 임의의 숫자로 설정합니다.

int randomNumber; 
int placeHolders[4]; 
int i=0; 
bool numberFound; 

do{ // until you get 4 unique numbers 
    randomNumber=arc4random()%4+1; 
    // Does this number exist already? 
    numberFound=FALSE; 
    for (int j=0; j<i; j++) { 
     if (placeHolders[j]==randomNumber) 
      numberFound=TRUE; 
    } 
    if (numberFound==FALSE){ 
     placeHolders[i]=randomNumber; 
     i++; 
    } 
} while (i<4); 

image1.tag = placeHolders[0]; 
image2.tag = placeHolders[1]; 
image3.tag = placeHolders[2]; 
image4.tag = placeHolders[3]; 


NSLog(@"img1 tag: %i img2 tag: %i img3 tag: %i img4 tag: %i", image1.tag, image2.tag, image3.tag, image4.tag); 

이 태그 정보를 자리 표시 자로 이동하려면 어떻게해야합니까?

의사에서 나는 생각했다 :

where image tag = 1, move that image to holder1 
where image tag = 2, move that image to holder2 
............ 

나는이 생각을 작성하는 방법을 모르겠어요.

더 좋은 방법이 있다면 도움을 주시면 감사하겠습니다. 감사합니다

답변

1

복잡한 do..while/tag 로직이 필요하지 않습니다. 당신은 무작위로 새로운 질서에 이미지를 배치 한, 그 후

NSMutableArray* images = [NSMutableArray arrayWithObjects: image1,image2,image3,image4,nil]; 

// shuffle the array 
NSUInteger count = [images count]; 
for (NSUInteger i = 0; i < count; i++) { 
    // Select a random element between i and end of array to swap with. 
    int nElements = count - i; 
    int n = (arc4random() % nElements) + i; 
    [images exchangeObjectAtIndex:i withObjectAtIndex:n]; 
} 

: 그냥 배열을 사용합니다. 그 위치를 지정 후 :

UIImageView* imageView1 = (UIImageView*)[images objectAtIndex: 0]; 
imageView.center = holder1; 
UIImageView* imageView2 = (UIImageView*)[images objectAtIndex: 1]; 
imageView.center = holder2; 
UIImageView* imageView3 = (UIImageView*)[images objectAtIndex: 2]; 
imageView.center = holder3; 
UIImageView* imageView4 = (UIImageView*)[images objectAtIndex: 3]; 
imageView.center = holder4; 

(더 일반적으로 재사용 될 수 있도록 당신은 또한 .. 루프에서이 작업을 수행 할 수 있습니다.)

좋아요
+0

, 감사합니다. 지금은 대단한 일입니다. 그런 무작위 화 방식이 훨씬 더 큰 크기의 퍼즐에 적합할까요? – garethdn

+0

예, 모든 크기의 배열에서 작동합니다. 그리고 모든 요소가 적어도 한 번 이상 다른 요소와 위치를 변경했는지 확인합니다. (추신 : 우리는 우리의 오래된 의견을 삭제할 수 있습니다. 그들은 도움이되지 않습니다;) – calimarkus

+0

다시 한번 감사드립니다. – garethdn

관련 문제