Java Reference
In-Depth Information
92
93
// Control the game on a separate thread
94
new
Thread(() -> {
95
try
{
96
// Get notification from the server
97
int
player = fromServer.readInt();
98
99
// Am I player 1 or 2?
100
if
(player == PLAYER1) {
101 myToken =
'X'
;
102 otherToken =
'O'
;
103 Platform.runLater(() -> {
104 lblTitle.setText(
"Player 1 with token 'X'"
);
105 lblStatus.setText(
"Waiting for player 2 to join"
);
106 });
107
108
// Receive startup notification from the server
109 fromServer.readInt();
// Whatever read is ignored
110
111
// The other player has joined
112 Platform.runLater(() ->
113 lblStatus.setText(
"Player 2 has joined. I start first"
));
114
115
// It is my turn
116 myTurn =
true
;
117 }
118
else if
(player == PLAYER2) {
119 myToken =
'O'
;
120 otherToken =
'X'
;
121 Platform.runLater(() -> {
122 lblTitle.setText(
"Player 2 with token 'O'"
);
123 lblStatus.setText(
"Waiting for player 1 to move"
);
124 });
125 }
126
127
// Continue to play
128
while
(continueToPlay) {
129
if
(player == PLAYER1) {
130
waitForPlayerAction();
// Wait for player 1 to move
131
sendMove();
// Send the move to the server
132
receiveInfoFromServer();
// Receive info from the server
133 }
134
else if
(player == PLAYER2) {
135
receiveInfoFromServer();
// Receive info from the server
136
waitForPlayerAction();
// Wait for player 2 to move
137
sendMove();
// Send player 2's move to the server
138 }
139 }
140 }
141
catch
(Exception ex) {
142 ex.printStackTrace();
143 }
144 }).start();
145 }
146
147
/** Wait for the player to mark a cell */
148
private void
waitForPlayerAction()
throws
InterruptedException {
149
while
(waiting) {
150 Thread.sleep(
100
);
151 }
Search WWH ::
Custom Search