Hardware Reference
In-Depth Information
Continued from previous page.
// disconnect the client from the server:
println(speakingPlayer.client.ip() + "\t logged out");
myServer.disconnect(speakingPlayer.client);
// remove the client's Player from the playerList:
playerList.remove(speakingPlayer);
break;
case 'l':
// if the client sends an "l", move the paddle left
speakingPlayer.movePaddle(-10);
break;
case'r':
// if the client sends an "r", move the paddle right
speakingPlayer.movePaddle(10);
break;
}
}
}
So far you've seen how the server receives new
connections (using serverEvent() ), creates
new Players from the new clients (using make-
NewPlayer() ), and listens for messages (using listenTo-
Clients() ). That covers the interaction between the server
and the clients. In addition, you've seen how the Player
class defines all the properties and methods that are
associated with each new player. Finally, it's time to look
at the methods for controlling the drawing of the game.
drawGame() , called from the draw() method, is the main
method for this. This method has four tasks:
• Iterate over the playerList and draw all the paddles
at their most current positions.
• Draw the ball and the score.
• If the game is over, show a “Game Over” message
and pause.
• Pause after each volley, then serve the ball again.
Show It
Here is the pongDraw()
method.
void drawGame() {
background(0);
// draw all the paddles
for (int p = 0; p < playerList.size(); p++) {
Player thisPlayer = (Player)playerList.get(p);
// show the paddle for this player:
thisPlayer.showPaddle();
}
You saw earlier that the listenToClients()
method actually updates the positions
of the paddles using the movePaddle()
method from the Player object. That
method doesn't actually draw the
paddles, but this one does, using
each Player's showPaddle() method. This
is why the two methods are separated in
the object.
8
Likewise, the moveBall() method,
called here, checks to see whether the ball
hit a paddle or a wall. It then calculates its
new position from there, but it doesn't
draw the ball itself because the ball needs
to be drawn even if it's not in motion.
// calculate ball's position:
if (ballInMotion) {
moveBall();
}
// draw the ball:
rect(ballPosH, ballPosV, ballSize, ballSize);
// show the score:
showScore();
»
 
Search WWH ::




Custom Search