Skip to content

Commit

Permalink
remove class OpenGames
Browse files Browse the repository at this point in the history
  • Loading branch information
h908714124 committed Oct 18, 2024
1 parent fbf6b6f commit 8b35d7c
Show file tree
Hide file tree
Showing 8 changed files with 418 additions and 381 deletions.
60 changes: 25 additions & 35 deletions src/main/java/com/bernd/CleanupController.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.bernd;

import com.bernd.model.Game;
import com.bernd.model.OpenGame;
import com.bernd.model.StatusMap;
import com.bernd.util.Sender;
import java.util.List;
Expand All @@ -12,41 +11,32 @@
@Component
public class CleanupController {

private final Sender sender;
private final StatusMap statusMap;
private final OpenGames openGames;
private final Games games;
private final Sender sender;
private final StatusMap statusMap;
private final Games games;

CleanupController(
Sender sender,
StatusMap statusMap,
OpenGames openGames,
Games games) {
this.sender = sender;
this.statusMap = statusMap;
this.openGames = openGames;
this.games = games;
}

@Scheduled(fixedDelay = 40 * 1000)
public void runScheduled() {
Map<String, List<String>> updatedRooms = statusMap.removeInactiveUsers();
for (Map.Entry<String, List<String>> e : updatedRooms.entrySet()) {
String room = e.getKey();
List<String> users = e.getValue();
sender.sendUsers(room, users);
}
List<Game> games = this.games.games();
for (Game game : games) {
if (updatedRooms.getOrDefault(game.id(), List.of()).isEmpty()) {
this.games.remove(game.id());
}
CleanupController(
Sender sender,
StatusMap statusMap,
Games games) {
this.sender = sender;
this.statusMap = statusMap;
this.games = games;
}
List<OpenGame> openGames = this.openGames.games();
for (OpenGame game : openGames) {
if (!statusMap.contains(game.user())) {
this.openGames.remove(game.user());
}

@Scheduled(fixedDelay = 40 * 1000)
public void runScheduled() {
Map<String, List<String>> updatedRooms = statusMap.removeInactiveUsers();
for (Map.Entry<String, List<String>> e : updatedRooms.entrySet()) {
String room = e.getKey();
List<String> users = e.getValue();
sender.sendUsers(room, users);
}
List<Game> games = this.games.games();
for (Game game : games) {
if (updatedRooms.getOrDefault(game.id(), List.of()).isEmpty()) {
this.games.remove(game.id());
}
}
}
}
}
295 changes: 148 additions & 147 deletions src/main/java/com/bernd/GameController.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.bernd.model.Move;
import com.bernd.model.OpenGame;
import com.bernd.model.StatusMap;
import com.bernd.model.UserStatus;
import com.bernd.model.ViewGame;
import com.bernd.util.Auth;
import com.bernd.util.RandomString;
Expand Down Expand Up @@ -37,167 +38,167 @@
@Controller
public class GameController {

private final MessageSendingOperations<String> operations;
private final RoomManager roomManager;
private final StatusMap statusMap;
private final Games games;
private final OpenGames openGames;
private final ActiveGames activeGames;
private final Chats chats;
private final MessageSendingOperations<String> operations;
private final RoomManager roomManager;
private final StatusMap statusMap;
private final Games games;
private final ActiveGames activeGames;
private final Chats chats;

GameController(
MessageSendingOperations<String> operations,
RoomManager roomManager,
StatusMap statusMap,
Games games,
OpenGames openGames,
ActiveGames activeGames,
Chats chats) {
this.operations = operations;
this.roomManager = roomManager;
this.statusMap = statusMap;
this.games = games;
this.openGames = openGames;
this.activeGames = activeGames;
this.chats = chats;
}

@ResponseBody
@GetMapping(value = "/api/game/{id}")
public ViewGame getGame(@PathVariable String id, Principal p) {
roomManager.updateStatus(Auth.getPrincipal(p), id);
Game game = games.get(id);
if (game == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such game");
GameController(
MessageSendingOperations<String> operations,
RoomManager roomManager,
StatusMap statusMap,
Games games,
ActiveGames activeGames,
Chats chats) {
this.operations = operations;
this.roomManager = roomManager;
this.statusMap = statusMap;
this.games = games;
this.activeGames = activeGames;
this.chats = chats;
}
return game.toView();
}

@MessageMapping("/game/move")
public void action(Move move, Principal p) {
String id = statusMap.getRoom(getPrincipal(p));
if (id == null) {
return;
}
Game game = games.get(id);
if (p == null || game == null) {
return;
}
if (game.gameHasEnded()) {
return;
}
int principalColor = getColorFromPrincipal(game, getPrincipal(p));
if (principalColor == 0) {
return;
}
int color = getColorFromGameState(game);
Chat chat = chats.get(game.id());
if (game.timesetting() != 0
&& !game.isCounting()
&& !game.gameHasEnded()
&& System.currentTimeMillis() > game.updated() + game.timesetting() * 1000L) {
games.put(game.withTimeoutState());
String text = color == Board.W ? "B+Time" : "W+Time";
ChatMessage message = new ChatMessage(chat.counter().getAndIncrement(), text, null, "status", null);
chat.messages().add(message);
operations.convertAndSend("/topic/chat/" + chat.id(), message);
operations.convertAndSend("/topic/move/" + game.id(), game.getLastMove());
return;
}
if (!game.isCounting() && !game.isSelfPlay() && color != principalColor) {
return;
}
if (game.isForbidden(move)) {
return;
@ResponseBody
@GetMapping(value = "/api/game/{id}")
public ViewGame getGame(@PathVariable String id, Principal p) {
roomManager.updateStatus(Auth.getPrincipal(p), id);
Game game = games.get(id);
if (game == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such game");
}
return game.toView();
}
Game updated = game.update(move
.withCount(game.moves().size())
.withColor(game.isSelfPlay() ? color : principalColor));
games.put(updated);
Move lastMove = game.getLastMove();
if (lastMove.end()) {
ChatMessage message = new ChatMessage(chat.counter().getAndIncrement(), game.getScore(), null, "status", null);
chat.messages().add(message);
operations.convertAndSend("/topic/chat/" + chat.id(), message);
}
operations.convertAndSend("/topic/move/" + game.id(), lastMove);
}

private int getColorFromGameState(Game game) {
if (game.remainingHandicap() > 0) {
return Board.B;
}
MoveList moves = game.moves();
if (moves.isEmpty()) {
return Board.B;
@MessageMapping("/game/move")
public void action(Move move, Principal p) {
String id = statusMap.getRoom(getPrincipal(p));
if (id == null) {
return;
}
Game game = games.get(id);
if (p == null || game == null) {
return;
}
if (game.gameHasEnded()) {
return;
}
int principalColor = getColorFromPrincipal(game, getPrincipal(p));
if (principalColor == 0) {
return;
}
int color = getColorFromGameState(game);
Chat chat = chats.get(game.id());
if (game.timesetting() != 0
&& !game.isCounting()
&& !game.gameHasEnded()
&& System.currentTimeMillis() > game.updated() + game.timesetting() * 1000L) {
games.put(game.withTimeoutState());
String text = color == Board.W ? "B+Time" : "W+Time";
ChatMessage message = new ChatMessage(chat.counter().getAndIncrement(), text, null, "status", null);
chat.messages().add(message);
operations.convertAndSend("/topic/chat/" + chat.id(), message);
operations.convertAndSend("/topic/move/" + game.id(), game.getLastMove());
return;
}
if (!game.isCounting() && !game.isSelfPlay() && color != principalColor) {
return;
}
if (game.isForbidden(move)) {
return;
}
Game updated = game.update(move
.withCount(game.moves().size())
.withColor(game.isSelfPlay() ? color : principalColor));
games.put(updated);
Move lastMove = game.getLastMove();
if (lastMove.end()) {
ChatMessage message = new ChatMessage(chat.counter().getAndIncrement(), game.getScore(), null, "status", null);
chat.messages().add(message);
operations.convertAndSend("/topic/chat/" + chat.id(), message);
}
operations.convertAndSend("/topic/move/" + game.id(), lastMove);
}
return moves.get(moves.size() - 1).color() ^ COLORS;
}

private static int getColorFromPrincipal(Game game, String principal) {
if (game.isBlack(principal)) {
return Board.B;
private int getColorFromGameState(Game game) {
if (game.remainingHandicap() > 0) {
return Board.B;
}
MoveList moves = game.moves();
if (moves.isEmpty()) {
return Board.B;
}
return moves.get(moves.size() - 1).color() ^ COLORS;
}
if (game.isWhite(principal)) {
return Board.W;

private static int getColorFromPrincipal(Game game, String principal) {
if (game.isBlack(principal)) {
return Board.B;
}
if (game.isWhite(principal)) {
return Board.W;
}
return 0;
}
return 0;
}

@ResponseBody
@PostMapping(value = "/api/create", consumes = "application/json")
public OpenGame newGame(@RequestBody OpenGame game) {
String principal = getPrincipal();
OpenGame result = openGames.put(game.withUser(principal)
.withId(RandomString.get()));
operations.convertAndSend("/topic/lobby/open_games", Map.of("games", openGames.games()));
return result;
}
@ResponseBody
@PostMapping(value = "/api/create", consumes = "application/json")
public OpenGame newGame(@RequestBody OpenGame game) {
String principal = getPrincipal();
UserStatus result = statusMap.openGame(game.withUser(principal)
.withId(RandomString.get()));
if (result == null) {
return null;
}
operations.convertAndSend("/topic/lobby/open_games", Map.of("games", statusMap.openGames()));
return result.openGame();
}

@PostMapping(value = "/api/lobby/start", consumes = "application/json")
public ResponseEntity<?> start(@RequestBody AcceptRequest acceptRequest) {
String principal = getPrincipal();
openGames.remove(acceptRequest.opponent());
OpenGame openGame = openGames.remove(principal);
Game fullGame = games.put(openGame.accept(acceptRequest));
Chat chat = chats.get(openGame.id());
@PostMapping(value = "/api/lobby/start", consumes = "application/json")
public ResponseEntity<?> start(@RequestBody AcceptRequest acceptRequest) {
String principal = getPrincipal();
statusMap.removeOpenGame(acceptRequest.opponent());
OpenGame openGame = statusMap.removeOpenGame(principal);
Game fullGame = games.put(openGame.accept(acceptRequest));
Chat chat = chats.get(openGame.id());

ChatMessage startMessage = ChatMessage.createStartMessage(chat, fullGame);
chat.messages().add(startMessage);
operations.convertAndSend("/topic/chat/" + chat.id(), startMessage);
operations.convertAndSend("/topic/gamestart", Map.of(
"players", List.of(principal, acceptRequest.opponent()),
"id", openGame.id()));
operations.convertAndSend("/topic/lobby/open_games", Map.of("games", openGames.games()));
operations.convertAndSend("/topic/lobby/active_games", Map.of("games", activeGames.games()));
return ResponseEntity.ok().build();
}
ChatMessage startMessage = ChatMessage.createStartMessage(chat, fullGame);
chat.messages().add(startMessage);
operations.convertAndSend("/topic/chat/" + chat.id(), startMessage);
operations.convertAndSend("/topic/gamestart", Map.of(
"players", List.of(principal, acceptRequest.opponent()),
"id", openGame.id()));
operations.convertAndSend("/topic/lobby/open_games", Map.of("games", statusMap.openGames()));
operations.convertAndSend("/topic/lobby/active_games", Map.of("games", activeGames.games()));
return ResponseEntity.ok().build();
}

@ResponseBody
@PostMapping(value = "/api/challenge", consumes = "application/json")
public Map<String, List<AcceptRequest>> challenge(@RequestBody AcceptRequest acceptRequest) {
String principal = getPrincipal();
openGames.remove(principal);
OpenGame openGame = openGames.addRequest(acceptRequest.game().user(), acceptRequest, principal);
operations.convertAndSend("/topic/lobby/requests", Map.of("requests", openGame.requests()));
return Map.of("requests", openGame.requests());
}
@ResponseBody
@PostMapping(value = "/api/challenge", consumes = "application/json")
public Map<String, List<AcceptRequest>> challenge(@RequestBody AcceptRequest acceptRequest) {
String principal = getPrincipal();
statusMap.removeOpenGame(principal);
UserStatus status = statusMap.addRequest(acceptRequest.game().user(), acceptRequest, principal);
operations.convertAndSend("/topic/lobby/requests", Map.of("requests", status.requests()));
return Map.of("requests", status.requests());
}

@ResponseBody
@GetMapping(value = "/api/lobby/requests")
public Map<String, List<AcceptRequest>> getRequests() {
String principal = getPrincipal();
return Map.of("requests", openGames.getRequests(principal));
}
@ResponseBody
@GetMapping(value = "/api/lobby/requests")
public Map<String, List<AcceptRequest>> getRequests() {
String principal = getPrincipal();
return Map.of("requests", statusMap.getRequests(principal));
}

@GetMapping("/api/sgf/{id}/{black}_vs_{white}.sgf")
public ResponseEntity<String> getSgf(
@PathVariable String id) {
Game game = games.get(id);
if (game == null) {
return ResponseEntity.notFound().build();
@GetMapping("/api/sgf/{id}/{black}_vs_{white}.sgf")
public ResponseEntity<String> getSgf(
@PathVariable String id) {
Game game = games.get(id);
if (game == null) {
return ResponseEntity.notFound().build();
}
String sgf = SgfCreator.createSgf(game, LocalDate.now());
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(sgf);
}
String sgf = SgfCreator.createSgf(game, LocalDate.now());
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(sgf);
}
}
Loading

0 comments on commit 8b35d7c

Please sign in to comment.