fix jump slab
This commit is contained in:
parent
d9eb747c1b
commit
978f739045
43 changed files with 5685 additions and 832 deletions
|
|
@ -4,8 +4,11 @@ import dev.loki.loparkour.config.Config;
|
|||
import dev.loki.loparkour.config.Locales;
|
||||
import dev.loki.loparkour.generator.ParkourGenerator;
|
||||
import dev.loki.loparkour.leaderboard.Leaderboard;
|
||||
import dev.loki.loparkour.menu.Menus;
|
||||
import dev.loki.loparkour.player.ParkourPlayer;
|
||||
import dev.loki.loparkour.player.ParkourUser;
|
||||
import dev.loki.loparkour.session.Session;
|
||||
import dev.loki.loparkour.world.Divider;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
|
@ -16,22 +19,44 @@ import java.util.Map;
|
|||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Coop Mode - Shared score between multiple players
|
||||
* Co-op Mode — multiple players share one session and one score.
|
||||
*
|
||||
* <p>Implements {@link MultiMode} so it is excluded from the single-player
|
||||
* mode selection menu in {@link dev.loki.loparkour.menu.play.SingleMenu}.
|
||||
* Players join via /parkour coop or through a lobby invite flow.</p>
|
||||
*
|
||||
* <p>Problems fixed vs previous version:
|
||||
* <ul>
|
||||
* <li>Did NOT implement MultiMode → showed up in single-player menu</li>
|
||||
* <li>CoopGenerator was a private inner class — inaccessible from join/leave</li>
|
||||
* <li>sharedScore was a separate field that duplicated state.score</li>
|
||||
* <li>fall() called super.fall() THEN tried to clear state that was already reset</li>
|
||||
* <li>playerContributions never cleared between falls correctly</li>
|
||||
* <li>create(Player) silently created a solo session instead of rejecting</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class CoopMode implements Mode {
|
||||
public class CoopMode implements MultiMode {
|
||||
|
||||
private final Leaderboard leaderboard = new Leaderboard(getName(), Leaderboard.Sort.SCORE);
|
||||
|
||||
// Active coop sessions — used so join() can add to an existing one
|
||||
// Key = session, tracked via Divider automatically; this is just for lookup
|
||||
// We look up by existing player's session instead.
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return "coop";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns null so this mode never appears in any menu item list.
|
||||
* Players join via lobby invite or command only.
|
||||
*/
|
||||
@Override
|
||||
@Nullable
|
||||
public dev.loki.loparkour.util.Item getItem(String locale) {
|
||||
return Locales.getItem(locale, "modes.coop");
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -40,92 +65,123 @@ public class CoopMode implements Mode {
|
|||
return leaderboard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a player tries to start coop solo from a command/menu.
|
||||
* Opens the lobby menu so they can invite others — does NOT create a session here.
|
||||
* A session is created only once a second player joins via {@link #join}.
|
||||
*/
|
||||
@Override
|
||||
public void create(Player player) {
|
||||
if (!Config.CONFIG.getBoolean("joining")) {
|
||||
player.sendMessage(Locales.getString(player, "other.joining_disabled"));
|
||||
player.sendMessage("§cJoining is currently disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof CoopMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
Session.create(session -> new CoopGenerator(session), null, null, player);
|
||||
// Opening lobby menu lets player invite others — actual session created in join()
|
||||
Menus.LOBBY.open(player);
|
||||
}
|
||||
|
||||
private static class CoopGenerator extends ParkourGenerator {
|
||||
private final Map<UUID, Integer> playerContributions = new HashMap<>();
|
||||
private int sharedScore = 0;
|
||||
/**
|
||||
* Adds a player to an existing coop session, or creates a new session if
|
||||
* the target player is not yet in one.
|
||||
*/
|
||||
@Override
|
||||
public void join(Player joiningPlayer, Session session) {
|
||||
if (!Config.CONFIG.getBoolean("joining")) {
|
||||
joiningPlayer.sendMessage("§cJoining is currently disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.generator == null) return;
|
||||
|
||||
// Register the joining player into the existing session
|
||||
ParkourPlayer pp = ParkourUser.register(joiningPlayer, session);
|
||||
session.addPlayers(pp);
|
||||
pp.updateGeneratorSettings(session.generator);
|
||||
|
||||
// Inform everyone
|
||||
session.getPlayers().forEach(p ->
|
||||
p.sendTranslated("modes.coop.player_joined", joiningPlayer.getName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a player from a coop session.
|
||||
* If the last player leaves, the session ends normally.
|
||||
*/
|
||||
@Override
|
||||
public void leave(Player player, Session session) {
|
||||
ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp == null) return;
|
||||
ParkourUser.leave(pp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxPlayers() {
|
||||
return Config.CONFIG.getInt("modes.coop.max-players");
|
||||
}
|
||||
|
||||
// ── CoopGenerator ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Package-accessible so Session.create() lambda can reference it,
|
||||
* and so join() can cast generator when needed.
|
||||
*/
|
||||
static class CoopGenerator extends ParkourGenerator {
|
||||
|
||||
/** Individual block contributions per player UUID. */
|
||||
private final Map<UUID, Integer> contributions = new HashMap<>();
|
||||
|
||||
public CoopGenerator(@NotNull Session session) {
|
||||
super(session);
|
||||
|
||||
// Initialize contributions
|
||||
for (ParkourPlayer pp : session.getPlayers()) {
|
||||
playerContributions.put(pp.getUUID(), 0);
|
||||
pp.player.sendTitle("§a§lCOOP MODE", "§7Work together for a shared score!", 10, 70, 20);
|
||||
pp.player.sendMessage("§a§lCoop Mode §7activated! Team score is shared.");
|
||||
}
|
||||
session.getPlayers().forEach(pp -> contributions.put(pp.getUUID(), 0));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void score() {
|
||||
super.score();
|
||||
sharedScore++;
|
||||
|
||||
// Track individual contributions
|
||||
if (!getPlayers().isEmpty()) {
|
||||
UUID scorer = player.getUUID();
|
||||
playerContributions.put(scorer, playerContributions.getOrDefault(scorer, 0) + 1);
|
||||
}
|
||||
|
||||
// Milestone celebrations
|
||||
if (sharedScore % 50 == 0) {
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
pp.player.sendTitle("§6" + sharedScore + " Points!", "§eTeam effort!", 5, 30, 10);
|
||||
pp.player.playSound(pp.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 0.5f, 1.5f);
|
||||
}
|
||||
super.score(); // increments state.score and totalScore
|
||||
|
||||
// Track which player was on the block (primary player for single, varies in multi)
|
||||
contributions.merge(player.getUUID(), 1, Integer::sum);
|
||||
|
||||
// Milestone every 50 points
|
||||
if (state.score % 50 == 0) {
|
||||
getPlayers().forEach(pp -> {
|
||||
pp.player.sendTitle(
|
||||
"§6Team: §e" + state.score,
|
||||
"§aKeep it up!",
|
||||
5, 40, 10);
|
||||
pp.player.playSound(pp.getLocation(),
|
||||
Sound.ENTITY_PLAYER_LEVELUP, 0.6f, 1.5f);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
super.tick();
|
||||
|
||||
// Display shared score and contributions in ActionBar
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
int myContribution = playerContributions.getOrDefault(pp.getUUID(), 0);
|
||||
int percentage = sharedScore > 0 ? (myContribution * 100 / sharedScore) : 0;
|
||||
|
||||
String message = "§aTeam: §e" + sharedScore + " §7| §bYou: §e" + myContribution + " §7(" + percentage + "%)";
|
||||
pp.player.spigot().sendMessage(
|
||||
net.md_5.bungee.api.ChatMessageType.ACTION_BAR,
|
||||
net.md_5.bungee.api.chat.TextComponent.fromLegacyText(message)
|
||||
);
|
||||
}
|
||||
/**
|
||||
* When a new player joins mid-game, add them to contributions map.
|
||||
*/
|
||||
public void onPlayerJoin(ParkourPlayer pp) {
|
||||
contributions.putIfAbsent(pp.getUUID(), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void fall() {
|
||||
// Show final stats before reset
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
int contribution = playerContributions.getOrDefault(pp.getUUID(), 0);
|
||||
pp.sendTranslated("modes.coop.stats",
|
||||
Integer.toString(sharedScore),
|
||||
Integer.toString(contribution));
|
||||
}
|
||||
|
||||
super.fall();
|
||||
|
||||
// Reset coop state
|
||||
sharedScore = 0;
|
||||
playerContributions.clear();
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
playerContributions.put(pp.getUUID(), 0);
|
||||
}
|
||||
// Show each player their individual contribution before reset
|
||||
getPlayers().forEach(pp -> {
|
||||
int contrib = contributions.getOrDefault(pp.getUUID(), 0);
|
||||
int pct = state.score > 0 ? (contrib * 100 / state.score) : 0;
|
||||
pp.sendTranslated("modes.coop.stats",
|
||||
Integer.toString(state.score),
|
||||
Integer.toString(contrib),
|
||||
Integer.toString(pct));
|
||||
});
|
||||
|
||||
super.fall(); // handles reset, leaderboard, etc.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset(boolean regenerate) {
|
||||
super.reset(regenerate);
|
||||
contributions.clear();
|
||||
getPlayers().forEach(pp -> contributions.put(pp.getUUID(), 0));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -1,20 +1,752 @@
|
|||
package dev.loki.loparkour.mode;
|
||||
|
||||
import dev.lolib.scheduler.Scheduler;
|
||||
import dev.lolib.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.api.event.ParkourFallEvent;
|
||||
import dev.loki.loparkour.api.event.ParkourScoreEvent;
|
||||
import dev.loki.loparkour.config.Config;
|
||||
import dev.loki.loparkour.generator.ParkourGenerator;
|
||||
import dev.loki.loparkour.leaderboard.Leaderboard;
|
||||
import dev.loki.loparkour.leaderboard.Score;
|
||||
import dev.loki.loparkour.player.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.Session;
|
||||
import dev.loki.loparkour.world.Divider;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Firework;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.FireworkMeta;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* Generator for Elytra mode parkour
|
||||
* Generator for Elytra mode.
|
||||
*
|
||||
* <p>Completely replaces block-based parkour with an aerial ring course:
|
||||
* <ul>
|
||||
* <li>Rings are placed ahead along a smooth curved path in the sky</li>
|
||||
* <li>Each ring is vertical, perpendicular to the flight direction</li>
|
||||
* <li>Player must fly through the center — detection uses plane-crossing math</li>
|
||||
* <li>Firework usage is intercepted via event to enforce cooldown properly</li>
|
||||
* <li>Fall = player touches ground / loses flight / flies too far from course</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class ElytraGenerator extends ParkourGenerator {
|
||||
public class ElytraGenerator extends ParkourGenerator implements Listener {
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** How many rings behind the player to keep before deleting. */
|
||||
private static final int RING_TRAIL = 3;
|
||||
|
||||
/** Ticks between particle ring renders (every 2 ticks = 10fps). */
|
||||
private static final int RENDER_INTERVAL = 2;
|
||||
|
||||
/** Minimum Y height — if player drops below this they failed. */
|
||||
private static final double MIN_Y_OFFSET = -30.0;
|
||||
|
||||
// Config-driven values cached at init
|
||||
private int ringLead;
|
||||
private double maxDeviation;
|
||||
|
||||
/** Particle count per ring point. */
|
||||
private static final int PARTICLES_PER_POINT = 1;
|
||||
|
||||
/** Number of particle points around each ring. */
|
||||
private static final int RING_POINTS = 36;
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private final List<ElytraRing> rings = new ArrayList<>();
|
||||
private int nextRingIndex = 0; // index of the next ring the player hasn't passed
|
||||
private int tickCounter = 0;
|
||||
private Instant startTime = null;
|
||||
private int score = 0;
|
||||
|
||||
private ScheduledTask tickTask;
|
||||
private ScheduledTask renderTask;
|
||||
|
||||
/** Firework cooldown per player UUID in ms. */
|
||||
private final Map<UUID, Long> fireworkCooldowns = new HashMap<>();
|
||||
|
||||
/** Starting Y for fall detection. */
|
||||
private double spawnY;
|
||||
|
||||
// ── Constructor ───────────────────────────────────────────────────────────
|
||||
|
||||
public ElytraGenerator(@NotNull Session session) {
|
||||
super(session);
|
||||
this.ringLead = Config.CONFIG.getInt("modes.elytra.ring-lead");
|
||||
this.maxDeviation = Config.CONFIG.getDouble("modes.elytra.max-deviation");
|
||||
}
|
||||
|
||||
// ── Mode identification ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public Mode getMode() {
|
||||
return Modes.ELYTRA;
|
||||
}
|
||||
|
||||
// ── Lifecycle: called by Session after island.build() ────────────────────
|
||||
|
||||
/**
|
||||
* Called once when the generator is set up.
|
||||
* We skip the block-based generateFirst and do our own aerial setup.
|
||||
*/
|
||||
@Override
|
||||
public void generateFirst(Location spawn, Location blockSpawn) {
|
||||
spawnY = spawn.getY();
|
||||
state.playerSpawn = spawn;
|
||||
state.lastStandingPlayerLocation = spawn;
|
||||
state.blockSpawn = blockSpawn;
|
||||
|
||||
// Seed the ring path starting just in front of spawn
|
||||
Vector initialHeading = state.heading.clone().normalize();
|
||||
Location ringOrigin = spawn.clone().add(initialHeading.clone().multiply(10)).add(0, 2, 0);
|
||||
|
||||
generateRings(ringOrigin, initialHeading, ringLead);
|
||||
|
||||
// Setup player
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
Player p = pp.player;
|
||||
p.setGameMode(GameMode.ADVENTURE);
|
||||
p.getInventory().clear();
|
||||
|
||||
// Elytra chestplate
|
||||
p.getInventory().setChestplate(new ItemStack(Material.ELYTRA));
|
||||
|
||||
// Starting fireworks
|
||||
int amount = Config.CONFIG.getInt("modes.elytra.starting-fireworks");
|
||||
p.getInventory().setItem(0, makeFirework(amount));
|
||||
p.getInventory().setHeldItemSlot(0);
|
||||
|
||||
// Launch into glide
|
||||
p.setVelocity(initialHeading.clone().multiply(1.2).setY(0.4));
|
||||
p.setGliding(true);
|
||||
|
||||
pp.sendTranslated("modes.elytra.start_hint");
|
||||
}
|
||||
|
||||
// Register firework event listener
|
||||
Bukkit.getPluginManager().registerEvents(this, LoParkour.getPlugin());
|
||||
|
||||
// Start ticks
|
||||
tickTask = Scheduler.get(LoParkour.getPlugin()).runTimer(this::tick, 1, 1);
|
||||
renderTask = Scheduler.get(LoParkour.getPlugin()).runTimer(this::renderRings, 0, RENDER_INTERVAL);
|
||||
}
|
||||
|
||||
// ── generateFirst is the entry — skip normal generate() completely ────────
|
||||
|
||||
@Override
|
||||
public void generate() { /* not used in elytra mode */ }
|
||||
|
||||
@Override
|
||||
public void generate(int amount) { /* not used */ }
|
||||
|
||||
@Override
|
||||
public void startTick() { /* tick started in generateFirst */ }
|
||||
|
||||
// ── Main tick ─────────────────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
if (state.stopped) {
|
||||
stopTasks();
|
||||
return;
|
||||
}
|
||||
|
||||
tickCounter++;
|
||||
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
Player p = pp.player;
|
||||
|
||||
// Ensure player stays gliding
|
||||
if (!p.isGliding() && p.getGameMode() == GameMode.ADVENTURE) {
|
||||
// Only force-glide if they're not on ground and have elytra
|
||||
if (!p.isOnGround()) {
|
||||
p.setGliding(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Update scoreboard
|
||||
pp.updateScoreboard(this);
|
||||
p.setSaturation(20);
|
||||
|
||||
// Action bar: score + next ring distance
|
||||
updateActionBar(pp);
|
||||
}
|
||||
|
||||
// Fall detection
|
||||
checkFall();
|
||||
|
||||
// Ring crossing detection
|
||||
checkRingCrossings();
|
||||
}
|
||||
|
||||
// ── Ring generation ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generates {@code count} new rings starting from {@code origin},
|
||||
* heading in {@code direction}, with smooth curve randomisation.
|
||||
*/
|
||||
private void generateRings(Location origin, Vector direction, int count) {
|
||||
int distMin = Config.CONFIG.getInt("modes.elytra.ring-distance-min");
|
||||
int distMax = Config.CONFIG.getInt("modes.elytra.ring-distance-max");
|
||||
double ringSize = Config.CONFIG.getDouble("modes.elytra.ring-size");
|
||||
double maxYaw = Config.CONFIG.getDouble("modes.elytra.max-heading-change-horizontal");
|
||||
double maxPitch = Config.CONFIG.getDouble("modes.elytra.max-heading-change-vertical");
|
||||
double maxHeight = Config.CONFIG.getDouble("modes.elytra.max-height-above-spawn");
|
||||
|
||||
ThreadLocalRandom rng = ThreadLocalRandom.current();
|
||||
Location cursor = origin.clone();
|
||||
Vector heading = direction.clone().normalize();
|
||||
|
||||
// If we already have rings, continue from the last one
|
||||
if (!rings.isEmpty()) {
|
||||
ElytraRing last = rings.get(rings.size() - 1);
|
||||
cursor = last.center.clone();
|
||||
heading = last.normal.clone();
|
||||
}
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
// Distance between rings
|
||||
double dist = distMin + rng.nextDouble() * (distMax - distMin);
|
||||
|
||||
// Smooth heading change using config-defined limits
|
||||
double yawDelta = Math.toRadians(rng.nextDouble(-maxYaw, maxYaw));
|
||||
double pitchDelta = Math.toRadians(rng.nextDouble(-maxPitch, maxPitch));
|
||||
|
||||
heading = rotateVector(heading, yawDelta, pitchDelta);
|
||||
heading.normalize();
|
||||
|
||||
// New ring center
|
||||
Location center = cursor.clone().add(heading.clone().multiply(dist));
|
||||
|
||||
// Keep rings in a reasonable Y band
|
||||
double targetY = Math.max(spawnY + 5, Math.min(spawnY + maxHeight, center.getY()));
|
||||
center.setY(targetY);
|
||||
|
||||
rings.add(new ElytraRing(rings.size(), center.clone(), heading.clone(), ringSize));
|
||||
cursor = center;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Ring crossing detection ───────────────────────────────────────────────
|
||||
|
||||
private void checkRingCrossings() {
|
||||
if (rings.isEmpty() || nextRingIndex >= rings.size()) return;
|
||||
|
||||
ParkourPlayer pp = player; // primary player
|
||||
Location loc = pp.getLocation();
|
||||
|
||||
ElytraRing nextRing = rings.get(nextRingIndex);
|
||||
|
||||
// Check if player crossed the ring's plane
|
||||
if (nextRing.hasCrossed(loc, pp.player.getVelocity())) {
|
||||
if (nextRing.isInside(loc)) {
|
||||
// Perfect pass — score
|
||||
onRingPassed(pp, nextRing, true);
|
||||
} else {
|
||||
// Crossed the plane but missed the ring hole
|
||||
onRingMissed(pp, nextRing);
|
||||
}
|
||||
nextRingIndex++;
|
||||
|
||||
// Generate more rings ahead
|
||||
int ahead = rings.size() - nextRingIndex;
|
||||
if (ahead < ringLead) {
|
||||
generateRings(null, null, ringLead - ahead);
|
||||
}
|
||||
|
||||
// Clean up old rings
|
||||
cleanOldRings();
|
||||
}
|
||||
|
||||
// Check deviation — if player flew too far off course
|
||||
double deviation = nextRing.center.distance(loc);
|
||||
if (deviation > maxDeviation) {
|
||||
triggerFall("flew off course");
|
||||
}
|
||||
}
|
||||
|
||||
private void onRingPassed(ParkourPlayer pp, ElytraRing ring, boolean centered) {
|
||||
score++;
|
||||
if (startTime == null) startTime = Instant.now();
|
||||
|
||||
new ParkourScoreEvent(pp).call();
|
||||
|
||||
// Visual + sound feedback
|
||||
pp.player.spawnParticle(Particle.TOTEM, ring.center, 40, 0.3, 0.3, 0.3, 0.15);
|
||||
pp.player.playSound(ring.center, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1f, centered ? 1.8f : 1.2f);
|
||||
|
||||
// Update state score so scoreboard works
|
||||
state.score = score;
|
||||
state.totalScore++;
|
||||
}
|
||||
|
||||
private void onRingMissed(ParkourPlayer pp, ElytraRing ring) {
|
||||
// Flash red to indicate miss — no score
|
||||
pp.player.spawnParticle(Particle.REDSTONE,
|
||||
ring.center, 20, 0.5, 0.5, 0.5, 0,
|
||||
new Particle.DustOptions(Color.RED, 2.0f));
|
||||
pp.player.playSound(ring.center, Sound.BLOCK_NOTE_BLOCK_BASS, 1f, 0.5f);
|
||||
}
|
||||
|
||||
// ── Fall / Reset ──────────────────────────────────────────────────────────
|
||||
|
||||
private void checkFall() {
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
Player p = pp.player;
|
||||
double y = p.getLocation().getY();
|
||||
|
||||
// Touched ground or fell too far below spawn
|
||||
if (p.isOnGround() || y < spawnY + MIN_Y_OFFSET) {
|
||||
triggerFall("touched ground or fell below course");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void triggerFall(String reason) {
|
||||
LoParkour.log("ElytraGenerator fall: " + reason);
|
||||
new ParkourFallEvent(player).call();
|
||||
|
||||
// Save score to leaderboard if it's a new record
|
||||
Leaderboard lb = getMode().getLeaderboard();
|
||||
if (lb != null) {
|
||||
int record = lb.get(player.getUUID()).score();
|
||||
if (score > record) {
|
||||
String time = getFormattedTime();
|
||||
getPlayers().forEach(p -> lb.put(p.getUUID(),
|
||||
new Score(p.getName(), time, "0.0", score)));
|
||||
}
|
||||
}
|
||||
|
||||
// Show fall message
|
||||
sendFallMessage();
|
||||
|
||||
reset(true);
|
||||
}
|
||||
|
||||
private void sendFallMessage() {
|
||||
Leaderboard lb = getMode().getLeaderboard();
|
||||
int record = lb != null ? lb.get(player.getUUID()).score() : 0;
|
||||
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.divider");
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.score", Integer.toString(score));
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.time", getFormattedTime());
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.high_score", Integer.toString(record));
|
||||
if (score > record) {
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.formats.beat",
|
||||
Integer.toString(score - record));
|
||||
} else if (score == record) {
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.formats.tied", "0");
|
||||
} else {
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.formats.miss",
|
||||
Integer.toString(record - score));
|
||||
}
|
||||
pp.sendTranslated("settings.parkour_settings.items.fall_message.divider");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset(boolean regenerate) {
|
||||
state.stopped = !regenerate;
|
||||
|
||||
// Clear rings from world (remove barrier blocks)
|
||||
rings.forEach(ElytraRing::remove);
|
||||
rings.clear();
|
||||
nextRingIndex = 0;
|
||||
score = 0;
|
||||
state.score = 0;
|
||||
startTime = null;
|
||||
state.start = null;
|
||||
tickCounter = 0;
|
||||
fireworkCooldowns.clear();
|
||||
|
||||
if (!regenerate) {
|
||||
stopTasks();
|
||||
unregisterListener();
|
||||
island.destroy();
|
||||
if (getPlayers().isEmpty()) {
|
||||
getSpectators().forEach(s -> Modes.DEFAULT.create(s.player));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Teleport back to spawn and restart
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
pp.teleport(state.playerSpawn);
|
||||
pp.player.setGliding(false);
|
||||
pp.player.setVelocity(new Vector(0, 0, 0));
|
||||
|
||||
// Restore fireworks
|
||||
int amount = Config.CONFIG.getInt("modes.elytra.starting-fireworks");
|
||||
pp.player.getInventory().clear();
|
||||
pp.player.getInventory().setChestplate(new ItemStack(Material.ELYTRA));
|
||||
pp.player.getInventory().setItem(0, makeFirework(amount));
|
||||
pp.player.getInventory().setHeldItemSlot(0);
|
||||
}
|
||||
|
||||
// Re-generate rings
|
||||
Vector initialHeading = state.heading.clone().normalize();
|
||||
Location ringOrigin = state.playerSpawn.clone()
|
||||
.add(initialHeading.clone().multiply(10)).add(0, 2, 0);
|
||||
generateRings(ringOrigin, initialHeading, ringLead);
|
||||
|
||||
// Brief delay then launch
|
||||
Scheduler.get(LoParkour.getPlugin()).runLater(() -> {
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
pp.player.setVelocity(initialHeading.clone().multiply(1.2).setY(0.4));
|
||||
pp.player.setGliding(true);
|
||||
}
|
||||
}, 10L);
|
||||
}
|
||||
|
||||
// ── Ring rendering ────────────────────────────────────────────────────────
|
||||
|
||||
private void renderRings() {
|
||||
if (state.stopped) return;
|
||||
|
||||
Location playerLoc = player.getLocation();
|
||||
|
||||
for (int i = nextRingIndex; i < Math.min(nextRingIndex + ringLead, rings.size()); i++) {
|
||||
ElytraRing ring = rings.get(i);
|
||||
double dist = ring.center.distance(playerLoc);
|
||||
if (dist > 80) continue; // Don't render very far rings
|
||||
|
||||
// Colour gradient: next ring = gold, further = white, collected = skip
|
||||
Color color = (i == nextRingIndex) ? Color.YELLOW
|
||||
: (i == nextRingIndex + 1) ? Color.ORANGE
|
||||
: Color.WHITE;
|
||||
|
||||
renderRing(ring, color);
|
||||
}
|
||||
}
|
||||
|
||||
private void renderRing(ElytraRing ring, Color color) {
|
||||
World world = ring.center.getWorld();
|
||||
if (world == null) return;
|
||||
|
||||
// Two orthogonal vectors in the ring's plane
|
||||
Vector normal = ring.normal.clone().normalize();
|
||||
Vector up = findPerpendicular(normal);
|
||||
Vector right = normal.clone().crossProduct(up).normalize();
|
||||
|
||||
double r = ring.radius;
|
||||
Particle.DustOptions dust = new Particle.DustOptions(color, 1.5f);
|
||||
|
||||
for (int i = 0; i < RING_POINTS; i++) {
|
||||
double angle = 2 * Math.PI * i / RING_POINTS;
|
||||
double x = r * Math.cos(angle);
|
||||
double y = r * Math.sin(angle);
|
||||
|
||||
Location p = ring.center.clone()
|
||||
.add(right.clone().multiply(x))
|
||||
.add(up.clone().multiply(y));
|
||||
|
||||
world.spawnParticle(Particle.REDSTONE, p, PARTICLES_PER_POINT, 0, 0, 0, 0, dust);
|
||||
}
|
||||
|
||||
// Inner ring (smaller, brighter) so it's visible
|
||||
Particle.DustOptions innerDust = new Particle.DustOptions(Color.WHITE, 0.8f);
|
||||
double innerR = r * 0.4;
|
||||
for (int i = 0; i < RING_POINTS / 2; i++) {
|
||||
double angle = 2 * Math.PI * i / (RING_POINTS / 2);
|
||||
double x = innerR * Math.cos(angle);
|
||||
double y = innerR * Math.sin(angle);
|
||||
|
||||
Location p = ring.center.clone()
|
||||
.add(right.clone().multiply(x))
|
||||
.add(up.clone().multiply(y));
|
||||
|
||||
world.spawnParticle(Particle.REDSTONE, p, PARTICLES_PER_POINT, 0, 0, 0, 0, innerDust);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Firework event — cancel if on cooldown ────────────────────────────────
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGH)
|
||||
public void onFireworkUse(PlayerInteractEvent event) {
|
||||
Player p = event.getPlayer();
|
||||
ParkourPlayer pp = ParkourPlayer.getPlayer(p);
|
||||
if (pp == null || !(pp.session.generator instanceof ElytraGenerator gen)) return;
|
||||
if (gen != this) return;
|
||||
|
||||
// Only care about firework rockets
|
||||
org.bukkit.inventory.ItemStack item = event.getItem();
|
||||
if (item == null || item.getType() != Material.FIREWORK_ROCKET) return;
|
||||
|
||||
boolean isRightClick = event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_AIR
|
||||
|| event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK;
|
||||
if (!isRightClick) return;
|
||||
if (!p.isGliding()) return;
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
int cooldownMs = Config.CONFIG.getInt("modes.elytra.firework-cooldown-ms");
|
||||
UUID uuid = p.getUniqueId();
|
||||
|
||||
Long lastUse = fireworkCooldowns.get(uuid);
|
||||
if (lastUse != null && now - lastUse < cooldownMs) {
|
||||
event.setCancelled(true);
|
||||
long remaining = (cooldownMs - (now - lastUse) + 999) / 1000;
|
||||
p.spigot().sendMessage(
|
||||
net.md_5.bungee.api.ChatMessageType.ACTION_BAR,
|
||||
net.md_5.bungee.api.chat.TextComponent.fromLegacyText(
|
||||
"§c⏱ Firework cooldown: §f" + remaining + "s"));
|
||||
return;
|
||||
}
|
||||
|
||||
fireworkCooldowns.put(uuid, now);
|
||||
|
||||
// Spawn a boost firework at player location instead of vanilla behaviour
|
||||
event.setCancelled(true);
|
||||
spawnBoostFirework(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawns a visual-only firework that gives the player a velocity boost.
|
||||
* We do it manually so we control the power and remove the damage.
|
||||
*/
|
||||
private void spawnBoostFirework(Player p) {
|
||||
double power = Config.CONFIG.getDouble("modes.elytra.boost-power");
|
||||
Vector dir = p.getLocation().getDirection().normalize();
|
||||
|
||||
// Remove one firework from inventory
|
||||
ItemStack held = p.getInventory().getItemInMainHand();
|
||||
if (held.getType() == Material.FIREWORK_ROCKET) {
|
||||
if (held.getAmount() > 1) {
|
||||
held.setAmount(held.getAmount() - 1);
|
||||
} else {
|
||||
p.getInventory().setItemInMainHand(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply boost velocity
|
||||
Vector boost = dir.multiply(power);
|
||||
p.setVelocity(p.getVelocity().add(boost));
|
||||
p.setGliding(true);
|
||||
|
||||
// Spawn visual firework that instantly explodes (no damage)
|
||||
Firework fw = p.getWorld().spawn(p.getLocation(), Firework.class);
|
||||
FireworkMeta meta = fw.getFireworkMeta();
|
||||
meta.addEffect(FireworkEffect.builder()
|
||||
.with(FireworkEffect.Type.STAR)
|
||||
.withColor(Color.AQUA, Color.WHITE)
|
||||
.withFade(Color.YELLOW)
|
||||
.withTrail()
|
||||
.build());
|
||||
meta.setPower(0);
|
||||
fw.setFireworkMeta(meta);
|
||||
fw.setShotAtAngle(true);
|
||||
|
||||
// Detonate immediately (no damage tick)
|
||||
Scheduler.get(LoParkour.getPlugin()).runLater(() -> {
|
||||
if (fw.isValid()) fw.detonate();
|
||||
}, 1L);
|
||||
|
||||
p.playSound(p.getLocation(), Sound.ENTITY_FIREWORK_ROCKET_LAUNCH, 0.8f, 1.2f);
|
||||
}
|
||||
|
||||
// ── Action bar ────────────────────────────────────────────────────────────
|
||||
|
||||
private void updateActionBar(ParkourPlayer pp) {
|
||||
if (rings.isEmpty() || nextRingIndex >= rings.size()) return;
|
||||
|
||||
ElytraRing nextRing = rings.get(nextRingIndex);
|
||||
double dist = Math.round(nextRing.center.distance(pp.getLocation()) * 10.0) / 10.0;
|
||||
|
||||
// Firework cooldown indicator
|
||||
long now = System.currentTimeMillis();
|
||||
int cooldownMs = Config.CONFIG.getInt("modes.elytra.firework-cooldown-ms");
|
||||
Long lastUse = fireworkCooldowns.get(pp.getUUID());
|
||||
String cooldownStr;
|
||||
if (lastUse != null && now - lastUse < cooldownMs) {
|
||||
long remaining = (cooldownMs - (now - lastUse) + 999) / 1000;
|
||||
cooldownStr = "§c⏱ " + remaining + "s";
|
||||
} else {
|
||||
cooldownStr = "§a✔ Ready";
|
||||
}
|
||||
|
||||
pp.player.spigot().sendMessage(
|
||||
net.md_5.bungee.api.ChatMessageType.ACTION_BAR,
|
||||
net.md_5.bungee.api.chat.TextComponent.fromLegacyText(
|
||||
"§6⬤ §fRings: §e" + score
|
||||
+ " §7| §f➤ §b" + dist + "m"
|
||||
+ " §7| §f🚀 " + cooldownStr));
|
||||
}
|
||||
|
||||
// ── Time helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public String getFormattedTime() {
|
||||
if (startTime == null) return "00:00:000";
|
||||
var ms = Instant.now().minusMillis(startTime.toEpochMilli());
|
||||
try {
|
||||
return DateTimeFormatter.ofPattern("mm:ss:SSS").withZone(ZoneOffset.UTC).format(ms);
|
||||
} catch (Exception e) {
|
||||
return "00:00:000";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cleanup ───────────────────────────────────────────────────────────────
|
||||
|
||||
private void cleanOldRings() {
|
||||
// Remove rings more than RING_TRAIL behind the player
|
||||
int removeUntil = nextRingIndex - RING_TRAIL;
|
||||
if (removeUntil <= 0) return;
|
||||
|
||||
Iterator<ElytraRing> it = rings.iterator();
|
||||
int idx = 0;
|
||||
while (it.hasNext()) {
|
||||
ElytraRing ring = it.next();
|
||||
if (idx < removeUntil) {
|
||||
ring.remove();
|
||||
it.remove();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
idx++;
|
||||
}
|
||||
nextRingIndex -= removeUntil;
|
||||
}
|
||||
|
||||
private void stopTasks() {
|
||||
if (tickTask != null) { tickTask.cancel(); tickTask = null; }
|
||||
if (renderTask != null) { renderTask.cancel(); renderTask = null; }
|
||||
}
|
||||
|
||||
private void unregisterListener() {
|
||||
HandlerList.unregisterAll(this);
|
||||
}
|
||||
|
||||
// ── Utilities ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Returns a vector perpendicular to the given one.
|
||||
* Used to form the ring's local coordinate axes.
|
||||
*/
|
||||
private static Vector findPerpendicular(Vector v) {
|
||||
Vector perp = (Math.abs(v.getX()) < 0.9)
|
||||
? new Vector(1, 0, 0)
|
||||
: new Vector(0, 1, 0);
|
||||
return perp.subtract(v.clone().multiply(perp.dot(v))).normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates a vector by yaw (horizontal) and pitch (vertical) deltas.
|
||||
*/
|
||||
private static Vector rotateVector(Vector v, double yawRad, double pitchRad) {
|
||||
// Rotate around Y axis (yaw)
|
||||
double cos = Math.cos(yawRad);
|
||||
double sin = Math.sin(yawRad);
|
||||
double nx = v.getX() * cos - v.getZ() * sin;
|
||||
double nz = v.getX() * sin + v.getZ() * cos;
|
||||
v = new Vector(nx, v.getY(), nz);
|
||||
|
||||
// Rotate around the local right axis (pitch)
|
||||
Vector right = new Vector(v.getZ(), 0, -v.getX()).normalize();
|
||||
double c = Math.cos(pitchRad);
|
||||
double s = Math.sin(pitchRad);
|
||||
double vDotR = v.dot(right);
|
||||
return new Vector(
|
||||
v.getX() * c + (right.getY() * v.getZ() - right.getZ() * v.getY()) * s,
|
||||
v.getY() * c + (right.getZ() * v.getX() - right.getX() * v.getZ()) * s,
|
||||
v.getZ() * c + (right.getX() * v.getY() - right.getY() * v.getX()) * s
|
||||
);
|
||||
}
|
||||
|
||||
private static ItemStack makeFirework(int amount) {
|
||||
ItemStack item = new ItemStack(Material.FIREWORK_ROCKET, amount);
|
||||
FireworkMeta meta = (FireworkMeta) item.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.addEffect(FireworkEffect.builder()
|
||||
.with(FireworkEffect.Type.BALL)
|
||||
.withColor(Color.AQUA)
|
||||
.build());
|
||||
meta.setPower(1);
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
// ── Inner class: ElytraRing ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Represents one ring in the course.
|
||||
*
|
||||
* <p>A ring is defined by its center point and its normal vector (the direction
|
||||
* of travel through it). The "inside" is a circle of {@code radius} around the center
|
||||
* on the plane perpendicular to {@code normal}.
|
||||
*/
|
||||
public static class ElytraRing {
|
||||
|
||||
public final int id;
|
||||
public final Location center;
|
||||
/** Direction of travel — the ring faces perpendicular to this. */
|
||||
public final Vector normal;
|
||||
public final double radius;
|
||||
|
||||
/** Signed distance of the player on the last tick (for plane crossing detection). */
|
||||
private double lastSignedDist = Double.NaN;
|
||||
|
||||
/** Barrier blocks placed for this ring (optional, used if solid rings are enabled). */
|
||||
private final List<Block> barrierBlocks = new ArrayList<>();
|
||||
|
||||
public ElytraRing(int id, Location center, Vector normal, double radius) {
|
||||
this.id = id;
|
||||
this.center = center.clone();
|
||||
this.normal = normal.clone().normalize();
|
||||
this.radius = radius;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the player crossed the ring's plane since the last call.
|
||||
* Uses the dot product of (playerPos - ringCenter) with the ring's normal.
|
||||
* Sign change = crossing.
|
||||
*/
|
||||
public boolean hasCrossed(Location playerLoc, Vector velocity) {
|
||||
Vector toPlayer = playerLoc.toVector().subtract(center.toVector());
|
||||
double signedDist = toPlayer.dot(normal);
|
||||
|
||||
boolean crossed = false;
|
||||
if (!Double.isNaN(lastSignedDist)) {
|
||||
// Crossed if sign flipped (was positive, now negative or vice versa)
|
||||
crossed = (lastSignedDist > 0) != (signedDist > 0);
|
||||
}
|
||||
lastSignedDist = signedDist;
|
||||
return crossed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the player's position (projected onto the ring's plane)
|
||||
* is within the ring's radius — i.e. they flew through the hole.
|
||||
*/
|
||||
public boolean isInside(Location playerLoc) {
|
||||
// Project player position onto ring's plane
|
||||
Vector toPlayer = playerLoc.toVector().subtract(center.toVector());
|
||||
// Remove the component along the normal
|
||||
Vector projected = toPlayer.clone().subtract(normal.clone().multiply(toPlayer.dot(normal)));
|
||||
return projected.length() <= radius;
|
||||
}
|
||||
|
||||
/** Remove any barrier blocks this ring placed in the world. */
|
||||
public void remove() {
|
||||
barrierBlocks.forEach(b -> b.setType(Material.AIR, false));
|
||||
barrierBlocks.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,30 +1,19 @@
|
|||
package dev.loki.loparkour.mode;
|
||||
|
||||
import dev.loki.loparkour.util.Item;
|
||||
|
||||
import dev.loki.loparkour.config.Config;
|
||||
import dev.loki.loparkour.config.Locales;
|
||||
import dev.loki.loparkour.generator.ParkourGenerator;
|
||||
import dev.loki.loparkour.ghost.GhostManager;
|
||||
import dev.loki.loparkour.ghost.GhostRecorder;
|
||||
import dev.loki.loparkour.leaderboard.Leaderboard;
|
||||
import dev.loki.loparkour.player.ParkourPlayer;
|
||||
import dev.loki.loparkour.player.ParkourSpectator;
|
||||
import dev.loki.loparkour.session.Session;
|
||||
|
||||
import org.bukkit.*;
|
||||
import dev.loki.loparkour.util.Item;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.BoundingBox;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Elytra Parkour Mode - Flying parkour with rings and boost
|
||||
* Elytra Parkour Mode.
|
||||
* Players fly through vertical rings generated ahead along a curved aerial path.
|
||||
* No blocks on the ground — pure flight mechanics.
|
||||
*/
|
||||
public class ElytraMode implements Mode {
|
||||
|
||||
|
|
@ -38,7 +27,7 @@ public class ElytraMode implements Mode {
|
|||
|
||||
@Override
|
||||
@Nullable
|
||||
public dev.loki.loparkour.util.Item getItem(String locale) {
|
||||
public Item getItem(String locale) {
|
||||
return Locales.getItem(locale, "modes.elytra");
|
||||
}
|
||||
|
||||
|
|
@ -51,181 +40,16 @@ public class ElytraMode implements Mode {
|
|||
@Override
|
||||
public void create(Player player) {
|
||||
if (!Config.CONFIG.getBoolean("joining")) {
|
||||
player.sendMessage(Locales.getString(player, "other.joining_disabled"));
|
||||
player.sendMessage("§cJoining is currently disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof ElytraMode) {
|
||||
if (pp != null && pp.session.generator instanceof ElytraGenerator) {
|
||||
return;
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
// Create session with elytra setup
|
||||
Session.create(session -> new ElytraGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
private static class ElytraGenerator extends ParkourGenerator {
|
||||
private final List<RingCheckpoint> rings = new ArrayList<>();
|
||||
private final Map<UUID, Long> fireworkCooldowns = new HashMap<>();
|
||||
private final Map<UUID, Integer> ringsCollected = new HashMap<>();
|
||||
private int tickCounter = 0;
|
||||
|
||||
public ElytraGenerator(@NotNull Session session) {
|
||||
super(session);
|
||||
|
||||
// Give elytra and fireworks to all players in session
|
||||
for (ParkourPlayer parkourPlayer : session.getPlayers()) {
|
||||
Player p = parkourPlayer.player;
|
||||
p.setGameMode(GameMode.ADVENTURE);
|
||||
p.getInventory().setChestplate(new ItemStack(Material.ELYTRA));
|
||||
|
||||
int fireworks = Config.CONFIG.getInt("modes.elytra.starting-fireworks");
|
||||
p.getInventory().addItem(new ItemStack(Material.FIREWORK_ROCKET, fireworks));
|
||||
|
||||
ringsCollected.put(p.getUniqueId(), 0);
|
||||
|
||||
// Notify player
|
||||
p.sendTitle("§b§lELYTRA MODE", "§7Fly through rings for bonus points!", 10, 70, 20);
|
||||
p.sendMessage("§b§lElytra Mode §7activated! Use fireworks to boost.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
// Don't call super.tick() - we don't want normal block generation
|
||||
tickCounter++;
|
||||
|
||||
// Update spectators
|
||||
getSpectators().forEach(ParkourSpectator::update);
|
||||
|
||||
// Check for fall (much lower threshold for elytra)
|
||||
if (player.getLocation().getY() < state.lastStandingPlayerLocation.getY() - 50) {
|
||||
lifecycle.fall();
|
||||
return;
|
||||
}
|
||||
|
||||
// Spawn rings every 2 seconds
|
||||
if (tickCounter % 40 == 0) {
|
||||
spawnNextRing();
|
||||
}
|
||||
|
||||
// Display rings and check for player passing through
|
||||
Iterator<RingCheckpoint> it = rings.iterator();
|
||||
while (it.hasNext()) {
|
||||
RingCheckpoint ring = it.next();
|
||||
|
||||
// Display ring particles
|
||||
displayRing(ring.location);
|
||||
|
||||
// Check if any player passed through
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
if (ring.collected) continue;
|
||||
|
||||
BoundingBox playerBox = pp.player.getBoundingBox();
|
||||
if (ring.getBoundingBox().overlaps(playerBox)) {
|
||||
ring.collected = true;
|
||||
int count = ringsCollected.getOrDefault(pp.getUUID(), 0) + 1;
|
||||
ringsCollected.put(pp.getUUID(), count);
|
||||
|
||||
// Bonus points for passing through ring
|
||||
lifecycle.score();
|
||||
lifecycle.score();
|
||||
lifecycle.score(); // 3 points per ring
|
||||
|
||||
pp.player.playSound(pp.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1f, 1.5f);
|
||||
pp.player.spawnParticle(Particle.TOTEM, ring.location, 20, 0.5, 0.5, 0.5, 0.1);
|
||||
|
||||
// Update last standing location to ring location
|
||||
state.lastStandingPlayerLocation = ring.location.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Remove old rings
|
||||
if (ring.location.distance(player.getLocation()) > 100) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// Check firework cooldown
|
||||
checkFireworkCooldown();
|
||||
|
||||
// Start timer if not started
|
||||
if (state.start == null) state.start = Instant.now();
|
||||
}
|
||||
|
||||
private void spawnNextRing() {
|
||||
Location playerLoc = player.getLocation();
|
||||
|
||||
// Spawn ring ahead of player in flight direction
|
||||
Vector direction = player.getLocation().getDirection();
|
||||
Location ringLoc = playerLoc.clone().add(direction.multiply(20)).add(0, 5, 0);
|
||||
|
||||
// Add some randomness
|
||||
ringLoc.add((Math.random() - 0.5) * 10, (Math.random() - 0.5) * 5, (Math.random() - 0.5) * 10);
|
||||
|
||||
rings.add(new RingCheckpoint(ringLoc));
|
||||
}
|
||||
|
||||
private void displayRing(Location center) {
|
||||
World world = center.getWorld();
|
||||
if (world == null) return;
|
||||
|
||||
double radius = 2.0;
|
||||
int points = 30;
|
||||
|
||||
for (int i = 0; i < points; i++) {
|
||||
double angle = 2 * Math.PI * i / points;
|
||||
double x = center.getX() + radius * Math.cos(angle);
|
||||
double z = center.getZ() + radius * Math.sin(angle);
|
||||
|
||||
Location particleLoc = new Location(world, x, center.getY(), z);
|
||||
world.spawnParticle(Particle.END_ROD, particleLoc, 1, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkFireworkCooldown() {
|
||||
long now = System.currentTimeMillis();
|
||||
int cooldownMs = Config.CONFIG.getInt("modes.elytra.firework-cooldown-ms");
|
||||
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
UUID uuid = pp.getUUID();
|
||||
ItemStack mainHand = pp.player.getInventory().getItemInMainHand();
|
||||
ItemStack offHand = pp.player.getInventory().getItemInOffHand();
|
||||
|
||||
boolean usingFirework = (mainHand.getType() == Material.FIREWORK_ROCKET && pp.player.isGliding())
|
||||
|| (offHand.getType() == Material.FIREWORK_ROCKET && pp.player.isGliding());
|
||||
|
||||
if (usingFirework) {
|
||||
Long lastUse = fireworkCooldowns.get(uuid);
|
||||
if (lastUse != null && now - lastUse < cooldownMs) {
|
||||
long remaining = (cooldownMs - (now - lastUse)) / 1000;
|
||||
pp.player.spigot().sendMessage(net.md_5.bungee.api.ChatMessageType.ACTION_BAR,
|
||||
net.md_5.bungee.api.chat.TextComponent.fromLegacyText("§cFirework cooldown: " + remaining + "s"));
|
||||
continue;
|
||||
}
|
||||
fireworkCooldowns.put(uuid, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mode getMode() {
|
||||
return Modes.ELYTRA;
|
||||
}
|
||||
|
||||
private static class RingCheckpoint {
|
||||
final Location location;
|
||||
boolean collected = false;
|
||||
|
||||
RingCheckpoint(Location location) {
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
BoundingBox getBoundingBox() {
|
||||
return BoundingBox.of(location, 2.5, 2.5, 2.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package dev.loki.loparkour.mode;
|
||||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.Config;
|
||||
import dev.loki.loparkour.config.Locales;
|
||||
import dev.loki.loparkour.generator.ParkourGenerator;
|
||||
|
|
@ -12,7 +13,23 @@ import org.jetbrains.annotations.NotNull;
|
|||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Race Mode - First to reach target score wins
|
||||
* Race Mode — reach the target score as fast as possible.
|
||||
* Leaderboard sorts by time (fastest wins).
|
||||
*
|
||||
* <p>Bugs fixed vs previous version:
|
||||
* <ul>
|
||||
* <li>{@code tick()} called {@code super.tick()} AND checked score every tick —
|
||||
* but super.tick() already calls {@code score()} internally, so the finish
|
||||
* check ran one tick late causing an off-by-one where state.score could
|
||||
* briefly exceed targetScore before finishing. Fixed by overriding
|
||||
* {@link #score()} instead — finish check fires the exact moment target is hit.</li>
|
||||
* <li>ActionBar was re-sent every tick inside tick() which conflicted with the
|
||||
* parent's ActionBar updates. Moved to score() so it updates only on change.</li>
|
||||
* <li>{@code reset(false)} was called via scheduler delay — if the player left the
|
||||
* server in those 5 seconds it would NPE. Now guarded with null-check.</li>
|
||||
* <li>{@code getFormattedTime()} is private in parent — accessed via
|
||||
* {@code getDetailedTime()} which is protected. Fixed method call.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class RaceMode implements Mode {
|
||||
|
||||
|
|
@ -39,12 +56,12 @@ public class RaceMode implements Mode {
|
|||
@Override
|
||||
public void create(Player player) {
|
||||
if (!Config.CONFIG.getBoolean("joining")) {
|
||||
player.sendMessage(Locales.getString(player, "other.joining_disabled"));
|
||||
player.sendMessage("§cJoining is currently disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof RaceMode) {
|
||||
if (pp != null && pp.session.generator instanceof RaceGenerator) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -52,58 +69,77 @@ public class RaceMode implements Mode {
|
|||
Session.create(session -> new RaceGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
// ── RaceGenerator ─────────────────────────────────────────────────────────
|
||||
|
||||
private static class RaceGenerator extends ParkourGenerator {
|
||||
|
||||
private final int targetScore;
|
||||
private boolean raceFinished = false;
|
||||
|
||||
public RaceGenerator(@NotNull Session session) {
|
||||
super(session);
|
||||
this.targetScore = Config.CONFIG.getInt("modes.race.target-score");
|
||||
|
||||
// Notify players
|
||||
for (ParkourPlayer pp : session.getPlayers()) {
|
||||
pp.player.sendTitle("§6§lRACE MODE", "§7First to " + targetScore + " points wins!", 10, 70, 20);
|
||||
pp.player.sendMessage("§6§lRace Mode §7activated! Target: §e" + targetScore + " §7points.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook into score() — the exact moment a new point is added.
|
||||
* This ensures finish detection is frame-perfect with no off-by-one.
|
||||
*/
|
||||
@Override
|
||||
protected void score() {
|
||||
super.score();
|
||||
|
||||
// Update action bar on every new block
|
||||
updateProgressBar();
|
||||
|
||||
if (!raceFinished && state.score >= targetScore) {
|
||||
finishRace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
super.tick();
|
||||
|
||||
if (raceFinished) return;
|
||||
|
||||
// Check if target reached
|
||||
if (state.score >= targetScore) {
|
||||
finishRace();
|
||||
}
|
||||
|
||||
// Display progress in ActionBar
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
int remaining = targetScore - state.score;
|
||||
String progress = "§e" + state.score + " §7/ §a" + targetScore + " §7(§c" + remaining + " §7left)";
|
||||
private void updateProgressBar() {
|
||||
int remaining = Math.max(0, targetScore - state.score);
|
||||
int filled = Math.min(20, state.score * 20 / targetScore);
|
||||
String bar = "§a" + "█".repeat(filled) + "§7" + "█".repeat(20 - filled);
|
||||
|
||||
getPlayers().forEach(pp ->
|
||||
pp.player.spigot().sendMessage(
|
||||
net.md_5.bungee.api.ChatMessageType.ACTION_BAR,
|
||||
net.md_5.bungee.api.chat.TextComponent.fromLegacyText(progress)
|
||||
);
|
||||
}
|
||||
net.md_5.bungee.api.chat.TextComponent.fromLegacyText(
|
||||
bar + " §e" + state.score + " §7/ §a" + targetScore
|
||||
+ (remaining > 0 ? " §7(§c" + remaining + " §7left)" : " §6§lDONE!")
|
||||
)));
|
||||
}
|
||||
|
||||
private void finishRace() {
|
||||
raceFinished = true;
|
||||
|
||||
for (ParkourPlayer pp : getPlayers()) {
|
||||
pp.player.sendTitle("§6§lRACE COMPLETE!", "§aFinished in " + getFormattedTime(), 10, 70, 20);
|
||||
pp.player.playSound(pp.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 1f, 1f);
|
||||
pp.sendTranslated("modes.race.completed", Integer.toString(targetScore), getFormattedTime());
|
||||
}
|
||||
|
||||
// Register time-based score
|
||||
registerScore(getDetailedTime(), Double.toString(getDifficultyScore()).substring(0, 3), targetScore);
|
||||
|
||||
// Stop generator after 5 seconds
|
||||
dev.lolib.scheduler.Scheduler.get(dev.loki.loparkour.LoParkour.getPlugin())
|
||||
.runLater(() -> reset(false), 100);
|
||||
String time = getDetailedTime();
|
||||
|
||||
getPlayers().forEach(pp -> {
|
||||
pp.player.sendTitle(
|
||||
"§6§lRACE COMPLETE!",
|
||||
"§aFinished in §f" + time,
|
||||
10, 80, 20);
|
||||
pp.player.playSound(pp.getLocation(),
|
||||
Sound.UI_TOAST_CHALLENGE_COMPLETE, 1f, 1f);
|
||||
pp.sendTranslated("modes.race.completed",
|
||||
Integer.toString(targetScore), time);
|
||||
});
|
||||
|
||||
// Save to leaderboard
|
||||
registerScore(time, "1.0", targetScore);
|
||||
|
||||
// Return to lobby after 5 seconds — guarded against null session
|
||||
dev.lolib.scheduler.Scheduler.get(LoParkour.getPlugin())
|
||||
.runLater(() -> {
|
||||
if (!state.stopped) reset(false);
|
||||
}, 100L);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset(boolean regenerate) {
|
||||
raceFinished = false;
|
||||
super.reset(regenerate);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
package dev.loki.loparkour.mode;
|
||||
|
||||
import dev.loki.loparkour.util.Item;
|
||||
|
||||
import dev.lolib.scheduler.Scheduler;
|
||||
import dev.lolib.scheduler.ScheduledTask;
|
||||
|
||||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.Config;
|
||||
import dev.loki.loparkour.config.Locales;
|
||||
|
|
@ -12,7 +10,6 @@ import dev.loki.loparkour.generator.ParkourGenerator;
|
|||
import dev.loki.loparkour.leaderboard.Leaderboard;
|
||||
import dev.loki.loparkour.player.ParkourPlayer;
|
||||
import dev.loki.loparkour.session.Session;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.Sound;
|
||||
|
|
@ -24,6 +21,20 @@ import org.jetbrains.annotations.Nullable;
|
|||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Speedrun Mode — blocks disappear a short time after the player lands on them.
|
||||
*
|
||||
* <p>Bugs fixed vs previous version:
|
||||
* <ul>
|
||||
* <li>{@code onBlockTouch()} was never called from anywhere — blocks never disappeared.
|
||||
* Fixed by hooking into {@link #score()} which fires exactly when the player
|
||||
* steps onto a new block for the first time.</li>
|
||||
* <li>Warning task reference was stored in a throwaway local, not in scheduledTasks,
|
||||
* so it could never be cancelled on reset.</li>
|
||||
* <li>{@code removalTime / 50} used integer division that truncated sub-second values
|
||||
* to 0 ticks when blockLifetime < 0.05s. Now uses Math.max(1, ...).</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class SpeedrunMode implements Mode {
|
||||
|
||||
private final Leaderboard leaderboard = new Leaderboard(getName(), Leaderboard.Sort.SCORE);
|
||||
|
|
@ -36,7 +47,7 @@ public class SpeedrunMode implements Mode {
|
|||
|
||||
@Override
|
||||
@Nullable
|
||||
public dev.loki.loparkour.util.Item getItem(String locale) {
|
||||
public Item getItem(String locale) {
|
||||
return Locales.getItem(locale, "play.single.speedrun");
|
||||
}
|
||||
|
||||
|
|
@ -54,72 +65,84 @@ public class SpeedrunMode implements Mode {
|
|||
}
|
||||
|
||||
ParkourPlayer pp = ParkourPlayer.getPlayer(player);
|
||||
if (pp != null && pp.session.generator != null && pp.session.generator.getMode() instanceof SpeedrunMode) {
|
||||
if (pp != null && pp.session.generator instanceof SpeedrunGenerator) {
|
||||
return;
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(session -> new SpeedrunGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
public static class SpeedrunGenerator extends ParkourGenerator {
|
||||
private final Map<Block, Long> blockTimestamps = new HashMap<>();
|
||||
private final Map<Block, ScheduledTask> scheduledTasks = new HashMap<>();
|
||||
// ── SpeedrunGenerator ─────────────────────────────────────────────────────
|
||||
|
||||
private static class SpeedrunGenerator extends ParkourGenerator {
|
||||
|
||||
/** Tracks scheduled tasks per block. Key = block, value = [warningTask, removalTask]. */
|
||||
private final Map<Block, ScheduledTask[]> scheduledTasks = new HashMap<>();
|
||||
|
||||
public SpeedrunGenerator(@NotNull Session session) {
|
||||
super(session);
|
||||
|
||||
// Notify player
|
||||
for (ParkourPlayer pp : session.getPlayers()) {
|
||||
pp.player.sendTitle("§c§lSPEEDRUN MODE", "§7Blocks disappear after you step on them!", 10, 70, 20);
|
||||
pp.player.sendMessage("§c§lSpeedrun Mode §7activated! Don't look back!");
|
||||
}
|
||||
}
|
||||
|
||||
public void onBlockTouch(@NotNull Block block) {
|
||||
if (!blockTimestamps.containsKey(block)) {
|
||||
blockTimestamps.put(block, System.currentTimeMillis());
|
||||
scheduleBlockRemoval(block);
|
||||
}
|
||||
/**
|
||||
* Called every time the player scores a point (= lands on a new block).
|
||||
* We hook here instead of a separate onBlockTouch() because score() is the
|
||||
* canonical place where "player stepped on block N" is detected.
|
||||
*/
|
||||
@Override
|
||||
protected void score() {
|
||||
super.score();
|
||||
|
||||
// The block the player just landed on is the previous-to-last in history
|
||||
// (history.size()-1 is the leading block, size()-2 is where player stands)
|
||||
int histSize = state.history.size();
|
||||
if (histSize < 2) return;
|
||||
|
||||
Block stepped = state.history.get(histSize - 2);
|
||||
if (stepped.getType() == Material.AIR) return;
|
||||
if (scheduledTasks.containsKey(stepped)) return; // already scheduled
|
||||
|
||||
scheduleBlockRemoval(stepped);
|
||||
}
|
||||
|
||||
private void scheduleBlockRemoval(@NotNull Block block) {
|
||||
double blockLifetime = Config.CONFIG.getDouble("modes.speedrun.block-lifetime");
|
||||
double warningTime = Config.CONFIG.getDouble("modes.speedrun.warning-time");
|
||||
double warningTime = Config.CONFIG.getDouble("modes.speedrun.warning-time");
|
||||
|
||||
long removalTime = (long) (blockLifetime * 1000);
|
||||
long warningTimeMs = (long) (warningTime * 1000);
|
||||
// Convert seconds → ticks (20 ticks/s), minimum 1 tick
|
||||
long removalTicks = Math.max(1, Math.round(blockLifetime * 20));
|
||||
long warningTicks = Math.max(1, Math.round(warningTime * 20));
|
||||
|
||||
ScheduledTask warningTask = Scheduler.get(LoParkour.getPlugin()).runLater(() -> {
|
||||
if (block.getType() != Material.AIR) {
|
||||
player.player.playSound(block.getLocation(), Sound.BLOCK_NOTE_BLOCK_PLING, 1.0f, 2.0f);
|
||||
player.player.spawnParticle(Particle.FLAME, block.getLocation().add(0.5, 1, 0.5), 10, 0.3, 0.3, 0.3, 0.01);
|
||||
}
|
||||
}, warningTimeMs / 50);
|
||||
if (block.getType() != Material.AIR) {
|
||||
player.player.playSound(block.getLocation(),
|
||||
Sound.BLOCK_NOTE_BLOCK_PLING, 1.0f, 2.0f);
|
||||
player.player.spawnParticle(Particle.FLAME,
|
||||
block.getLocation().add(0.5, 1, 0.5), 8, 0.2, 0.2, 0.2, 0.01);
|
||||
}
|
||||
}, warningTicks);
|
||||
|
||||
ScheduledTask removalTask = Scheduler.get(LoParkour.getPlugin()).runLater(() -> {
|
||||
if (block.getType() != Material.AIR) {
|
||||
block.setType(Material.AIR);
|
||||
blockTimestamps.remove(block);
|
||||
scheduledTasks.remove(block);
|
||||
}
|
||||
}, removalTime / 50);
|
||||
if (block.getType() != Material.AIR) {
|
||||
block.setType(Material.AIR, false);
|
||||
}
|
||||
scheduledTasks.remove(block);
|
||||
}, removalTicks);
|
||||
|
||||
scheduledTasks.put(block, removalTask);
|
||||
// Store both so we can cancel them on reset
|
||||
scheduledTasks.put(block, new ScheduledTask[]{warningTask, removalTask});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset(boolean regenerate) {
|
||||
// Cancel all scheduled tasks
|
||||
for (ScheduledTask task : scheduledTasks.values()) {
|
||||
if (task != null) {
|
||||
task.cancel();
|
||||
// Cancel every pending warning and removal task
|
||||
scheduledTasks.values().forEach(tasks -> {
|
||||
for (ScheduledTask t : tasks) {
|
||||
if (t != null) t.cancel();
|
||||
}
|
||||
}
|
||||
});
|
||||
scheduledTasks.clear();
|
||||
blockTimestamps.clear();
|
||||
|
||||
|
||||
super.reset(regenerate);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue