Skip to content

Instantly share code, notes, and snippets.

@PaulBGD
Created October 14, 2013 02:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulBGD/6969970 to your computer and use it in GitHub Desktop.
Save PaulBGD/6969970 to your computer and use it in GitHub Desktop.
RollbackRunnable Resource 1
package me.ultimate.Arena;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.block.BlockState;
import org.bukkit.scheduler.BukkitRunnable;
public class RollbackRunnable extends BukkitRunnable {
// To hold our original blocks, and the ones that have changed
private List<BlockState> originalBlocks, changedBlocks = new ArrayList<BlockState>();
public RollbackRunnable(List<BlockState> originalBlocks) {
this.originalBlocks = originalBlocks;
}
// Now we're going to go through all of our blocks, and check if they
// changed.
@Override
public void run() {
// Loop through
for (BlockState state : originalBlocks) {
/*
* This checks if the current block's type is the same as the stored
* one. If not, add it to the changed list.
*/
if (!state.getBlock().getType().equals(state.getType())) {
changedBlocks.add(state);
}
}
// To clear some of our RAM, we'll clear the list of original blocks.
originalBlocks = null;
/*
* Starts the rollbacker with the current blocks. What the 5 means, is
* how many ticks between each setting of blocks.
*
* While normally you would pass the main class's instance along in
* constructors, for the sake of this tutorial I made it a static
* variable.
*/
new StaggeredRunnable().runTaskTimer(ArenaTutorial.instance, 0, 5);
}
/*
* Now, we want to rollback all of our blocks. But if you've ever done a
* really large worldedit or schematic paste, you know that it will lag the
* server to set so many blocks at once. What this does, is space it out
* making it so they're not all set at once.
*/
private class StaggeredRunnable extends BukkitRunnable {
/*
* maxIterations: How many blocks it sets before pausing
*
* iterations: How many blocks it has done in the current iteration
*/
private int maxIterations = 300, iterations = 0;
@Override
public void run() {
iterations = 0;
// While there are still unchanged blocks, and iterations left
while (!changedBlocks.isEmpty() && iterations < maxIterations) {
/*
* Gets the first changed block from the list, then updates it.
* What this does, is update it to the previous data
* (technically not updating). The second boolean makes sure
* that if it's something like a torch, it would break if it
* gets placed on air or something.
*/
changedBlocks.get(0).update(true, false);
// Removed it from the list
changedBlocks.remove(0);
// Increase iterations by 1
iterations++;
}
// If all blocks are changed
if (changedBlocks.isEmpty()) {
// Cancel itself
cancel();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment