-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameStateHandler.java
More file actions
50 lines (44 loc) · 2 KB
/
GameStateHandler.java
File metadata and controls
50 lines (44 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Owen Gregson
// Artificial Intelligence
// TTT Checkpoint #3
// Dec 18, 2024
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
class GameStateHandler implements HttpHandler {
private Game game;
public GameStateHandler(Game game) {
this.game = game;
}
@Override
public void handle(HttpExchange t) throws IOException {
try {
String gameState = game.board.toString();
String response = "{\"gameState\": \"" + gameState + "\","
+ "\"isPlayingAgainstAI\": " + game.isPlayingAgainstAI + ","
+ "\"currentPlayer\": \"" + game.nextPlayer + "\","
+ "\"aiPlayerX\": " + (game.aiPlayerX != null ? "\"X\"" : "\"None\"") + ","
+ "\"aiPlayerO\": " + (game.aiPlayerO != null ? "\"O\"" : "\"None\"") + ","
+ "\"isGameOver\": " + game.isGameOver + ","
+ "\"winner\": " + (game.winner != null ? "\"" + game.winner + "\"" : "null") + ","
+ "\"winningLine\": " + getWinningLinePositions() + "}";
t.getResponseHeaders().add("Content-Type", "application/json");
t.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); // For CORS
t.sendResponseHeaders(200, response.getBytes("UTF-8").length);
OutputStream os = t.getResponseBody();
os.write(response.getBytes("UTF-8"));
os.close();
} catch (Exception e) {
String response = "Internal Server Error: " + e.getMessage();
t.sendResponseHeaders(500, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
e.printStackTrace();
}
}
private String getWinningLinePositions() {
return (game.winningLine == null) ? "null" : game.winningLine.toString().replace("{", "[").replace("}", "]");
}
}