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
............
我不知道該怎麼寫,雖然。
如果有更好的方法,我會很感激的幫助。謝謝
這是偉大的,謝謝。現在它工作得很好。那種隨機化的方式適用於更大尺寸的拼圖嗎? – garethdn 2012-03-25 18:08:52
是的,它適用於任何大小的數組。而且它確保每個元素至少有一次與另一個元素的位置發生了變化。 (PS:我們可以刪除我們的舊評論,他們不會幫助任何人;) – calimarkus 2012-03-25 18:13:38
很好,再次感謝 – garethdn 2012-03-25 18:18:13