Compare commits

..

No commits in common. "trunk" and "v0.0.0-rc.6" have entirely different histories.

30 changed files with 137 additions and 826 deletions

View file

@ -1,13 +0,0 @@
package de.towerdefence.server.match;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public class Enemy {
private int poxX;
private int posY;
}

View file

@ -1,54 +0,0 @@
package de.towerdefence.server.match;
import de.towerdefence.server.match.callbacks.PlayerHitpointsCallback;
import de.towerdefence.server.match.callbacks.PlayerMoneyCallback;
import de.towerdefence.server.match.exeptions.InvalidPlacementException;
import de.towerdefence.server.match.exeptions.InvalidPlacementReason;
import de.towerdefence.server.player.Player;
import lombok.Getter;
public class GameSession {
final static int START_HITPOINTS = 100;
final static int START_MONEY = 50;
final static int MAP_SIZE_X = 10;
final static int MAP_SIZE_Y = 20;
private final Tower[][] towers = new Tower[MAP_SIZE_X][MAP_SIZE_Y];
private final Player player;
@Getter
private int money;
@Getter
private int playerHitpoints;
private final PlayerMoneyCallback moneyCallback;
//private final PlayerHitpointsCallback hitpointsCallback;
public GameSession(Player player, PlayerMoneyCallback moneyCallback) {
this.player = player;
this.moneyCallback = moneyCallback;
//this.hitpointsCallback = hitpointsCallback;
this.money = START_MONEY;
this.playerHitpoints = START_HITPOINTS;
}
public void placeTower(Tower tower, int x, int y) throws InvalidPlacementException {
if (x < 0 || y < 0 || x + 1 > MAP_SIZE_X || y + 1 > MAP_SIZE_Y) {
throw new InvalidPlacementException(InvalidPlacementReason.OUT_OF_BOUNDS);
}
if (towers[x][y] != null) {
throw new InvalidPlacementException(InvalidPlacementReason.LOCATION_USED);
}
if (money < Tower.COST) {
throw new InvalidPlacementException(InvalidPlacementReason.NOT_ENOUGH_MONEY);
}
money -= Tower.COST;
moneyCallback.call(player, money);
towers[x][y] = tower;
}
public void addMoney(int amount) {
money += amount;
moneyCallback.call(player, money);
}
}

View file

@ -1,74 +1,13 @@
package de.towerdefence.server.match;
import de.towerdefence.server.match.callbacks.PlayerHitpointsCallback;
import de.towerdefence.server.match.callbacks.PlayerMoneyCallback;
import de.towerdefence.server.player.Player;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Optional;
@AllArgsConstructor
@Getter
public class Match {
private final String matchId;
private final Player player1;
private final Player player2;
private GameSession player1Session;
private GameSession player2Session;
public Match(String matchId, Player player1, Player player2) {
this.matchId = matchId;
this.player1 = player1;
this.player2 = player2;
}
public Optional<Player> getOpponent(Player player) {
boolean isPlayer1 = player1.equals(player);
boolean isPlayer2 = player2.equals(player);
if (!isPlayer1 && !isPlayer2) {
return Optional.empty();
}
if (isPlayer1) {
return Optional.of(player2);
}
return Optional.of(player1);
}
public Optional<GameSession> getPlayerGameSession(Player player) {
boolean isPlayer1 = player1.equals(player);
boolean isPlayer2 = player2.equals(player);
if (!isPlayer1 && !isPlayer2) {
return Optional.empty();
}
if (isPlayer1) {
return Optional.of(player1Session);
}
return Optional.of(player2Session);
}
public void connectPlayer(
Player player,
PlayerMoneyCallback moneyCallback,
PlayerHitpointsCallback hitpointsCallback
) {
boolean isPlayer1 = player1.equals(player);
boolean isPlayer2 = player2.equals(player);
if (!isPlayer1 && !isPlayer2) {
return;
}
if (isPlayer1 && player1Session == null) {
this.player1Session = new GameSession(player, moneyCallback);
return;
}
if (isPlayer2 && player2Session == null) {
this.player2Session = new GameSession(player, moneyCallback);
return;
}
}
public boolean hasMatchStarted() {
return player1Session != null && player2Session != null;
}
private final Player playerOne;
private final Player playerTwo;
}

View file

@ -1,89 +0,0 @@
package de.towerdefence.server.match;
import de.towerdefence.server.match.callbacks.PlayerHitpointsCallback;
import de.towerdefence.server.match.callbacks.PlayerMoneyCallback;
import de.towerdefence.server.match.exeptions.InvalidPlacementException;
import de.towerdefence.server.match.exeptions.InvalidPlacementReason;
import de.towerdefence.server.match.exeptions.NotInMatchException;
import de.towerdefence.server.player.Player;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;
@Service
public class MatchService {
private final Map<Player, Match> playerMatches = new HashMap<>();
private final Map<Match, ScheduledFuture<?>> moneyTasks = new HashMap<>();
private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public void createMatch(String matchId, Player player1, Player player2) {
Match match = new Match(matchId, player1, player2);
playerMatches.put(player1, match);
playerMatches.put(player2, match);
}
public Match get(Player player) {
return playerMatches.get(player);
}
/**
* @return opponent
*/
public Player placeTower(Player player, int x, int y) throws NotInMatchException, InvalidPlacementException {
Match match = playerMatches.get(player);
if (!match.hasMatchStarted()) {
throw new InvalidPlacementException(InvalidPlacementReason.MATCH_NOT_STARTED);
}
Optional<GameSession> playerSession = match.getPlayerGameSession(player);
if (playerSession.isEmpty()) {
throw new NotInMatchException();
}
Optional<Player> opponent = match.getOpponent(player);
if (opponent.isEmpty()) {
throw new NotInMatchException();
}
playerSession.get().placeTower(new Tower(), x, y);
return opponent.get();
}
public void playerConnected(
Player player,
PlayerMoneyCallback moneyCallback,
PlayerHitpointsCallback hitpointsCallback
) {
Match match = playerMatches.get(player);
match.connectPlayer(player, moneyCallback, hitpointsCallback);
Optional<GameSession> optionalPlayerSession = match.getPlayerGameSession(player);
if (optionalPlayerSession.isEmpty()) {
return;
}
GameSession playerSession = optionalPlayerSession.get();
moneyCallback.call(player, playerSession.getMoney());
hitpointsCallback.call(player, playerSession.getPlayerHitpoints() );
if (!match.hasMatchStarted()) {
return;
}
Optional<Player> optionalOpponent = match.getOpponent(player);
if (optionalOpponent.isEmpty()) {
return;
}
Player opponent = optionalOpponent.get();
Optional<GameSession> optionalOpponentSession = match.getPlayerGameSession(opponent);
if (optionalOpponentSession.isEmpty()) {
return;
}
GameSession opponentSession = optionalOpponentSession.get();
ScheduledFuture<?> moneyTask = scheduler.scheduleAtFixedRate(
() -> {
playerSession.addMoney(3);
opponentSession.addMoney(3);
},
5,
5,
TimeUnit.SECONDS);
moneyTasks.put(match, moneyTask);
}
}

View file

@ -1,5 +0,0 @@
package de.towerdefence.server.match;
public class Tower {
public static final int COST = 20;
}

View file

@ -1,8 +0,0 @@
package de.towerdefence.server.match.callbacks;
import de.towerdefence.server.player.Player;
@FunctionalInterface
public interface PlayerHitpointsCallback {
void call(Player player, int playerHitpoints);
}

View file

@ -1,8 +0,0 @@
package de.towerdefence.server.match.callbacks;
import de.towerdefence.server.player.Player;
@FunctionalInterface
public interface PlayerMoneyCallback {
void call(Player player, int playerMoney);
}

View file

@ -1,76 +1,28 @@
package de.towerdefence.server.match.confirmation;
import de.towerdefence.server.match.MatchService;
import de.towerdefence.server.player.Player;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;
@AllArgsConstructor
@Service
public class MatchConfirmationService {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final Map<Player, UnconfirmedMatch> unconfirmedMatch = new HashMap<>();
final Map<UnconfirmedMatch, ScheduledFuture<?>> matchAbortTasks = new ConcurrentHashMap<>();
@Autowired
private final MatchService matchService;
private final Map<Player, UnconfirmedMatch> unconfirmedMatch = new HashMap<>();
public UnconfirmedMatch createMatch(Player player1,
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2Callbacks) {
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2callbacks) {
UnconfirmedMatch match = new UnconfirmedMatch(
player1,
player2,
player1Callbacks,
player2Callbacks);
player1,
player2,
player1Callbacks,
player2callbacks);
unconfirmedMatch.put(player1, match);
unconfirmedMatch.put(player2, match);
ScheduledFuture<?> scheduledTask = scheduler.schedule(
() -> {
matchAbortTasks.remove(match);
unconfirmedMatch.remove(match.getPlayer1());
unconfirmedMatch.remove(match.getPlayer2());
if (match.getPlayer1State() == PlayerMatchConfirmState.CONFIRMED ) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
} else {
player1Callbacks.getAbortCallback().call(
match.getPlayer1(),
match.getMatchId()
);
}
if (match.getPlayer2State() == PlayerMatchConfirmState.CONFIRMED) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
} else {
player2Callbacks.getAbortCallback().call(
match.getPlayer2(),
match.getMatchId()
);
}
},
UnconfirmedMatch.TTL,
TimeUnit.MILLISECONDS
);
matchAbortTasks.put(match, scheduledTask);
return match;
}
@ -111,8 +63,6 @@ public class MatchConfirmationService {
if (state == UnconfirmedMatchState.WAITING) {
return;
}
matchAbortTasks.get(match).cancel(true);
matchAbortTasks.remove(match);
unconfirmedMatch.remove(match.getPlayer1());
unconfirmedMatch.remove(match.getPlayer2());
@ -121,91 +71,30 @@ public class MatchConfirmationService {
ConfirmationCallbacks player2Callbacks = match.getPlayer2Callbacks();
switch (state) {
case ABORTED -> {
if (match.getPlayer1State() != PlayerMatchConfirmState.ABORTED ) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
} else {
player1Callbacks.getAbortCallback().call(
match.getPlayer1(),
match.getMatchId()
);
}
if (match.getPlayer2State() != PlayerMatchConfirmState.ABORTED) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
} else {
player2Callbacks.getAbortCallback().call(
match.getPlayer2(),
match.getMatchId()
);
}
}
case CONFIRMED -> {
boolean player1successful = sendPlayerEstablished(
match.getMatchId(),
player1Callbacks.getEstablishedCallback(),
match.getPlayer1(),
match.getPlayer2()
);
boolean player2successful = sendPlayerEstablished(
match.getMatchId(),
player2Callbacks.getEstablishedCallback(),
match.getPlayer2(),
match.getPlayer1()
);
if (!player1successful || !player2successful) {
if (player1successful) {
case ABORTED -> {
if (match.getPlayer1State() == PlayerMatchConfirmState.CONFIRMED) {
player1Callbacks.getRequeueCallback().call(
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
match.getPlayer1(),
match.getMatchId(),
player1Callbacks.getFoundCallback(),
player1Callbacks.getQueuedCallback(),
player1Callbacks.getAbortCallback(),
player1Callbacks.getEstablishedCallback());
}
if (player2successful) {
if (match.getPlayer2State() == PlayerMatchConfirmState.CONFIRMED) {
player2Callbacks.getRequeueCallback().call(
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
match.getPlayer2(),
match.getMatchId(),
player2Callbacks.getFoundCallback(),
player2Callbacks.getQueuedCallback(),
player2Callbacks.getAbortCallback(),
player2Callbacks.getEstablishedCallback());
}
return;
}
matchService.createMatch(match.getMatchId(), match.getPlayer1(), match.getPlayer2());
case CONFIRMED -> {
// TODO: Create Match and Send Players the info that the Match is created
}
}
}
}
/**
* @return if successful
*/
private boolean sendPlayerEstablished(
String matchId,
EstablishedCallback callback,
Player player,
Player opponent
) {
try {
callback.call(player, matchId, opponent);
} catch (IOException ignored) {
return false;
}
return true;
}
private Optional<UnconfirmedMatch> getPlayerMatch(Player player, String matchId) {

View file

@ -18,10 +18,10 @@ public class UnconfirmedMatch {
private final ConfirmationCallbacks player2Callbacks;
public UnconfirmedMatch(
Player player1,
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2Callbacks) {
Player player1,
Player player2,
ConfirmationCallbacks player1Callbacks,
ConfirmationCallbacks player2Callbacks) {
this.player1 = player1;
this.player2 = player2;
this.player1Callbacks = player1Callbacks;
@ -35,21 +35,16 @@ public class UnconfirmedMatch {
public Optional<UnconfirmedMatchState> setPlayerConfirmState(Player player, PlayerMatchConfirmState state) {
Optional<MatchPlayer> matchPlayer = getMatchPlayer(player);
if (matchPlayer.isEmpty()) {
if(matchPlayer.isEmpty()){
return Optional.empty();
}
switch (matchPlayer.get()) {
case ONE -> player1State = state;
case TWO -> player2State = state;
switch (matchPlayer.get()){
case ONE -> player1State = state;
case TWO -> player2State = state;
}
boolean timedOut = Instant.now().toEpochMilli() > created + TTL;
if (
timedOut
|| player1State == PlayerMatchConfirmState.ABORTED
|| player2State == PlayerMatchConfirmState.ABORTED
) {
if (player1State == PlayerMatchConfirmState.ABORTED || player2State == PlayerMatchConfirmState.ABORTED) {
return Optional.of(UnconfirmedMatchState.ABORTED);
}
if (player1State == PlayerMatchConfirmState.UNKNOWN || player2State == PlayerMatchConfirmState.UNKNOWN) {
@ -58,31 +53,31 @@ public class UnconfirmedMatch {
return Optional.of(UnconfirmedMatchState.CONFIRMED);
}
public Optional<PlayerMatchConfirmState> getPlayerState(Player player) {
public Optional<PlayerMatchConfirmState> getPlayerState(Player player){
Optional<MatchPlayer> matchPlayer = getMatchPlayer(player);
if (matchPlayer.isEmpty()) {
if(matchPlayer.isEmpty()){
return Optional.empty();
}
return switch (matchPlayer.get()) {
return switch (matchPlayer.get()){
case ONE -> Optional.of(player1State);
case TWO -> Optional.of(player2State);
};
}
private enum MatchPlayer {
private enum MatchPlayer{
ONE,
TWO
}
private Optional<MatchPlayer> getMatchPlayer(Player player) {
private Optional<MatchPlayer> getMatchPlayer(Player player){
boolean isPlayerOne = player.equals(player1);
boolean isPlayerTwo = player.equals(player2);
if (!isPlayerOne && !isPlayerTwo) {
return Optional.empty();
}
if (isPlayerOne) {
if (isPlayerOne){
return Optional.of(MatchPlayer.ONE);
}
return Optional.of(MatchPlayer.TWO);

View file

@ -1,10 +0,0 @@
package de.towerdefence.server.match.exeptions;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class InvalidPlacementException extends RuntimeException {
private final InvalidPlacementReason reason;
}

View file

@ -1,15 +0,0 @@
package de.towerdefence.server.match.exeptions;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum InvalidPlacementReason {
MATCH_NOT_STARTED("match-not-started"),
OUT_OF_BOUNDS("out-of-bounds"),
LOCATION_USED("location-used"),
NOT_ENOUGH_MONEY("not-enough-money");
private final String jsonName;
}

View file

@ -1,4 +0,0 @@
package de.towerdefence.server.match.exeptions;
public class NotInMatchException extends RuntimeException {
}

View file

@ -39,7 +39,6 @@ public abstract class JsonWebsocketHandler extends TextWebSocketHandler {
protected void closeSession(WebSocketSession session, CloseStatus reason){
if(session.isOpen()){
try{
sessionPlayers.remove(session);
session.close(reason);
} catch (Exception exception) {
logger.info("Unable to Close the Session", exception);

View file

@ -1,12 +1,11 @@
package de.towerdefence.server.server.channels;
import de.towerdefence.server.match.MatchService;
import de.towerdefence.server.match.confirmation.MatchConfirmationService;
import de.towerdefence.server.match.queue.MatchQueueService;
import de.towerdefence.server.server.JsonWebsocketHandler;
import de.towerdefence.server.server.channels.connection.ConnectionWebsocketHandler;
import de.towerdefence.server.server.channels.match.MatchWebsocketHandler;
import de.towerdefence.server.server.channels.matchmaking.MatchmakingWebsocketHandler;
import de.towerdefence.server.server.channels.time.TimeWebsocketHandler;
import de.towerdefence.server.session.SessionsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
@ -26,8 +25,6 @@ public class WebsocketConfig implements WebSocketConfigurer {
private final MatchQueueService matchQueueService;
@Autowired
private final MatchConfirmationService matchConfirmationService;
@Autowired
private final MatchService matchService;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
@ -37,7 +34,7 @@ public class WebsocketConfig implements WebSocketConfigurer {
this.matchQueueService,
this.matchConfirmationService
));
registerJsonChannel(registry, new MatchWebsocketHandler(this.sessionsService, this.matchService));
registerJsonChannel(registry, new TimeWebsocketHandler(this.sessionsService));
}
private void registerJsonChannel(WebSocketHandlerRegistry registry, JsonWebsocketHandler handler){

View file

@ -34,9 +34,6 @@ public class ConnectionWebsocketHandler extends JsonWebsocketHandler {
private void handleRequestConnectionToken(WebSocketSession session, String payload) throws Exception {
RequestConnectionTokenMessage msg = objectMapper.readValue(payload, RequestConnectionTokenMessage.class);
Player player = this.sessionPlayers.get(session);
if (msg.getChannel() != Channel.MATCHMAKING) {
return;
}
String jwt = this.sessionsService.createSession(player, msg.getChannel());
new ProvidedConnectionTokenMessage(msg.getChannel(), jwt).send(session);
}

View file

@ -1,112 +0,0 @@
package de.towerdefence.server.server.channels.match;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.towerdefence.server.match.MatchService;
import de.towerdefence.server.match.exeptions.InvalidPlacementException;
import de.towerdefence.server.match.exeptions.NotInMatchException;
import de.towerdefence.server.player.Player;
import de.towerdefence.server.server.JsonWebsocketHandler;
import de.towerdefence.server.server.channels.match.hitpoints.PlayerHitpointsMessage;
import de.towerdefence.server.server.channels.match.money.PlayerMoneyMessage;
import de.towerdefence.server.server.channels.match.placing.GamePlayerMap;
import de.towerdefence.server.server.channels.match.placing.InvalidPlacementMessage;
import de.towerdefence.server.server.channels.match.placing.RequestTowerPlacingMessage;
import de.towerdefence.server.server.channels.match.placing.TowerPlacedMessage;
import de.towerdefence.server.session.Channel;
import de.towerdefence.server.session.SessionsService;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public class MatchWebsocketHandler extends JsonWebsocketHandler {
protected final Map<Player, WebSocketSession> playerSessions = new ConcurrentHashMap<>();
private final MatchService matchService;
private final ObjectMapper objectMapper = new ObjectMapper();
public MatchWebsocketHandler(SessionsService sessionsService, MatchService matchService) {
super(Channel.MATCH, sessionsService);
this.matchService = matchService;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
super.afterConnectionEstablished(session);
playerSessions.put(sessionPlayers.get(session), session);
matchService.playerConnected(
sessionPlayers.get(session),
this::onPlayerMoneyChanged,
this::onPlayerHitpointsChanged
);
}
private void onPlayerMoneyChanged(Player player, int playerMoney) {
WebSocketSession session = playerSessions.get(player);
try {
new PlayerMoneyMessage(playerMoney).send(session);
} catch (IOException ignored) {
}
}
private void onPlayerHitpointsChanged(Player player, int playerHitpoints) {
WebSocketSession session = playerSessions.get(player);
try {
new PlayerHitpointsMessage(playerHitpoints).send(session);
} catch (IOException ignored) {
}
}
@Override
protected void closeSession(WebSocketSession session, CloseStatus reason) {
Player player = sessionPlayers.get(session);
super.closeSession(session, reason);
playerSessions.remove(player);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
try {
String payload = message.getPayload();
if (!Objects.equals(
objectMapper.readTree(payload).get("$id").asText(),
RequestTowerPlacingMessage.MESSAGE_ID
)) {
this.closeSession(session, CloseStatus.BAD_DATA);
return;
}
handleRequestTowerPlacingMessage(session, payload);
} catch (IOException ignored) {
this.closeSession(session, CloseStatus.BAD_DATA);
}
}
private void handleRequestTowerPlacingMessage(
WebSocketSession session,
String payload
) throws IOException {
RequestTowerPlacingMessage msg = objectMapper.readValue(payload, RequestTowerPlacingMessage.class);
Player opponent;
try {
opponent = this.matchService.placeTower(
this.sessionPlayers.get(session),
msg.getX(),
msg.getY()
);
} catch (InvalidPlacementException exception) {
new InvalidPlacementMessage(msg.getX(), msg.getY(), exception.getReason()).send(session);
return;
} catch (NotInMatchException ignored) {
this.closeSession(session, CloseStatus.BAD_DATA);
return;
}
WebSocketSession opponentSession = playerSessions.get(opponent);
new TowerPlacedMessage(msg.getX(), msg.getY(), GamePlayerMap.PLAYER).send(session);
new TowerPlacedMessage(msg.getX(), msg.getY(), GamePlayerMap.OPPONENT).send(opponentSession);
}
}

View file

@ -1,25 +0,0 @@
package de.towerdefence.server.server.channels.match.hitpoints;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import de.towerdefence.server.server.JsonMessage;
import lombok.AllArgsConstructor;
import java.util.Map;
@AllArgsConstructor
public class PlayerHitpointsMessage extends JsonMessage {
private final int playerHitpoints;
@Override
protected String getMessageId() {
return "PlayerHitpoints";
}
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(
"playerHitpoints", factory.numberNode(this.playerHitpoints)
);
}
}

View file

@ -1,13 +0,0 @@
package de.towerdefence.server.server.channels.match.placing;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum GamePlayerMap {
PLAYER("player"),
OPPONENT("opponent");
private final String jsonName;
}

View file

@ -1,31 +0,0 @@
package de.towerdefence.server.server.channels.match.placing;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import de.towerdefence.server.match.exeptions.InvalidPlacementReason;
import de.towerdefence.server.server.JsonMessage;
import lombok.AllArgsConstructor;
import java.util.Map;
@AllArgsConstructor
public class InvalidPlacementMessage extends JsonMessage {
private final int x;
private final int y;
private final InvalidPlacementReason reason;
@Override
protected String getMessageId() {
return "InvalidPlacement";
}
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(
"x", factory.numberNode(this.x),
"y", factory.numberNode(this.y),
"reason", factory.textNode(this.reason.getJsonName()));
}
}

View file

@ -1,16 +0,0 @@
package de.towerdefence.server.server.channels.match.placing;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
@NotNull
public class RequestTowerPlacingMessage {
public static final String MESSAGE_ID = "RequestTowerPlacing";
@JsonProperty("$id")
private String messageId;
private int x;
private int y;
}

View file

@ -1,30 +0,0 @@
package de.towerdefence.server.server.channels.match.placing;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import de.towerdefence.server.server.JsonMessage;
import lombok.AllArgsConstructor;
import java.util.Map;
@AllArgsConstructor
public class TowerPlacedMessage extends JsonMessage {
private final int x;
private final int y;
private final GamePlayerMap map;
@Override
protected String getMessageId() {
return "TowerPlaced";
}
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(
"x", factory.numberNode(this.x),
"y", factory.numberNode(this.y),
"map", factory.textNode(this.map.getJsonName())
);
}
}

View file

@ -46,7 +46,6 @@ public class MatchmakingWebsocketHandler extends JsonWebsocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
try {
String payload = message.getPayload();
switch (objectMapper.readTree(payload).get("$id").asText()) {
case MatchSetSearchStateMessage.MESSAGE_ID -> handleMatchSetSearchStateMessage(session, payload);
@ -97,8 +96,7 @@ public class MatchmakingWebsocketHandler extends JsonWebsocketHandler {
private void onEstablished(Player player, String matchId, Player opponent) throws IOException {
WebSocketSession session = playerSessions.get(player);
String token = this.sessionsService.createSession(player, Channel.MATCH);
MatchEstablishedMessage msg = new MatchEstablishedMessage(matchId, opponent.getUsername(), token);
MatchEstablishedMessage msg = new MatchEstablishedMessage(matchId, opponent.getUsername());
msg.send(session);
}

View file

@ -1,6 +1,5 @@
package de.towerdefence.server.server.channels.matchmaking.bi;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
@ -13,6 +12,7 @@ import java.util.Map;
@Getter
@NotNull
@AllArgsConstructor
public class MatchSetSearchStateMessage extends JsonMessage {
public static final String MESSAGE_ID = "MatchSetSearchState";
@ -26,15 +26,6 @@ public class MatchSetSearchStateMessage extends JsonMessage {
this(MESSAGE_ID, searching);
}
@JsonCreator
public MatchSetSearchStateMessage(
@JsonProperty("$id") String messageId,
@JsonProperty("searching") boolean searching
) {
this.messageId = messageId;
this.searching = searching;
}
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(

View file

@ -11,7 +11,6 @@ import java.util.Map;
public class MatchEstablishedMessage extends JsonMessage {
private String matchId;
private String opponentName;
private String token;
@Override
protected String getMessageId() {
@ -21,9 +20,8 @@ public class MatchEstablishedMessage extends JsonMessage {
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(
"matchId", factory.textNode(this.matchId),
"opponentName", factory.textNode(this.opponentName),
"token", factory.textNode(this.token)
"matchId", factory.textNode(this.matchId),
"opponentName", factory.textNode(this.opponentName)
);
}
}

View file

@ -1,4 +1,4 @@
package de.towerdefence.server.server.channels.match.money;
package de.towerdefence.server.server.channels.time;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
@ -8,19 +8,16 @@ import lombok.AllArgsConstructor;
import java.util.Map;
@AllArgsConstructor
public class PlayerMoneyMessage extends JsonMessage {
private final int playerMoney;
public class TimeMessage extends JsonMessage {
private final long time;
@Override
protected String getMessageId() {
return "PlayerMoney";
return "CurrentUnixTime";
}
@Override
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
return Map.of(
"playerMoney", factory.numberNode(this.playerMoney)
);
return Map.of("time", factory.numberNode(this.time));
}
}

View file

@ -0,0 +1,46 @@
package de.towerdefence.server.server.channels.time;
import de.towerdefence.server.server.JsonWebsocketHandler;
import de.towerdefence.server.session.Channel;
import de.towerdefence.server.session.SessionsService;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.*;
public class TimeWebsocketHandler extends JsonWebsocketHandler {
private final Map<WebSocketSession, ScheduledFuture<?>> sessionTaskMap = new ConcurrentHashMap<>();
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public TimeWebsocketHandler(SessionsService sessionsService) {
super(Channel.TIME, sessionsService);
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
super.afterConnectionEstablished(session);
ScheduledFuture<?> scheduledTask = scheduler.scheduleAtFixedRate(
() -> sendCurrentTime(session),
0,
1,
TimeUnit.MILLISECONDS
);
sessionTaskMap.put(session, scheduledTask);
}
private void sendCurrentTime(WebSocketSession session) {
ScheduledFuture<?> task = sessionTaskMap.get(session);
try {
if(!session.isOpen()){
throw new RuntimeException("Session is not open");
}
new TimeMessage(System.currentTimeMillis()).send(session);
} catch (RuntimeException | IOException e) {
task.cancel(true);
sessionTaskMap.remove(session);
}
}
}

View file

@ -9,7 +9,7 @@ import lombok.Getter;
public enum Channel {
CONNECTION("connection"),
MATCHMAKING("matchmaking"),
MATCH("match");
TIME("time");
private final String jsonName;

View file

@ -14,15 +14,4 @@
<Class name="de.towerdefence.server.session.JwtService"/>
<Bug code="M,B,CT"/>
</Match>
<Match>
<!-- Spotbugs does not detect that the other cases are handled above in an if-->
<Class name="de.towerdefence.server.match.confirmation.MatchConfirmationService"/>
<Bug code="M,D,SF"/>
</Match>
<Match>
<!-- This is Only a Placeholder Object, thus it's not a bad practice to instance it-->
<Class name="de.towerdefence.server.match.MatchService"/>
<Method name="placeTower"/>
<Bug code="L,B,ISC"/>
</Match>
</FindBugsFilter>

17
ws/example/time_channel.sh Executable file
View file

@ -0,0 +1,17 @@
#!/bin/sh
response=$(curl -s -X 'POST' \
'http://localhost:8080/api/v1/player/login' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"username": "Player1",
"password": "1234"
}')
token=$(echo "$response" | jq -r .token)
payload='{"$id": "RequestConnectionToken", "channel": "time"}'
response=$(echo "$payload" | websocat ws://localhost:8080/ws/connection -H "Authorization: $token")
time_token=$(echo "$response" | jq -r .token)
websocat ws://localhost:8080/ws/time -H "Authorization: $time_token"

142
ws/ws.yml
View file

@ -66,7 +66,7 @@ channels:
matchmaking:
title: Matchmaking
description: |
description: |
A Channel used to search for a match and
to receive one
messages:
@ -147,21 +147,19 @@ channels:
type: string
opponentName:
type: string
token:
$ref: "#/components/schemas/JWT"
required:
- $id
- matchId
- opponentName
- token
match:
title: Match
time:
title: Time
description: |
Channel for managing an active match
A Simple example channel for receiving
the current Unix time
messages:
RequestTowerPlacing:
description: Requesting a placement of a tower
CurrentUnixTime:
description: The Current time in Unix Time
payload:
type: object
additionalProperties: false
@ -169,92 +167,12 @@ channels:
$id:
type: string
format: messageId
x:
type: integer
y:
time:
type: integer
format: int64
required:
- $id
- x
- y
TowerPlaced:
description: A tower was placed
payload:
type: object
additionalProperties: false
properties:
$id:
type: string
format: messageId
x:
type: integer
y:
type: integer
map:
type: string
enum:
- player
- opponent
required:
- $id
- x
- y
- map
InvalidPlacement:
description: A tower was placed
payload:
type: object
additionalProperties: false
properties:
$id:
type: string
format: messageId
x:
type: integer
y:
type: integer
reason:
type: string
enum:
- "match-not-started"
- "out-of-bounds"
- "location-used"
- "not-enough-money"
required:
- $id
- x
- y
- reason
PlayerMoney:
description: Money a player currently has
payload:
type: object
additionalProperties: false
properties:
$id:
type: string
format: messageId
playerMoney:
type: integer
required:
- $id
- playerMoney
PlayerHitpoints:
description: Hitpoints a player currently has
payload:
type: object
additionalProperties: false
properties:
$id:
type: string
format: messageId
playerHitpoints:
type: integer
required:
- $id
- playerHitpoints
- time
operations:
requestConnectionToken:
@ -309,42 +227,13 @@ operations:
$ref: "#/channels/matchmaking"
messages:
- $ref: "#/channels/matchmaking/messages/MatchEstablished"
towerPlacing:
title: TowerPlacing
action: send
channel:
$ref: "#/channels/match"
messages:
- $ref: "#/channels/match/messages/RequestTowerPlacing"
reply:
channel:
$ref: "#/channels/match"
messages:
- $ref: "#/channels/match/messages/TowerPlaced"
- $ref: "#/channels/match/messages/InvalidPlacement"
enemyPlacedTower:
title: EnemyPlacedTower
updateTime:
title: Updates of the current Unix Time
action: receive
channel:
$ref: "#/channels/match"
$ref: "#/channels/time"
messages:
- $ref: "#/channels/match/messages/TowerPlaced"
playerMoney:
title: PlayerMoney
action: receive
channel:
$ref: "#/channels/match"
messages:
- $ref: "#/channels/match/messages/PlayerMoney"
playerHitpoints:
title: PlayerHitpoints
action: receive
channel:
$ref: "#/channels/match"
messages:
- $ref: "#/channels/match/messages/PlayerHitpoints"
- $ref: "#/channels/time/messages/CurrentUnixTime"
components:
securitySchemes:
@ -363,4 +252,7 @@ components:
Channel:
type: string
enum:
- connection
- matchmaking
- time