Airplay Tutorial: An Apple TV multiplayer game (4)

Source: Internet
Author: User

Now the client needs to act on the commands that the server sends.

Add code at the end of method ReceiveData:fromPeer:inSession:context:

if ([commandreceived hasprefix:kcommandquestion] && ! Self.isserver) {

NSString *answersstring = [commandreceived substringfromindex:kcommandquestion.length ];

[self.scene startquestionwithanswercount: [answersstring integervalue]];

}

Assuming that there will never be more than 9 answers, the last character is the number of answers. Answersstring Save this character, you can convert it to a number, and then pass the value to the Startquestionwithanswercount: method so that the screen displays the same number of answer buttons.

Compile and run the project, run it on the emulator first, and then run it on the real machine. When the Start Game button appears, tap the button. You will see the following interface:

On the real machine, the same content as the emulator is displayed. Depending on the content of the question, the number of buttons may be displayed differently. To click on a button on the emulator or real machine, the screen will appear as follows:

In addition, the program will not have other reactions. Because when you click on the option button, the logic in Atmyscene contains only the Delete button and calls the Atviewcontroller method-but in fact this method is still empty implementation.

Open atviewcontroller.m, Find Sendanswer: Method, add the following code:

[Self sendtoallpeers: [kcommandanswer stringbyappendingstring: [nsstring stringWithFormat:@"%ld", (long)answer]] ;

The code is simple, sending the "answer" command and the user-selected answer (index).

The server passes ReceiveData:fromPeer:inSession:context: to receive information.

At the end of this method, add:

if ([commandreceived hasprefix:kcommandanswer] && self.isserver)

{

NSString *answerstring = [commandreceived substringfromindex:kcommandanswer.length ];

Nsinteger answer = [answerstring integervalue];

if (answer = = self.currentquestionanswer && self.currentquestionanswer >= 0) {

Self.currentquestionanswer = -1;

Nsinteger points = 1 + [self.peerstopoints[peer] IntegerValue ];

if       (points > self.maxpoints) {

Self.maxpoints = points;

}

Self.peerstopoints[peer] = @(points);

[self endquestion:peer];

}

Else if     (+ +self.currentquestionanswersreceived = = Self.peersToNames.count) {

[self endquestion:nil];

}

}

First determine if the received message is a "answer" command. If yes and answer with the correct answer system, reset the Currentquestionanswer to 1 for the next quiz. Then add points for the player and update the current maximum score record. Finally, call the Endquestion method.

If the answer is not correct and the answer you have received is the same as the number of players, the current question ends and the Endquestion method is called with nil as the argument.

Next implement the Endquestion: method.

Add a method below the ReceiveData:fromPeer:inSession:context: method:

- (void)endquestion:(nsstring *)winnerpeerid {

[self sendtoallpeers:kcommandendquestion];

nsmutabledictionary *namestopoints = [[nsmutabledictionary alloc] Initwithcapacity:self.peersToNames.count];

for   (nsstring *peerid in Self.peerstonames) {

Namestopoints[self.peerstonames[peerid]] = self.peerstopoints[ Peerid];

}

[self.mirroredscene endquestionwithpoints:namestopoints winner: Winnerpeerid? Self.peerstonames[winnerpeerid] : nil];

[self.scene endquestion];

dispatch_time_t poptime = dispatch_time(dispatch_time_now, 4 * nsec_per_sec) ;

Dispatch_after(poptime, Dispatch_get_main_queue(), ^ (void) {

[self startquestion];

});

}

This method sends a message to the client to end the current question, which will be told later. Then, create a dictionary that stores each player and the corresponding score and sends it to the second monitor to show the player the correct question and the current score.

Finally, a delay of 4 seconds to run the statement block, call Startquestion to open the next question.

The client needs to process the end question command.

Add code at the end of the ReceiveData:fromPeer:inSession:context: method:

if ([commandreceived isequaltostring:kcommandendquestion] && ! Self.isserver) {

[self.scene endquestion];

}

Once the client receives the command, it calls the Endquestion method, which ends this round of questioning and hides the answer button.

Compile run program, first simulator, after real machine. Start the game and answer some questions casually. If the answer is not correct, you will need to wait until the real machine and simulator are answered before you can start the next question.

You can now see a screen similar to the following:

If the emulator is running for a long time, you may experience a scenario where the program crashes. This is because the code does not handle the case when the question has been asked (i.e. the game is over). This is the last piece of work!

Add the following code to the Startquestion method header:

if   (self.questions.count = = 0) {

nsmutablestring *Winner = [[nsmutablestring alloc] init];

for     (nsstring *peerid in self.peerstopoints) {

Nsinteger points = [self.peerstopoints[peerid] integervalue];

if       (points = = self.maxpoints) {

if (winner.length) {

[winner AppendFormat:@",%@", Self.peerstonames[peerid]];

} else {

[winner appendString:self.peerstonames[peerid]];

}

}

}

[self.mirroredscene setGameOver:winner];

return;

}

If your answer is a question, the method generates the winner's name (one or more winners)-and then it appears on the second display.

Compile and run the program, when you finish the whole game, you will see the following interface:

How did you pass the CS test?

What do you do next?

Congratulations-you just wrote a multi-player client/server game with an external monitor using game Kit! The final completed project is downloaded here .

Now that you have the foundation to write client/server games using Gamekit and know how to use the extended screen, this benefit is self-evident for some games. You can use the second screen as the game view, the device as the control terminal, or display some additional information on the device, just like the HUD (head-up display).

Gamekit-In-the-peer communication opens up a door for multiplayer games or apps, and you can see how easy it is to use the APIs provided by Apple to achieve multi-person control. But in IOS7, Gksession has been replaced by the multipeer Connectivity framework . These two frames are similar, and your gksession knowledge will be smoothed over to the new mcsession and its associated classes.

Hope you enjoy this tutorial. Use AirPlay and Gamekit to develop what you want!

If you have any questions or suggestions, please leave a message below.


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.