Server/Server/src/main/java/uulm/teamname/marvelous/server/lobby/TurnTimeoutTimer.java

57 lines
1.9 KiB
Java
Raw Normal View History

2021-06-04 14:26:45 +02:00
package uulm.teamname.marvelous.server.lobby;
import org.tinylog.Logger;
2021-06-04 14:26:45 +02:00
import uulm.teamname.marvelous.gamelibrary.messages.ParticipantType;
import uulm.teamname.marvelous.server.lobbymanager.Participant;
import java.util.concurrent.*;
2021-06-04 14:26:45 +02:00
import java.util.function.Consumer;
/**
2021-06-07 16:44:29 +02:00
* The {@link TurnTimeoutTimer} class is called by the {@link Lobby} to limit the amount of time a player has per round.
*/
2021-06-07 16:44:29 +02:00
public class TurnTimeoutTimer {
private final ScheduledExecutorService timer;
2021-06-04 14:26:45 +02:00
private final Consumer<Participant> callback;
private final int maxRoundTime;
private ScheduledFuture<Participant> current;
2021-06-07 16:44:29 +02:00
public TurnTimeoutTimer(int maxRoundTime, Consumer<Participant> callback) {
String lobbyThreadName = Thread.currentThread().getName();
2021-08-05 22:19:27 +02:00
ThreadFactory threadFactory = r -> new Thread(r, lobbyThreadName + "-TurnTimerThread");
this.timer = Executors.newSingleThreadScheduledExecutor(threadFactory);
this.maxRoundTime = maxRoundTime;
2021-06-04 14:26:45 +02:00
this.callback = callback;
}
/**
* This method checks if the participant is not a spectator. Otherwise it won't start a timer.
*
* @param participant the timer is for
*/
public void startTurnTimer(Participant participant) {
if (participant.type == ParticipantType.Spectator) {
2021-06-04 14:26:45 +02:00
throw new IllegalStateException("Spectators don't have TurnTime");
}
2021-06-04 14:26:45 +02:00
clear();
Logger.debug("Starting turn timer for participant '{}' with role {}",
participant.id.getName(), participant.type);
current = timer.schedule(() -> {
callback.accept(participant);
return participant;
},
maxRoundTime,
TimeUnit.SECONDS);
2021-06-04 14:26:45 +02:00
}
/** cancels all currently running timers */
public void clear() {
Logger.trace("Clearing timer");
if (this.current != null) {
current.cancel(true);
}
2021-06-04 14:26:45 +02:00
}
}