Hardware Reference
In-Depth Information
Continued from opposite page.
nextTopPaddleV = nextTopPaddleV + paddleHeight * 2;
y = nextTopPaddleV;
}
}
// make a new Player object with the position you just calculated
// and using the Client that generated the serverEvent:
Player newPlayer = new Player(x, y, thisClient);
// add the new Player to the playerList:
playerList.add(newPlayer);
// Announce the new Player:
println("We have a new player: " + newPlayer.client.ip());
newPlayer.client.write("hi\r\n");
}
8
Once a new Player has been
created, you need to listen continuously
for that Player's client to send any
messages. The more often you check
for messages, the tighter the interac-
tive loop between sensor and action.
void listenToClients() {
// get the next client that sends a message:
Client speakingClient = myServer.available();
Player speakingPlayer = null;
// iterate over the playerList to figure out whose
// client sent the message:
for (int p = 0; p < playerList.size(); p++) {
// get the next object in the ArrayList and convert it
// to a Player:
Player thisPlayer = (Player)playerList.get(p);
// compare the client of thisPlayer to the client that sent a message.
// If they're the same, then this is the Player we want:
if (thisPlayer.client == speakingClient) {
speakingPlayer = thisPlayer;
break;
}
}
The listenToClients() method, called
continuously from the draw() method,
listens for messages from clients. If
there's data available from any client,
this method takes action. First, it
iterates over the list of Players to see
whether each one's client is speaking.
Then, it checks to see whether the
client sent any of the game messages
(that is, l for left, r for right, or x for
exit). If any of those messages was
received, the program acts on the
message appropriately.
// read what the client sent:
if (speakingPlayer != null) {
int whatClientSaid = speakingPlayer.client.read();
/*
There are a number of things it might have said that we care about:
x = exit
l = move left
r = move right
*/
switch (whatClientSaid) {
// If the client says "exit", disconnect it
case 'x':
// say goodbye to the client:
speakingPlayer.client.write("bye\r\n");
ยป
 
Search WWH ::




Custom Search