
// 1 -  self.isTouchEnabled = YES; CGSize wins = [CCDirector sharedDirector].winSize; // 2 -   CCSprite * background = [CCSprite spriteWithFile:@"Bg.png"]; [self addChild:background]; [background setPosition:ccp(wins.width/2,wins.height/2)];  NSMutableArray * towerBases;  //    "init" -(void)loadTowerPositions { NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"TowersPosition" ofType:@"plist"]; NSArray * towerPositions = [NSArray arrayWithContentsOfFile:plistPath]; towerBases = [[NSMutableArray alloc] initWithCapacity:10]; for(NSDictionary * towerPos in towerPositions) { CCSprite * towerBase = [CCSprite spriteWithFile:@"open_spot.png"]; [self addChild:towerBase]; [towerBase setPosition:ccp([[towerPos objectForKey:@"x"] intValue],[[towerPos objectForKey:@"y"] intValue])]; [towerBases addObject:towerBase]; } } // init,      #2 // 3 -    [self loadTowerPositions]; // dealloc,     (  super) [towerBases release]; 
 @property (nonatomic,retain) NSMutableArray *towers;  @synthesize towers;  #import "cocos2d.h" #import "HelloWorldLayer.h" #define kTOWER_COST 300 @class HelloWorldLayer, Enemy; @interface Tower: CCNode { int attackRange; int damage; float fireRate; } @property (nonatomic,assign) HelloWorldLayer *theGame; @property (nonatomic,assign) CCSprite *mySprite; +(id)nodeWithTheGame:(HelloWorldLayer*)_game location:(CGPoint)location; -(id)initWithTheGame:(HelloWorldLayer *)_game location:(CGPoint)location; @end  #import "Tower.h" @implementation Tower @synthesize mySprite,theGame; +(id) nodeWithTheGame:(HelloWorldLayer*)_game location:(CGPoint)location { return [[[self alloc] initWithTheGame:_game location:location] autorelease]; } -(id) initWithTheGame:(HelloWorldLayer *)_game location:(CGPoint)location { if( (self=[super init])) { theGame = _game; attackRange = 70; damage = 10; fireRate = 1; mySprite = [CCSprite spriteWithFile:@"tower.png"]; [self addChild:mySprite]; [mySprite setPosition:location]; [theGame addChild:self]; [self scheduleUpdate]; } return self; } -(void)update:(ccTime)dt { } -(void)draw { glColor4f(255, 255, 255, 255); ccDrawCircle(mySprite.position, attackRange, 360, 30, false); [super draw]; } -(void)dealloc { [super dealloc]; } @end  //  : #import "Tower.h" //dealloc: [towers release]; //  dealloc   : -(BOOL)canBuyTower { return YES; } - (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { for( UITouch *touch in touches ) { CGPoint location = [touch locationInView: [touch view]]; location = [[CCDirector sharedDirector] convertToGL: location]; for(CCSprite * tb in towerBases) { if([self canBuyTower] && CGRectContainsPoint([tb boundingBox],location) && !tb.userData) { //    . Tower * tower = [Tower nodeWithTheGame:self location:tb.position]; [towers addObject:tower]; tb.userData = tower; } } } } 
 #import "cocos2d.h" #import "HelloWorldLayer.h" @interface Waypoint: CCNode { HelloWorldLayer *theGame; } @property (nonatomic,readwrite) CGPoint myPosition; @property (nonatomic,assign) Waypoint *nextWaypoint; +(id)nodeWithTheGame:(HelloWorldLayer*)_game location:(CGPoint)location; -(id)initWithTheGame:(HelloWorldLayer *)_game location:(CGPoint)location; @end  #import "Waypoint.h" @implementation Waypoint @synthesize myPosition, nextWaypoint; +(id)nodeWithTheGame:(HelloWorldLayer*)_game location:(CGPoint)location { return [[[self alloc] initWithTheGame:_game location:location] autorelease]; } -(id)initWithTheGame:(HelloWorldLayer *)_game location:(CGPoint)location { if( (self=[super init])) { theGame = _game; [self setPosition:CGPointZero]; myPosition = location; [theGame addChild:self]; } return self; } -(void)draw { glColor4f(0, 255, 0, 255); ccDrawCircle(myPosition, 6, 360, 30, false); ccDrawCircle(myPosition, 2, 360, 30, false); if(nextWaypoint) ccDrawLine(myPosition, nextWaypoint.myPosition); [super draw]; } -(void)dealloc { [super dealloc]; } @end  @property (nonatomic,retain) NSMutableArray *waypoints;  //   : #import "Waypoint.h" //  synthesise @synthesize waypoints; //    init -(void)addWaypoints { waypoints = [[NSMutableArray alloc] init]; Waypoint * waypoint1 = [Waypoint nodeWithTheGame:self location:ccp(420,35)]; [waypoints addObject:waypoint1]; Waypoint * waypoint2 = [Waypoint nodeWithTheGame:self location:ccp(35,35)]; [waypoints addObject:waypoint2]; waypoint2.nextWaypoint =waypoint1; Waypoint * waypoint3 = [Waypoint nodeWithTheGame:self location:ccp(35,130)]; [waypoints addObject:waypoint3]; waypoint3.nextWaypoint =waypoint2; Waypoint * waypoint4 = [Waypoint nodeWithTheGame:self location:ccp(445,130)]; [waypoints addObject:waypoint4]; waypoint4.nextWaypoint =waypoint3; Waypoint * waypoint5 = [Waypoint nodeWithTheGame:self location:ccp(445,220)]; [waypoints addObject:waypoint5]; waypoint5.nextWaypoint =waypoint4; Waypoint * waypoint6 = [Waypoint nodeWithTheGame:self location:ccp(-40,220)]; [waypoints addObject:waypoint6]; waypoint6.nextWaypoint =waypoint5; } //    init: // 4 - Add waypoints [self addWaypoints]; // dealloc [waypoints release]; 
 -(BOOL)circle:(CGPoint)circlePoint withRadius:(float)radius collisionWithCircle:(CGPoint)circlePointTwo collisionCircleRadius:(float)radiusTwo; void ccFillPoly(CGPoint *poli, int points, BOOL closePolygon);  void ccFillPoly( CGPoint *poli, int points, BOOL closePolygon ) { //   GL: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY //  : GL_VERTEX_ARRAY, //  : GL_TEXTURE_2D, GL_TEXTURE_COORD_ARRAY, GL_COLOR_ARRAY glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glVertexPointer(2, GL_FLOAT, 0, poli); if( closePolygon ) glDrawArrays(GL_TRIANGLE_FAN, 0, points); else glDrawArrays(GL_LINE_STRIP, 0, points); // restore default state glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); } -(BOOL)circle:(CGPoint) circlePoint withRadius:(float) radius collisionWithCircle:(CGPoint) circlePointTwo collisionCircleRadius:(float) radiusTwo { float xdif = circlePoint.x - circlePointTwo.x; float ydif = circlePoint.y - circlePointTwo.y; float distance = sqrt(xdif*xdif+ydif*ydif); if(distance <= radius+radiusTwo) return YES; return NO; }  //    int wave; CCLabelBMFont *ui_wave_lbl; //    property @property (nonatomic,retain) NSMutableArray *enemies;  // Synthesize enemies @synthesize enemies; //  dealloc [enemies release];  #import "cocos2d.h" #import "HelloWorldLayer.h" #import "GameConfig.h" @class HelloWorldLayer, Waypoint, Tower; @interface Enemy: CCNode { CGPoint myPosition; int maxHp; int currentHp; float walkingSpeed; Waypoint *destinationWaypoint; BOOL active; } @property (nonatomic,assign) HelloWorldLayer *theGame; @property (nonatomic,assign) CCSprite *mySprite; +(id)nodeWithTheGame:(HelloWorldLayer*)_game; -(id)initWithTheGame:(HelloWorldLayer *)_game; -(void)doActivate; -(void)getRemoved; @end  #import "Enemy.h" #import "Tower.h" #import "Waypoint.h" #import "SimpleAudioEngine.h" #define HEALTH_BAR_WIDTH 20 #define HEALTH_BAR_ORIGIN -10 @implementation Enemy @synthesize mySprite, theGame; +(id)nodeWithTheGame:(HelloWorldLayer*)_game { return [[[self alloc] initWithTheGame:_game] autorelease]; } -(id)initWithTheGame:(HelloWorldLayer *)_game { if ((self=[super init])) { theGame = _game; maxHp = 40; currentHp = maxHp; active = NO; walkingSpeed = 0.5; mySprite = [CCSprite spriteWithFile:@"enemy.png"]; [self addChild:mySprite]; Waypoint * waypoint = (Waypoint *)[theGame.waypoints objectAtIndex:([theGame.waypoints count]-1)]; destinationWaypoint = waypoint.nextWaypoint; CGPoint pos = waypoint.myPosition; myPosition = pos; [mySprite setPosition:pos]; [theGame addChild:self]; [self scheduleUpdate]; } return self; } -(void)doActivate { active = YES; } -(void)update:(ccTime)dt { if(!active)return; if([theGame circle:myPosition withRadius:1 collisionWithCircle:destinationWaypoint.myPosition collisionCircleRadius:1]) { if(destinationWaypoint.nextWaypoint) { destinationWaypoint = destinationWaypoint.nextWaypoint; }else { //  .    [theGame getHpDamage]; [self getRemoved]; } } CGPoint targetPoint = destinationWaypoint.myPosition; float movementSpeed = walkingSpeed; CGPoint normalized = ccpNormalize(ccp(targetPoint.x-myPosition.x,targetPoint.y-myPosition.y)); mySprite.rotation = CC_RADIANS_TO_DEGREES(atan2(normalized.y,-normalized.x)); myPosition = ccp(myPosition.x+normalized.x * movementSpeed,myPosition.y+normalized.y * movementSpeed); [mySprite setPosition:myPosition]; } -(void)getRemoved { [self.parent removeChild:self cleanup:YES]; [theGame.enemies removeObject:self]; //              [theGame enemyGotKilled]; } -(void)draw { glColor4f(255, 0, 0, 255); CGPoint healthBarBack[] = {ccp(mySprite.position.x -10,mySprite.position.y+16),ccp(mySprite.position.x+10,mySprite.position.y+16),ccp(mySprite.position.x+10,mySprite.position.y+14),ccp(mySprite.position.x-10,mySprite.position.y+14)}; ccFillPoly(healthBarBack, 4, YES); glColor4f(0, 255, 0, 255); CGPoint healthBar[] = {ccp(mySprite.position.x + HEALTH_BAR_ORIGIN,mySprite.position.y+16),ccp(mySprite.position.x+HEALTH_BAR_ORIGIN+(float)(currentHp * HEALTH_BAR_WIDTH) / maxHp,mySprite.position.y+16),ccp(mySprite.position.x+HEALTH_BAR_ORIGIN+(float)(currentHp * HEALTH_BAR_WIDTH) / maxHp,mySprite.position.y+14),ccp(mySprite.position.x+HEALTH_BAR_ORIGIN,mySprite.position.y+14)}; ccFillPoly(healthBar, 4, YES); } -(void)dealloc { [super dealloc]; } @end  -(void)enemyGotKilled;  // : #import "Enemy.h" //  init: -(BOOL)loadWave { NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"Waves" ofType:@"plist"]; NSArray * waveData = [NSArray arrayWithContentsOfFile:plistPath]; if(wave >= [waveData count]) { return NO; } NSArray * currentWaveData =[NSArray arrayWithArray:[waveData objectAtIndex:wave]]; for(NSDictionary * enemyData in currentWaveData) { Enemy * enemy = [Enemy nodeWithTheGame:self]; [enemies addObject:enemy]; [enemy schedule:@selector(doActivate) interval:[[enemyData objectForKey:@"spawnTime"]floatValue]]; } wave++; [ui_wave_lbl setString:[NSString stringWithFormat:@"WAVE: %d",wave]]; return YES; } -(void)enemyGotKilled { if ([enemies count]<=0) //If there are no more enemies. { if(![self loadWave]) { NSLog(@"You win!"); [[CCDirector sharedDirector] replaceScene:[CCTransitionSplitCols transitionWithDuration:1 scene:[HelloWorldLayer scene]]]; } } } //   init: // 5 -   enemies = [[NSMutableArray alloc] init]; [self loadWave]; // 6 -      ui_wave_lbl = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"WAVE: %d",wave] fntFile:@"font_red_14.fnt"]; [self addChild:ui_wave_lbl z:10]; [ui_wave_lbl setPosition:ccp(400,wins.height-12)]; [ui_wave_lbl setAnchorPoint:ccp(0,0.5)]; 
 //    BOOL attacking; Enemy *chosenEnemy; //    -(void)targetKilled;  //   Enemy  #import "Enemy.h" //     init: -(void)attackEnemy { [self schedule:@selector(shootWeapon) interval:fireRate]; } -(void)chosenEnemyForAttack:(Enemy *)enemy { chosenEnemy = nil; chosenEnemy = enemy; [self attackEnemy]; [enemy getAttacked:self]; } -(void)shootWeapon { CCSprite * bullet = [CCSprite spriteWithFile:@"bullet.png"]; [theGame addChild:bullet]; [bullet setPosition:mySprite.position]; [bullet runAction:[CCSequence actions:[CCMoveTo actionWithDuration:0.1 position:chosenEnemy.mySprite.position],[CCCallFunc actionWithTarget:self selector:@selector(damageEnemy)],[CCCallFuncN actionWithTarget:self selector:@selector(removeBullet:)], nil]]; } -(void)removeBullet:(CCSprite *)bullet { [bullet.parent removeChild:bullet cleanup:YES]; } -(void)damageEnemy { [chosenEnemy getDamaged:damage]; } -(void)targetKilled { if(chosenEnemy) chosenEnemy =nil; [self unschedule:@selector(shootWeapon)]; } -(void)lostSightOfEnemy { [chosenEnemy gotLostSight:self]; if(chosenEnemy) chosenEnemy =nil; [self unschedule:@selector(shootWeapon)]; }  -(void)update:(ccTime)dt { if (chosenEnemy){ //       CGPoint normalized = ccpNormalize(ccp(chosenEnemy.mySprite.position.x-mySprite.position.x,chosenEnemy.mySprite.position.y-mySprite.position.y)); mySprite.rotation = CC_RADIANS_TO_DEGREES(atan2(normalized.y,-normalized.x))+90; if(![theGame circle:mySprite.position withRadius:attackRange collisionWithCircle:chosenEnemy.mySprite.position collisionCircleRadius:1]) { [self lostSightOfEnemy]; } } else { for(Enemy * enemy in theGame.enemies) { if([theGame circle:mySprite.position withRadius:attackRange collisionWithCircle:enemy.mySprite.position collisionCircleRadius:1]) { [self chosenEnemyForAttack:enemy]; break; } } } }  //  NSMutableArray *attackedBy; //    -(void)getAttacked:(Tower *)attacker; -(void)gotLostSight:(Tower *)attacker; -(void)getDamaged:(int)damage;  //     initWithTheGame: (  "if") attackedBy = [[NSMutableArray alloc] initWithCapacity:5]; //   getRemoved: -(void)getRemoved { for(Tower * attacker in attackedBy) { [attacker targetKilled]; } [self.parent removeChild:self cleanup:YES]; [theGame.enemies removeObject:self]; // ,       ,      [theGame enemyGotKilled]; } //       -(void)getAttacked:(Tower *)attacker { [attackedBy addObject:attacker]; } -(void)gotLostSight:(Tower *)attacker { [attackedBy removeObject:attacker]; } -(void)getDamaged:(int)damage { currentHp -=damage; if(currentHp <=0) { [self getRemoved]; } } 
 int playerHp; CCLabelBMFont *ui_hp_lbl; BOOL gameEnded;  -(void)getHpDamage; -(void)doGameOver;  //    init: // 7 -   playerHp = 5; ui_hp_lbl = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"HP: %d",playerHp] fntFile:@"font_red_14.fnt"]; [self addChild:ui_hp_lbl z:10]; [ui_hp_lbl setPosition:ccp(35,wins.height-12)]; //      : -(void)getHpDamage { playerHp--; [ui_hp_lbl setString:[NSString stringWithFormat:@"HP: %d",playerHp]]; if (playerHp <=0) { [self doGameOver]; } } -(void)doGameOver { if (!gameEnded) { gameEnded = YES; [[CCDirector sharedDirector] replaceScene:[CCTransitionRotoZoom transitionWithDuration:1 scene:[HelloWorldLayer scene]]]; } } 
 int playerGold; CCLabelBMFont *ui_gold_lbl;  -(void)awardGold:(int)gold;  //   init: -(void)awardGold:(int)gold { playerGold += gold; [ui_gold_lbl setString:[NSString stringWithFormat:@"GOLD: %d",playerGold]]; } //   init: // 8 -  playerGold = 1000; ui_gold_lbl = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"GOLD: %d",playerGold] fntFile:@"font_red_14.fnt"]; [self addChild:ui_gold_lbl z:10]; [ui_gold_lbl setPosition:ccp(135,wins.height-12)]; [ui_gold_lbl setAnchorPoint:ccp(0,0.5)]; //  canBuyTower: -(BOOL)canBuyTower { if (playerGold - kTOWER_COST >=0) return YES; return NO; } //  ccTouchesBegan,      "if",    ,     : playerGold -= kTOWER_COST; [ui_gold_lbl setString:[NSString stringWithFormat:@"GOLD: %d",playerGold]];  [theGame awardGold:200]; 
 //  : #import "SimpleAudioEngine.h" //   init: (  'if') [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"8bitDungeonLevel.mp3" loop:YES]; //  ccTouchesBegan,     Tower: [[SimpleAudioEngine sharedEngine] playEffect:@"tower_place.wav"]; //  getHpDamage [[SimpleAudioEngine sharedEngine] playEffect:@"life_lose.wav"];  // : #import "SimpleAudioEngine.h" //   getDamaged: [[SimpleAudioEngine sharedEngine] playEffect:@"laser_shoot.wav"]; Source: https://habr.com/ru/post/162733/
All Articles