Cocos2d games (beginners) (2)

Source: Internet
Author: User

First look: (must be on a real machine)

Source Code address: Click to open the link

Directly paste the code. All comments and explanations are included in the Code:

Gamescene. h

# Import <Foundation/Foundation. h> # import "cocos2d. H "@ interface gamescene: cclayer {ccsprite * player; // player genie cgpoint playervelocity; // rate ccarray * shits; // float shitmoveduration of all poop collections; // The distance between pods is int numshitsmoved; // The number of pods is cclabelttf * scorelabel; // The double totaltime tag. // The total time is int score. // The score is cclabelbmfont * gamelabel; cclabelttf * taplabel;} + (ID) scene; @ end

Gamescene. m

# Import "gamescene. H "# import" simpleaudioengine. H "@ implementation gamescene + (ID) scene {ccscene * scene = [ccscene node]; cclayer * layer = [gamescene node]; [scene addchild: layer]; return scene ;} -(ID) Init {If (Self = [Super init]) {// create a background music [[[simpleaudioengine sharedengine] playbackgroundmusic: @ "background#" loop: Yes]; cclog (@ "% @, % @", nsstringfromselector (_ cmd), Self); // sets the accelerator and adds the accelerometer Method [Self setaccelerometerenabled: Yes]; // call the cctouchesended (nsset *) touches event [self settouchenabled: Yes]; // initialize the genie player = [ccsprite spritewithfile: @ "icon.png"]; // Add the genie [self addchild: Player Z: 0 Tag: 1]; // screen size cgsize screensize = [[ccdirector shareddire] winsize]; // sprite height float imageheight = [Player texture]. contentsize. height; // precise position. position is the intermediate coordinate of the genie. position = cgpointmake (screensiz E. width/2, imageheight/2); // score tag // scorelabel = [cclabelttf labelwithstring: @ "0" fontname: @ "Arial" fontsize: 48]; scorelabel = [cclabelbmfont labelwithstring: @ "0" fntfile: @ "font01.fnt"]; // location display // tag location, scorelabel at the top of the screen. position = cgpointmake (screensize. width/2, screensize. height); // scorelabel alignment on the label. anchorpoint = cgpointmake (0.5f, 1.0f); // Add the score Label [self addchild: scorelabel Z:-1]; // update the sprite position, each frame will Call method update [self scheduleupdate]; // Initialize all slots [self initshits];} return self;} // accelerator method-(void) accelerometer :( uiaccelerometer *) accelerometer didaccelerate :( uiacceleration *) Acceleration {// cgpoint Pos = player. position; // POS. X + = acceleration. x * 10; // player. position = Pos; // deceleration value float deceleration = 0.4f; // acceleration value sensitivity float sensitivity = 6.0f; // maximum speed float maxvelocity = 100; // change the Coordinate Position playervelocity. X = Playervelocity. x * deceleration + acceleration. x * sensitiity; // determines if (playervelocity. x> maxvelocity) {playervelocity. X = maxvelocity;} else if (playervelocity. x <-maxvelocity) {playervelocity. X =-maxvelocity ;}/// each frame updates the player genie location-(void) Update :( cctime) Delta {// the current location of the genie cgpoint Pos = player. position; // Add the POs speed. X + = playervelocity. x; cgsize screensize = [[ccdirector shareddire] winsize]; // refined Float imagewidthhalved = [Player texture]. contentsize. width * 0.5f; // float leftborderlimit = imagewidthhalved; // float rightborderlimit = screensize. width-imagewidthhalved; // If (POS. x <leftborderlimit) {pos. X = leftborderlimit; playervelocity = cgpointzero;} else if (POS. x> rightborderlimit) {pos. X = rightborderlimit; playervelocity = cgpointzero;} // change the sprite location Player. position = Pos; // time is used as the player's score totaltime + = delta; int currenttime = (INT) totaltime; If (score <currenttime) {score = currenttime; [scorelabel setstring: [nsstring stringwithformat: @ "% I", score];} // check the collision [self checkforcollision];} // initialize void) initshits {cgsize screensize = [[ccdirector shareddire] winsize]; ccsprite * tempshit = [ccsprite spritewithfile: @ "shit.png"]; // float imagew Idth = [tempshit texture]. contentsize. width; // The total number of poop int numshits = screensize can be displayed on the screen. width/imagewidth; shits = [[ccarray alloc] initwithcapacity: numshits]; for (INT I = 0; I <numshits; I ++) {ccsprite * Shit = [ccsprite spritewithfile: @ "shit.png"]; [self addchild: Shit Z: 0 Tag: 2]; [shits addobject: Shit];} // reset all slots [self resetshits];} // reset all slots-(void) resetshits {cgsize screentsize = [ccdi Rector shareddire] winsize]; ccsprite * tempshit = [shits lastobject]; cgsize size = [tempshit texture]. contentsize; int numshits = [shits count]; for (INT I = 0; I <numshits; I ++) {ccsprite * Shit = [shits objectatindex: I]; shit. position = cgpointmake (size. width * I + size. width * 0.5f, screentsize. height + size. height); // stop all actions [shit stopallactions];} // update stop [self unschedule: @ selector (shitsu Pdate :)]; // run shitsupdate [self schedule: @ selector (shitsupdate :) interval: 0.7f]; numshitsmoved = 0; shitmoveduration = 4.0f ;} // void shitsupdate: (cctime) Delta {// Why do we loop 10 times, I don't know whether the randomly generated index value is actually active or not, so make sure that the randomly selected spider is currently idle. Of course, this number is random, if no idle spider is randomly selected, the system skips the update and waits for the next update. For (INT I = 0; I <10; I ++) {int randomshiteindex = ccrandom_0_1 () * [shits count]; ccsprite * Shit = [shits objectatindex: randomshiteindex]; // whether a poop is in the activity if ([shit numberofrunningactions] = 0) {// if it is idle, make it exercise [self runshitmovesequence: Shit]; break ;}}} // control the casual motion through action-(void) runshitmovesequence :( ccsprite *) Shit {numshitsmoved ++; // accelerate every eight drops, acceleration reduces the distance between stools if (numshitsmoved % 8 = 0 & shitmoveduration> 2.0f) {shitmoveduration-= 0.1f;} // the position to which the log is dropped. cgpoint belowscreenposition = cgpointmake (shit. position. x,-[shit texture]. contentsize. height); // action ccmoveto * Move = [ccmoveto actionwithduration: lower position: belowscreenposition]; cccallfuncn * calldiddrop = [cccallfuncn actionwithtarget: Self selector: @ selector (shitdiddrop :)]; // action loop ccsequence * sequence = [ccsequence actions: Move, call Diddrop, nil]; [shit runaction: sequence];} // reset the slot location-(void) shitdiddrop :( ID) sender {// ensure that the sender parameter belongs to the correct class nsassert ([Sender iskindofclass: [ccsprite class], @ "sender is not a ccsprite! "); Ccsprite * Shit = (ccsprite *) sender; cgpoint Pos = shit. position; cgsize screensize = [[ccdirector shareddire] winsize]; POS. y = screensize. height + [shit texture]. contentsize. height; // change the shit position. position = Pos;} // Collision Detection-(void) checkforcollision {// use the sprite and poop radius to determine whether a collision float playerimagesize = [Player texture]. contentsize. width; float shitimagesize = [[shits lastobject] texture]. contentsize. widt H; float playcollisionradius = playerimagesize * 0.4f; float shitcollisionradius = shitimagesize * 0.4f; // maximum collision distance float maxcollisiondistance = playcollisionradius + distance; int numshits = [shits count]; for (INT I = 0; I <numshits; I ++) {ccsprite * Shit = [shits objectatindex: I]; If ([shit numberofrunningactions] = 0) {continue;} // The ccpdistance method is used to determine whether a collision occurs. Float actualdistance = ccpdista NCE (player. Position, shit. position); If (actualdistance <maxcollisiondistance) {// game over !! [[Simpleaudioengine sharedengine] playeffect: @ "007.mp3"]; // [self resetshits]; [self gameover]; break ;}}- (void) gameover {// screen size cgsize screentsize = [[ccdirector shareddire] winsize]; ccsprite * tempshit = [shits lastobject]; cgsize size = [tempshit texture]. contentsize; int numshits = [shits count]; for (INT I = 0; I <numshits; I ++) {ccsprite * Shit = [shits objectatindex: I]; shit. position = Cgpointmake (size. width * I + size. width * 0.5f, screentsize. height + size. height); // stop all actions [shit stopallactions];} // update stop // [self unschedule: @ selector (shitsupdate :)]; [self unscheduleallselectors]; gamelabel = [cclabelbmfont labelwithstring: @ "game over! "Fntfile: @" font01.fnt "]; gamelabel. position = cgpointmake (screentsize. width/2, screentsize. height/2); [self addchild: gamelabel]; taplabel = [cclabelttf labelwithstring: @ "tap screen to play again" fontname: @ "Arial" fontsize: 20]; taplabel. position = cgpointmake (screentsize. width/2, screentsize. height/2-[gamelabel texture]. contentsize. height/2); [self addchild: taplabel];} // Click Event-(void) CCT Ouchesended :( nsset *) touches withevent :( uievent *) event {If (gamelabel! = Nil) {[self removechild: gamelabel]; [self removechild: taplabel]; taplabel = nil; gamelabel = nil; totaltime = 0.0f;
        [self scheduleUpdate];

[Self resetshits];}

- (void)dealloc{
 CCLOG(@"%@,%@",NSStringFromSelector(_cmd),self); shits = nil;
 [super dealloc];
}@end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.