将图像移动到随机占位符

时间:2012-03-25 16:42:17

标签: iphone objective-c ios image random

我正在制作一个简单的拼图游戏。我有一个方法,在加载视图和摇动设备时调用。该方法将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 个答案:

答案 0 :(得分: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;

(您也可以在循环中执行此操作..因此它会更通用且可重复使用。)