0

我想创建一个小游戏:

你应该找到成对的图片,这是我的代码我可以在图片上看到正面和背面,但我不知道我应该如何找到或比较图片以找到成对

这是我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.


}

// Create the view
CardView *cv = [[CardView alloc] initWithFrontImage:img1 backImage:img2];


}

你能帮我一些提示或教程吗:)

4

1 回答 1

2

Why don't u use tags as you already did in the sample code? Is there a reason you always set cardview's tag to 1? If not you can set different tags for different images and compare tags when images are clicked. This would be the simplest solution. Otherwise another simple solution would be to add another instance variable to your cardview class such as imageID, store unique ids for different images and then compare these imageIDs to check if two clicked images are the same.

To generate imageIDs and store them I would suggest you to use NSDictionary where image file names are object keys and IDs are nsnumber objects. Then while adding images to nsdictionary you check if image file name already exists if so you return the imageID otherwise you add a new object-key pair and return the newly created imageID. If you want more details just tell me where you are stuck.

EDIT: I got a simpler idea while thinking instead of storing imageIDs in the cardview class just add an NSString frontImageFileName as instance variable. Modify addCardAtX to :

- (void)addCardAtX:(CGFloat)x y:(CGFloat)y andFrontImageWithFileName:(NSString *) imgName andTag:(int)tag
{
// Load images
UIImage *img2= [UIImage imageNamed:@"card_back.png"];

// Create the view
//So instead of this one
//CardView *cv = [[CardView alloc] initWithFrontImage:img1 backImage:img2];

//You have
CardView *cv = [[CardView alloc] initWithFrontImage:[UIImage imageNamed:imgName] backImage:img2];
cv.frontImageFileName = imgName;

// Center card on location
CGRect f = cv.frame;
f.origin.x = x-(f.size.width/2.0);
f.origin.y = y-(f.size.height/2.0);

cv.frame = f;
}

Now you can compare equality of cardviews by

[cv1.frontImageFileName isEqualTo:cv2.frontImageFileName] 
于 2013-01-28T16:57:03.140 回答