Java Reference
In-Depth Information
89
private
DataOutputStream toPlayer1;
90
private
DataInputStream fromPlayer2;
91
private
DataOutputStream toPlayer2;
92
93
// Continue to play
94
private boolean
continueToPlay =
true
;
95
96
/** Construct a thread */
97
public
HandleASession(Socket player1, Socket player2) {
98
this
.player1 = player1;
99
this
.player2 = player2;
100
101
// Initialize cells
102
for
(
int
i =
0
; i <
3
; i++)
103
for
(
int
j =
0
; j <
3
; j++)
104 cell[i][j] =
' '
;
105 }
106
107
/** Implement the run() method for the thread */
108
public void
run() {
109
try
{
110
// Create data input and output streams
111 DataInputStream fromPlayer1 =
new
DataInputStream(
112 player1.getInputStream());
113 DataOutputStream toPlayer1 =
new
DataOutputStream(
114 player1.getOutputStream());
115 DataInputStream fromPlayer2 =
new
DataInputStream(
116 player2.getInputStream());
117 DataOutputStream toPlayer2 =
new
DataOutputStream(
118 player2.getOutputStream());
119
120
IO streams
// Write anything to notify player 1 to start
121
// This is just to let player 1 know to start
122
toPlayer1.writeInt(
1
);
123
124
// Continuously serve the players and determine and report
125
// the game status to the players
126
while
(
true
) {
127
// Receive a move from player 1
128
int
row = fromPlayer1.readInt();
129
int
column = fromPlayer1.readInt();
130 cell[row][column] =
'X'
;
131
132
// Check if Player 1 wins
133
if
(isWon(
'X'
)) {
134 toPlayer1.writeInt(PLAYER1_WON);
135 toPlayer2.writeInt(PLAYER1_WON);
136 sendMove(toPlayer2, row, column);
137
X won?
break
;
// Break the loop
138 }
139
else if
(isFull()) {
// Check if all cells are filled
140 toPlayer1.writeInt(DRAW);
141 toPlayer2.writeInt(DRAW);
142 sendMove(toPlayer2, row, column);
143
Is full?
break
;
144 }
145
else
{
146
// Notify player 2 to take the turn
147
toPlayer2.writeInt(CONTINUE);
148
Search WWH ::
Custom Search