57 lines
1.9 KiB
Java
57 lines
1.9 KiB
Java
package uulm.teamname.marvelous.server.lobby;
|
|
|
|
import org.tinylog.Logger;
|
|
import uulm.teamname.marvelous.gamelibrary.messages.ParticipantType;
|
|
import uulm.teamname.marvelous.server.lobbymanager.Participant;
|
|
|
|
import java.util.concurrent.*;
|
|
import java.util.function.Consumer;
|
|
|
|
/**
|
|
* The {@link TurnTimeoutTimer} class is called by the {@link Lobby} to limit the amount of time a player has per round.
|
|
*/
|
|
public class TurnTimeoutTimer {
|
|
private final ScheduledExecutorService timer;
|
|
private final Consumer<Participant> callback;
|
|
private final int maxRoundTime;
|
|
|
|
private ScheduledFuture<Participant> current;
|
|
|
|
public TurnTimeoutTimer(int maxRoundTime, Consumer<Participant> callback) {
|
|
String lobbyThreadName = Thread.currentThread().getName();
|
|
ThreadFactory threadFactory = r -> new Thread(r, lobbyThreadName + "-TurnTimerThread");
|
|
this.timer = Executors.newSingleThreadScheduledExecutor(threadFactory);
|
|
this.maxRoundTime = maxRoundTime;
|
|
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) {
|
|
throw new IllegalStateException("Spectators don't have TurnTime");
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
/** cancels all currently running timers */
|
|
public void clear() {
|
|
Logger.trace("Clearing timer");
|
|
if (this.current != null) {
|
|
current.cancel(true);
|
|
}
|
|
}
|
|
}
|