(译)如何使用cocos2d制作一个滑动图片游戏教程:第二部分(完)

原文链接地址:http://www.iphonegametutorials.com/2011/03/17/cocos2d-game-tutorial-%E2%80%93-building-a-slide-image-game-part-2-with-solution/

教程截图:

 

  大家好!我们将再一次回到滑动图片游戏教程,然后给它添加一些新的特性。我们将添加判断,是否玩家成功解谜。这个任务很明了了,让我们直接开干吧!

  这里有本教程的完整源代码

 

  本教程的所有信息,都是基于上一篇教程,所以在继续阅读之前,请你先看第一篇教程。

  好了,现在,是时候教大家如何实现啦! 

  首先,在tile.h中,我们需要添加一个新的变量“originalValue”,用来保存Tile的初始位置。这样的话,当你把Tile打乱的时候,我们就可以使用这个位置与新的位置作比较,以此来判断玩家是否完成拼图。

@interface Tile : NSObject {
int x, y, value, originalValue;
CCSprite
*sprite;
}

-(id) initWithX: (int) posX Y: (int) posY;
@property (nonatomic,
readonly) int x, y;
@property (nonatomic)
int value;
@property (nonatomic)
int originalValue;
@property (nonatomic, retain) CCSprite
*sprite;
-(BOOL) nearTile: (Tile *)othertile;
-(void) trade:(Tile *)otherTile;
-(CGPoint) pixPosition;
@end

 

  接下来,我们打开box.m,然后在check函数的底部,作下面的修改:

destTile.value = (7* destTile.x) + destTile.y;
destTile.originalValue
= destTile.value;
destTile.sprite
= sprite;

  如果你是直接从第一个工程的源代码进行修改的话,那么,原来的代码如下所示:

destTile.value = imgValue;
destTile.sprite
= sprite;

  在你完成这些修改以后,我们还有最后一件事件需要做,就是在box.m里面添加一个新的函数,用来判断游戏状态。

-(BOOL) checkSolution {

BOOL isSolved
=true;

for (int x=0; x < size.width; x++) {
for (int y=0; y < size.height; y++) {
Tile
*tile = [self objectAtX:x Y:y];

if (tile.originalValue != tile.value) {
isSolved
=false;
}
}
}

if (isSolved) {
NSLog(
@"The Sliding Image is Solved");
returntrue;
}
else {
NSLog(
@"The Sliding Image is NOT Solved");
returnfalse;
}

returntrue;
}

 

  这里就是遍历所有的Tiles,然后比较value和originalValue的值,如果全部相等,则表明成功解谜,否则,就表明失败。

  最后,在PlayLayer.m中,我们在ChangeTileWithA方法里面添加下面的代码:

NSLog(@"Check Solution");

BOOL isSolved
= [box checkSolution];

CCLabel
*solvedLabel = (CCLabel*)[self getChildByTag:kSolvedText];

if (isSolved) {
[solvedLabel setString:
@"The Puzzle is Solved"];
}
else {
[solvedLabel setString:
@"The Puzzle is NOT Solved"];
}

 

  这样,每一次你交换两个小图片的时候,都会判断一下游戏的状态,同时用CCLabel显示在屏幕上面。

  如果大家有什么问题,请留言。

  下篇教程见!

  

    著作权声明:本文由http://www.cnblogs.com/andyque翻译,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!

posted on 2011-07-27 11:01  子龙山人  阅读(5456)  评论(3编辑  收藏  举报