Java Reference
In-Depth Information
149
// Send player 1's selected row and column to player 2
150
sendMove(toPlayer2, row, column);
151 }
152
153 // Receive a move from Player 2
154 row = fromPlayer2.readInt();
155 column = fromPlayer2.readInt();
156 cell[row][column] = 'O' ;
157
158
// Check if Player 2 wins
159
if (isWon( 'O' )) {
O won?
160
toPlayer1.writeInt(PLAYER2_WON);
161
toPlayer2.writeInt(PLAYER2_WON);
162
sendMove(toPlayer1, row, column);
163
break ;
164 }
165
else {
166
// Notify player 1 to take the turn
167
toPlayer1.writeInt(CONTINUE);
168
169
// Send player 2's selected row and column to player 1
170
sendMove(toPlayer1, row, column);
171 }
172 }
173 }
174 catch (IOException ex) {
175 ex.printStackTrace();
176 }
177 }
178
179
/** Send the move to other player */
180
private void sendMove(DataOutputStream out, int row, int column)
send a move
181
throws IOException {
182
out.writeInt(row); // Send row index
183
out.writeInt(column); // Send column index
184 }
185
186
/** Determine if the cells are all occupied */
187
private boolean isFull() {
188
for ( int i = 0 ; i < 3 ; i++)
189
for ( int j = 0 ; j < 3 ; j++)
190
if (cell[i][j] == ' ' )
191
return false ; // At least one cell is not filled
192
193
// All cells are filled
194
return true ;
195 }
196
197 /** Determine if the player with the specified token wins */
198 private boolean isWon( char token) {
199 // Check all rows
200 for ( int i = 0 ; i < 3 ; i++)
201 if ((cell[i][ 0 ] == token)
202 && (cell[i][ 1 ] == token)
203 && (cell[i][ 2 ] == token)) {
204
return true ;
205 }
206
207
/** Check all columns */
208
for ( int j = 0 ; j < 3 ; j++)
 
Search WWH ::




Custom Search