2025-03-05 11:39:47 +01:00
|
|
|
package de.towerdefence.server.match;
|
|
|
|
|
|
|
|
import de.towerdefence.server.player.Player;
|
2025-03-12 12:15:25 +01:00
|
|
|
import de.towerdefence.server.server.channels.match.money.PlayerMoneyCallback;
|
2025-03-10 13:39:14 +01:00
|
|
|
import de.towerdefence.server.server.channels.match.placing.Tower;
|
2025-03-05 11:39:47 +01:00
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
2025-03-12 12:15:25 +01:00
|
|
|
import java.util.Optional;
|
|
|
|
import java.util.concurrent.*;
|
2025-03-05 11:39:47 +01:00
|
|
|
|
|
|
|
@Service
|
|
|
|
public class MatchService {
|
|
|
|
private final Map<Player, Match> playerMatches = new HashMap<>();
|
2025-03-12 12:15:25 +01:00
|
|
|
private final Map<Match, ScheduledFuture<?>> moneyTasks = new HashMap<>();
|
|
|
|
private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
2025-03-05 11:39:47 +01:00
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
2025-03-10 13:39:14 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @return opponent
|
|
|
|
*/
|
2025-03-12 13:03:33 +01:00
|
|
|
public Player placeTower(Player player, int x, int y) throws InvalidPlacementException{
|
2025-03-10 13:39:14 +01:00
|
|
|
return playerMatches.get(player).addTower(player, new Tower(), x, y);
|
2025-03-12 12:15:25 +01:00
|
|
|
}
|
|
|
|
|
2025-03-10 13:39:14 +01:00
|
|
|
|
2025-03-12 12:15:25 +01:00
|
|
|
public void playerConnected(Player player, PlayerMoneyCallback callback) {
|
|
|
|
Match match = playerMatches.get(player);
|
|
|
|
Optional<Integer> currentMoney = match.getPlayerMoney(player);
|
|
|
|
if (currentMoney.isEmpty()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
match.setPlayerMoneyCallback(player, callback);
|
|
|
|
callback.call(player, currentMoney.get());
|
|
|
|
boolean matchStarted =match.setPlayerConnected(player);
|
|
|
|
if (!matchStarted) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
ScheduledFuture<?> moneyTask = scheduler.scheduleAtFixedRate(
|
|
|
|
() -> {
|
|
|
|
match.addMoney(3);
|
|
|
|
match.getPlayer1MoneyCallback().call(match.getPlayer1(), match.getPlayer1Money());
|
|
|
|
match.getPlayer2MoneyCallback().call(match.getPlayer2(), match.getPlayer2Money());
|
|
|
|
},
|
|
|
|
5,
|
|
|
|
5,
|
|
|
|
TimeUnit.SECONDS
|
|
|
|
);
|
|
|
|
moneyTasks.put(match, moneyTask);
|
2025-03-10 13:39:14 +01:00
|
|
|
}
|
2025-03-05 11:39:47 +01:00
|
|
|
}
|