2012-03-25 86 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; 
} 

我想将图像随机放置在四个占位符中。我有更多的代码写在下面,我得到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 /标记逻辑。 只需使用一个数组:

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 2012-03-25 18:08:52

+0

是的,它适用于任何大小的数组。而且它确保每个元素至少有一次与另一个元素的位置发生了变化。 (PS:我们可以删除我们的旧评论,他们不会帮助任何人;) – calimarkus 2012-03-25 18:13:38

+0

很好,再次感谢 – garethdn 2012-03-25 18:18:13