Skip to content

Instantly share code, notes, and snippets.

@Intelliractive
Created November 6, 2023 06:22
Show Gist options
  • Save Intelliractive/ab06eb8f6bf071e9fb50e2f56f830b3c to your computer and use it in GitHub Desktop.
Save Intelliractive/ab06eb8f6bf071e9fb50e2f56f830b3c to your computer and use it in GitHub Desktop.
Bukkit API Timers and Counters
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
public class Countdown {
private int seconds;
private BukkitTask task;
public Countdown(int seconds) {
this.seconds = seconds;
}
public void start() {
task = Bukkit.getScheduler().runTaskTimerAsynchronously(Bukkit.getPluginManager().getPlugin("YourPlugin"), () -> {
if (seconds <= 0) {
// Countdown is complete
task.cancel();
return;
}
// Broadcast the remaining time to all players
Bukkit.broadcastMessage("There are " + seconds + " seconds remaining until the countdown is complete.");
seconds -= 1;
}, 0L, 20L);
}
public void cancel() {
if (task != null) {
task.cancel();
}
}
}
@file:Suppress("KDocMissingDocumentation", "ReplaceNotNullAssertionWithElvisReturn")
package intelliractive.printer2
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextColor
import org.bukkit.Bukkit
import org.bukkit.Bukkit.getOnlinePlayers
import org.bukkit.Location
import org.bukkit.entity.Player
import org.bukkit.scheduler.BukkitRunnable
/** #### Game Countdown*/
class Countdown(override var seconds: Int): Timer(seconds){
override var state: String = "on"
override fun start() {
object : BukkitRunnable() {
override fun run() {
if (seconds <= 0) {
task()
// Timer has finished
state = "off"
cancel()
} else {
getOnlinePlayers().forEach { player ->
player.sendMessage(Component.text("Starting in ${seconds}s", TextColor.color(155, 255, 255)))
}
// Decrement the timer
seconds--
}
}
}.runTaskTimer(Bukkit.getPluginManager().getPlugin("GP_Printer2")!!, 0, 20)
}
}
@file:Suppress("KDocMissingDocumentation", "ReplaceNotNullAssertionWithElvisReturn")
package intelliractive.printer2
import org.bukkit.Bukkit
import org.bukkit.scheduler.BukkitRunnable
open class Timer(open var seconds: Int, open var tick: () -> Unit = {}, open var task: () -> Unit = {}) {
open var state: String = "on"
open fun start() {
object : BukkitRunnable() {
override fun run() {
if (seconds <= 0) {
task()
// Timer has finished
state = "off"
cancel()
} else {
tick()
// Decrement the timer
seconds--
}
}
}.runTaskTimer(Bukkit.getPluginManager().getPlugin("GP_Printer2")!!, 0, 20)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment