Java Code Examples for org.bukkit.scheduler.BukkitRunnable

The following are top voted examples for showing how to use org.bukkit.scheduler.BukkitRunnable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SpigotBoard   File: SBScoreboard.java   Source Code and License 7 votes vote down vote up
@Override
public void enableScoreboard() {
       final Scoreboard board = Bukkit.getScoreboardManager().getNewScoreboard();
       final Objective obj = board.registerNewObjective("Spigotboard", "dummy");
       
       obj.setDisplaySlot(DisplaySlot.SIDEBAR);
       obj.setDisplayName(ChatColor.translateAlternateColorCodes('&', Main.instance.getConfig().getString("title")));

       new BukkitRunnable() {
           @Override
           public void run() {
               for(Player p : Bukkit.getOnlinePlayers()) {
               	int count = Main.instance.getConfig().getList("text").size();
               	
               	PlaceholderUtils placeholders = new PlaceholderUtils(p);
                   for(Object text : Main.instance.getConfig().getList("text")){
                   	obj.getScore(ChatColor.translateAlternateColorCodes('&', placeholders.replace(text.toString()))).setScore(count);
                   	count--;
                   }
                   p.setScoreboard(board);
               }
           }
       }.runTaskTimer(Main.instance, 0, 20);
}
 
Example 2
Project: HCFCore   File: PlayerBoard.java   Source Code and License 6 votes vote down vote up
public void setTemporarySidebar(final SidebarProvider provider, final long expiration) {
    if (this.removed.get()) {
        throw new IllegalStateException("Cannot update whilst board is removed");
    }
    this.temporaryProvider = provider;
    this.updateObjective();
    new BukkitRunnable() {
        public void run() {
            if (PlayerBoard.this.removed.get()) {
                this.cancel();
                return;
            }
            if (PlayerBoard.this.temporaryProvider == provider) {
                PlayerBoard.access$4(PlayerBoard.this, null);
                PlayerBoard.this.updateObjective();
            }
        }
    }.runTaskLaterAsynchronously((Plugin)this.plugin, expiration);
}
 
Example 3
Project: mczone   File: GameEvents.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
	final Gamer g = Gamer.get(event.getPlayer());
	
	new BukkitRunnable() {

		@Override
		public void run() {
			Team t = Nexus.getRotary().getCurrentMap().getTeam(g);
			
			if (t == null) {
				g.teleport(Nexus.getRotary().getCurrentMap().getSpawnLocation());
				return;
			}
			
			g.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 20 * 5, 3));
			
			g.teleport(t.getSpawnLocation());
			g.run("give-kit");
		}
		
	}.runTaskLater(Nexus.getPlugin(), 1);
}
 
Example 4
Project: PA   File: Helpers.java   Source Code and License 6 votes vote down vote up
public void lobbyScoreboard() {
    ScoreboardUtil board = new ScoreboardUtil(PAData.LOBBY.getPrefix(), "lobby");
    new BukkitRunnable() {
        @Override
        public void run() {
            if (u.getPlayer() == null) {
                board.reset();
                cancel();
                return;
            }

            if (!u.isOnline()) {
                board.reset();
                cancel();
                return;
            }

            board.setName(PAData.LOBBY.getOldPrefix());
            board.text(3, "§d ");
            board.text(2, "Rango: §" + PACmd.Grupo.groupColor(u.getUserData().getGrupo()) + u.getUserData().getGrupo().toString());
            board.text(1, "§d ");
            board.text(0, PACore.getIP().replace('&', '§'));
            board.build(u.getPlayer());
        }
    }.runTaskTimer(PALobby.getInstance(), 1, 20);
}
 
Example 5
Project: Arcadia-Spigot   File: KingOfTheHillGame.java   Source Code and License 6 votes vote down vote up
@Override
public void onGameStart() {
    this.allowPVP = true;
    new BukkitRunnable() {
        public void run() {
            if(getAPI().getGameManager().getGameState() != GameState.INGAME) {
                this.cancel();
                return;
            }
            for(Player player : Bukkit.getOnlinePlayers()) {
                if(!getAPI().getGameManager().isAlive(player)) continue;
                if(hill.contains(player.getLocation())) {
                    ScoreSidebar scoreSidebar = (ScoreSidebar) getSidebar();
                    scoreSidebar.setScore(player, (scoreSidebar.getScore(player)+1));
                }
            }
        }
    }.runTaskTimer(this.getAPI().getPlugin(), 0, 20L);
}
 
Example 6
Project: RPGInventory   File: ItemListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR)
public void afterEquipChange(final InventoryDragEvent event) {
    final Player player = (Player) event.getWhoClicked();

    if (!InventoryManager.playerIsLoaded(player)) {
        return;
    }

    new BukkitRunnable() {
        @Override
        public void run() {
            InventoryView inventoryView = event.getView();
            for (int slot : event.getRawSlots()) {
                ItemStack item = inventoryView.getItem(slot);
                if (CustomItem.isCustomItem(item)) {
                    ItemManager.updateStats((Player) event.getWhoClicked());
                }
            }
        }
    }.runTaskLater(RPGInventory.getInstance(), 1);
}
 
Example 7
Project: OpenRPG   File: NPC.java   Source Code and License 6 votes vote down vote up
public void spawn(OpenPlayer player) {
        PlayerConnection connection = player.getConnection();

        connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, this.entity));
        connection.sendPacket(new PacketPlayOutNamedEntitySpawn(this.entity));

//        if (this.sleeping) {
//            connection.sendPacket(new PacketPlayOutBed(this.entity, new BlockPosition(this.entity.locX, this.entity.locY - 1, this.entity.locZ)));
//        }

        new BukkitRunnable() {
            @Override
            public void run() {
                connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, entity));
            }
        }.runTaskLater(Main.getInstance(), 20 * 5);
    }
 
Example 8
Project: OMGPI   File: Game.java   Source Code and License 6 votes vote down vote up
/**
 * Start game: discovery or get ready to start.
 */
public void game_start() {
    if (state == GameState.PRELOBBY) {
        event_game_preStart();
        if (settings.hasDiscovery) {
            OMGPlayer.link.values().forEach(p -> gamePreparer.player_start_discovery(p));
            event_game_discovery();
            state = GameState.DISCOVERY;
            broadcast(ChatColor.AQUA + "You have " + (settings.discoveryLength / 20) + " seconds to discover the map.");
            discoveryStartDelay = new BukkitRunnable() {
                public void run() {
                    game_readyToStart();
                }
            };
            discoveryStartDelay.runTaskLater(this, settings.discoveryLength);
        } else {
            OMGPlayer.link.values().forEach(p -> gamePreparer.player_start_nonDiscovery(p));
            game_readyToStart();
        }
    }
}
 
Example 9
Project: black   File: LiveElement.java   Source Code and License 6 votes vote down vote up
@Override
public void displayOn(Inventory inventory, int locX, int locY) {
    frames[0].displayOn(inventory, locX, locY);

    new BukkitRunnable(){
        private int iterator;

        @Override
        public void run() {
            if (inventory.getViewers().isEmpty()) {
                this.cancel();
            } else {
                nextFrame().displayOn(inventory, locX, locY);
            }
        }

        private final Element nextFrame() {
            iterator = iterator + 1 < frames.length
                ? iterator + 1
                : 0;

            return frames[iterator];
        }
    }.runTaskTimer(plugin, 1, period);
}
 
Example 10
Project: ZorahPractice   File: PlayerTab.java   Source Code and License 6 votes vote down vote up
public PlayerTab(Player player) {
    this.player = player;

    entries = new ArrayList<>();

    clear();

    if (!player.getScoreboard().equals(Bukkit.getScoreboardManager().getMainScoreboard())) {
        scoreboard = player.getScoreboard();
        assemble();
    } else {
        new BukkitRunnable() {
            @Override
            public void run() {
                scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
                player.setScoreboard(scoreboard);
                assemble();
            }
        }.runTask(PracticePlugin.getInstance());
    }

    playerTabs.add(this);
}
 
Example 11
Project: Hub   File: OpeningAnimationRunnable.java   Source Code and License 6 votes vote down vote up
private void walk(Location location, Runnable callback)
{
    this.graou.getGraouEntity().getPathfinderGoalWalkToTile().setTileToWalk(location.getX(), location.getY(), location.getZ());

    new BukkitRunnable()
    {
        @Override
        public void run()
        {
            Optional<Entity> entity = ProximityUtils.getNearbyEntities(location, 3.0D).stream()
                    .filter(e -> e.getUniqueId() != null)
                    .filter(e -> e.getUniqueId() == OpeningAnimationRunnable.this.graou.getGraouEntity().getUniqueID())
                    .findAny();

            if (entity.isPresent())
            {
                OpeningAnimationRunnable.this.graou.getGraouEntity().getPathfinderGoalWalkToTile().cancel();
                OpeningAnimationRunnable.this.hub.getServer().getScheduler().runTask(OpeningAnimationRunnable.this.hub, callback);

                this.cancel();
            }
        }
    }.runTaskTimer(this.hub, 5L, 5L);
}
 
Example 12
Project: skLib   File: Main.java   Source Code and License 6 votes vote down vote up
public static void sendMessage(final String channel, final String msg) {
    if (!connected) {
        return;
    }
    Jedis jedis = pool.getResource();
    new BukkitRunnable(){

        public void run() {
            if (!Main.connected) {
                return;
            }
            try {
            	jedis.publish(channel, msg);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            jedis.close();
        }
    }.runTaskAsynchronously(plugin);
}
 
Example 13
Project: OMGPI   File: Game.java   Source Code and License 6 votes vote down vote up
/**
 * Stop the game and reload OMGPI.
 */
public void game_stop() {
    if (state == GameState.INGAME) {
        OMGPlayer.link.values().forEach(p -> {
            if (p.team != spectatorTeam) {
                p.setTeam(spectatorTeam);
                if (p.played) player_reward(p, "winner");
            } else if (p.played) player_reward(p, "loser");
            p.play_sound_levelup();
        });
        broadcast(ChatColor.AQUA + "You will be sent to the prelobby in 10 seconds.");
        state = GameState.ENDING;
        if (infoBar != null) infoBar.removeAll();
        new BukkitRunnable() {
            public void run() {
                event_game_stop();
                OMGPI.instance.reload();
            }
        }.runTaskLater(OMGPI.instance, 200L);
    }
}
 
Example 14
Project: HCFCore   File: DeathbanListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled=true, priority=EventPriority.LOW)
/*     */   public void onPlayerDeath(PlayerDeathEvent event) {
/*  99 */     final Player player = event.getEntity();
/* 100 */     final Deathban deathban = this.plugin.getDeathbanManager().applyDeathBan(player, event.getDeathMessage());
/* 101 */     long remaining = deathban.getRemaining();
/* 102 */     if ((remaining <= 0L) || (player.hasPermission("hcf.deathban.bypass"))) {
/* 103 */       return;
/*     */     }
/*     */
/* 106 */     if ((RESPAWN_KICK_DELAY_MILLIS <= 0L) || (remaining < RESPAWN_KICK_DELAY_MILLIS)) {
/* 107 */       handleKick(player, deathban);
/* 108 */       return;
/*     */     }
/*     */
/*     */
/* 112 */     this.respawnTickTasks.put(player.getUniqueId(), new BukkitRunnable()
/*     */     {
            /*     */       public void run() {
/* 115 */         DeathbanListener.this.handleKick(player, deathban);
/*     */       }
/* 117 */     }.runTaskLater(this.plugin, RESPAWN_KICK_DELAY_TICKS).getTaskId());
/*     */   }
 
Example 15
Project: HCFCore   File: LoggerEntityHuman.java   Source Code and License 6 votes vote down vote up
@Override
public void postSpawn(HCF plugin) {
    if (this.world.addEntity((Entity)this)) {
        Bukkit.getConsoleSender().sendMessage(String.format((Object)ChatColor.GOLD + "Combat logger of " + this.getName() + " has spawned at %.2f, %.2f, %.2f", this.locX, this.locY, this.locZ));
        MinecraftServer.getServer().getPlayerList().playerFileData.load((EntityHuman)this);
    } else {
        Bukkit.getConsoleSender().sendMessage(String.format((Object)ChatColor.RED + "Combat logger of " + this.getName() + " failed to spawned at %.2f, %.2f, %.2f", this.locX, this.locY, this.locZ));
    }
    this.removalTask = new BukkitRunnable(){

        public void run() {
            MinecraftServer.getServer().getPlayerList().sendAll((Packet)PacketPlayOutPlayerInfo.removePlayer((EntityPlayer)LoggerEntityHuman.this.getBukkitEntity().getHandle()));
            LoggerEntityHuman.this.destroy();
        }
    }.runTaskLater((Plugin)plugin, SettingsYML.COMBAT_LOG_DESPAWN_TICKS);
}
 
Example 16
Project: Hub   File: DeveloperRoomParkour.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerResourcePackStatus(PlayerResourcePackStatusEvent event)
{
    if (!this.expected.contains(event.getPlayer().getUniqueId()) || event.getStatus() != PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED)
        return;

    this.playMusic(event.getPlayer());

    new BukkitRunnable()
    {
        @Override
        public void run()
        {
            if (expected.contains(event.getPlayer().getUniqueId()))
                playMusic(event.getPlayer());
            else
                this.cancel();
        }
    }.runTaskTimer(this.hub, MUSIC_LENGTH, MUSIC_LENGTH);
}
 
Example 17
Project: black   File: LivePane.java   Source Code and License 6 votes vote down vote up
@Override
public void displayOn(Inventory inventory) {
    frames[0].displayOn(inventory);

    new BukkitRunnable(){
        private int iterator;

        @Override
        public void run() {
            if (inventory.getViewers().isEmpty()) {
                this.cancel();
            } else {
                nextFrame().displayOn(inventory);
            }
        }

        private final Pane nextFrame() {
            iterator = iterator + 1 < frames.length
                ? iterator + 1
                : 0;

            return frames[iterator];
        }
    }.runTaskTimer(plugin, 1, period);
}
 
Example 18
Project: InventoryAPI   File: InventorySlotWatcher.java   Source Code and License 6 votes vote down vote up
public void startListing() {
    if ( !active ) {
        scheduler = new BukkitRunnable() {
            @Override
            public void run() {
                if ( ( inventory.getContents()[slot] == null ) == ( lastItemStack == null ) ) {
                    if ( lastItemStack != null && !lastItemStack.equals( inventory.getContents()[slot] ) ) {
                        update( inventory.getContents()[slot] );
                    }
                }
                else {
                    update( inventory.getContents()[slot] );
                }
            }
        };
        scheduler.runTaskTimer(plugin, 1L, 1L );
        active = true;
    }
}
 
Example 19
Project: DragonEggDrop   File: DragonEggDrop.java   Source Code and License 6 votes vote down vote up
private void doVersionCheck() {
	new BukkitRunnable() {
		@Override
		public void run() {
			try (BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(SPIGET_LINK).openStream()))){
				JsonObject object = GSON.fromJson(reader, JsonObject.class);
				String currentVersion = getDescription().getVersion();
				String recentVersion = object.get("name").getAsString();
				
				if (!currentVersion.equals(recentVersion)) {
					getLogger().info("New version available. Your Version = " + currentVersion + ". New Version = " + recentVersion);
					newVersionAvailable = true;
					newVersion = recentVersion;
				}
			} catch (IOException e) {
				getLogger().info("Could not check for a new version. Perhaps the website is down?");
			}
		}
	}.runTaskAsynchronously(this);
}
 
Example 20
Project: FactionsXL   File: FScoreboard.java   Source Code and License 6 votes vote down vote up
public void setDefaultSidebar(final FSidebarProvider provider, int updateInterval) {
    if (!isSupportedByServer()) {
        return;
    }

    defaultProvider = provider;
    if (temporaryProvider == null) {
        // We have no temporary provider; update the BufferedObjective!
        updateObjective();
    }

    new BukkitRunnable() {
        @Override
        public void run() {
            if (removed || provider != defaultProvider) {
                cancel();
                return;
            }

            if (temporaryProvider == null) {
                updateObjective();
            }
        }
    }.runTaskTimer(plugin, updateInterval, updateInterval);
}
 
Example 21
Project: ZorahPractice   File: PlayerListener.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerTabCreateEvent(PlayerTabCreateEvent event) {
    if (!PracticeConfiguration.USE_TAB) {
        return;
    }

    PlayerTab playerTab = event.getPlayerTab();

    new BukkitRunnable() {
        public void run() {
            if (playerTab == null || playerTab.getPlayer() == null || !playerTab.getPlayer().isOnline()) {
                this.cancel();
                return;
            }

            try {
                updateTab(playerTab);
            }
            catch (Exception e) {
                e.printStackTrace();
                this.cancel();
                playerTab.getPlayer().sendMessage(ChatColor.RED + "Failed to load your tab info, re-join if you want to re-attempt to load it.");
            }
        }
    }.runTaskTimerAsynchronously(PracticePlugin.getInstance(), 0L, 10L);
}
 
Example 22
Project: HCFCore   File: LoggerEntityHuman.java   Source Code and License 6 votes vote down vote up
@Override
public void postSpawn(HCF plugin) {
    if (this.world.addEntity((Entity)this)) {
        Bukkit.getConsoleSender().sendMessage(String.format((Object)ChatColor.GOLD + "Combat logger of " + this.getName() + " has spawned at %.2f, %.2f, %.2f", this.locX, this.locY, this.locZ));
        MinecraftServer.getServer().getPlayerList().playerFileData.load((EntityHuman)this);
    } else {
        Bukkit.getConsoleSender().sendMessage(String.format((Object)ChatColor.RED + "Combat logger of " + this.getName() + " failed to spawned at %.2f, %.2f, %.2f", this.locX, this.locY, this.locZ));
    }
    this.removalTask = new BukkitRunnable(){

        public void run() {
            MinecraftServer.getServer().getPlayerList().sendAll((Packet)PacketPlayOutPlayerInfo.removePlayer((EntityPlayer)LoggerEntityHuman.this.getBukkitEntity().getHandle()));
            LoggerEntityHuman.this.destroy();
        }
    }.runTaskLater((Plugin)plugin, SettingsYML.COMBAT_LOG_DESPAWN_TICKS);
}
 
Example 23
Project: MBedwars-Kits   File: Events.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onArenaStatusUpdateEvent(final ArenaStatusUpdateEvent event){
	// give every player the items of their kits if the arena is starting
	if(BedwarsAddonKits.kits.size() >= 1 && event.getStatusBefore() == ArenaStatus.Lobby && event.getStatus() == ArenaStatus.Running){
		// wait a secound before giving him his items because if we would give them him now, they would disappear
		new BukkitRunnable(){
			@Override
			public void run(){
				for(Player player:event.getArena().getPlayers()){
					for(ItemStack is:BedwarsAddonKits.selectedKits.get(player).getItems())
						player.getInventory().addItem(is);
				}
			}
		}.runTaskLater(BedwarsAddonKits.plugin, 20);
	}
}
 
Example 24
Project: ZorahPractice   File: Cache.java   Source Code and License 6 votes vote down vote up
public static void storeInventory(Player player, boolean dead) {
    List<String> effects = new ArrayList<>();
    player.getActivePotionEffects().forEach(effect -> effects.add(effect.getType().getName() + " " + effect.getAmplifier() + " (" + TimeUtil.formatSeconds(effect.getDuration() / 20) + ")"));
    CachedInventory inv = getCachedInventory(player, dead);

    if (inventories.containsKey(player.getUniqueId())) {
        inventories.replace(player.getUniqueId(), inv);
    }
    else {
        inventories.put(player.getUniqueId(), inv);
    }

    new BukkitRunnable() {
        public void run() {
            if (inventories.containsKey(player.getUniqueId()) && inventories.get(player.getUniqueId()).getIdentifier().equals(inv.getIdentifier())) {
                inventories.remove(player.getUniqueId());
            }
        }
    }.runTaskLater(PracticePlugin.getInstance(), 20L * 60);
}
 
Example 25
Project: AlphaLibary   File: EndercrystalFakeUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Teleport a {@link FakeEndercrystal} to a specific {@link Location} in certain intervals, which is visible for all Players
 *
 * @param p             the {@link Player} to teleport the {@link FakeEndercrystal} for
 * @param to            the {@link Location} where the {@link FakeEndercrystal} should be teleported to
 * @param teleportCount the amount of teleportation that should be made
 * @param wait          the amount of time to wait 'till the next teleport starts
 * @param endercrystal  the {@link FakeEndercrystal} which should be teleported
 */
public static void splitTeleportBigItem(final Player p, final Location to, final int teleportCount, final long wait, final FakeEndercrystal endercrystal) {
    final Location currentLocation = endercrystal.getCurrentlocation();
    Vector between = to.toVector().subtract(currentLocation.toVector());

    final double toMoveInX = between.getX() / teleportCount;
    final double toMoveInY = between.getY() / teleportCount;
    final double toMoveInZ = between.getZ() / teleportCount;

    SPLIT_MAP.put(p.getName(), new BukkitRunnable() {
        public void run() {
            if (!LocationUtil.isSameLocation(currentLocation, to)) {
                teleportEndercrystal(p, currentLocation.add(new Vector(toMoveInX, toMoveInY, toMoveInZ)), endercrystal);
            } else
                this.cancel();
        }
    }.runTaskTimer(AlphaLibary.getInstance(), 0, wait));
}
 
Example 26
Project: mczone   File: KitEvents.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
	final Gamer g = Gamer.get(event.getPlayer());

	if (g.getVariable("spectator") != null)
		return;
	
	if (g.getVariable("kit") != Kit.get("tank"))
		return;
	
	g.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1, 100), true);
	
	if (g.getPlayer().isSprinting()) {
		new BukkitRunnable() {
			public void run() {
				g.getPlayer().setSprinting(false);
			}
		}.runTaskLater(Nexus.getPlugin(), 1);
	}
}
 
Example 27
Project: AlphaLibary   File: MobFakeUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Teleport a {@link FakeMob} to a specific {@link Location} in certain intervals, which is visible for all Players
 *
 * @param p             the {@link Player} to teleport the {@link FakeMob} for
 * @param to            the {@link Location} where the {@link FakeMob} should be teleported to
 * @param teleportCount the amount of teleportation that should be made
 * @param wait          the amount of time to wait 'till the next teleport starts
 * @param mob           the {@link FakeMob} which should be teleported
 */
public static void splitTeleportMob(final Player p, final Location to, final int teleportCount, final long wait, final FakeMob mob) {
    final Location currentLocation = mob.getCurrentlocation();
    Vector between = to.toVector().subtract(currentLocation.toVector());

    final double toMoveInX = between.getX() / teleportCount;
    final double toMoveInY = between.getY() / teleportCount;
    final double toMoveInZ = between.getZ() / teleportCount;

    SPLIT_MAP.put(p.getName(), new BukkitRunnable() {
        public void run() {
            if (!LocationUtil.isSameLocation(currentLocation, to)) {
                teleportMob(p, currentLocation.add(new Vector(toMoveInX, toMoveInY, toMoveInZ)), mob);
            } else
                this.cancel();
        }
    }.runTaskTimer(AlphaLibary.getInstance(), 0, wait));
}
 
Example 28
Project: AlphaLibary   File: BigItemFakeUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Teleport a {@link FakeBigItem} to a specific {@link Location} in certain intervals, which is visible for all Players
 *
 * @param p             the {@link Player} to teleport the {@link FakeBigItem} for
 * @param to            the {@link Location} where the {@link FakeBigItem} should be teleported to
 * @param teleportCount the amount of teleportation that should be made
 * @param wait          the amount of time to wait 'till the next teleport starts
 * @param item          the {@link FakeBigItem} which should be teleported
 */
public static void splitTeleportBigItem(final Player p, final Location to, final int teleportCount, final long wait, final FakeBigItem item) {
    final Location currentLocation = item.getCurrentlocation();
    Vector between = to.toVector().subtract(currentLocation.toVector());

    final double toMoveInX = between.getX() / teleportCount;
    final double toMoveInY = between.getY() / teleportCount;
    final double toMoveInZ = between.getZ() / teleportCount;

    SPLIT_MAP.put(p.getName(), new BukkitRunnable() {
        public void run() {
            if (!LocationUtil.isSameLocation(currentLocation, to)) {
                teleportBigItem(p, currentLocation.add(new Vector(toMoveInX, toMoveInY, toMoveInZ)), item);
            } else
                this.cancel();
        }
    }.runTaskTimer(AlphaLibary.getInstance(), 0, wait));
}
 
Example 29
Project: Locked   File: Prison.java   Source Code and License 6 votes vote down vote up
private void playTimeCounter() {
    new BukkitRunnable() {

        @Override
        public void run() {
            for (UUID uuid : playtime.keySet()) {
                playtime.put(uuid, playtime.get(uuid) + 1);
                if (playtime.get(uuid) % 3600 == 0) {
                    if (RankManager.isPrisoner(Bukkit.getPlayer(uuid))) {
                        Bukkit.getPlayer(uuid).setTotalExperience(Bukkit.getPlayer(uuid).getTotalExperience() + 100);
                    }
                }
            }
        }
    }.runTaskTimer(this, 0, 20);
}
 
Example 30
Project: ZorahPractice   File: KitEditManager.java   Source Code and License 6 votes vote down vote up
private void finishEditing(Player player) {
    this.editKits.remove(player.getUniqueId());

    ManagerHandler.getEntityHider().showAllPlayers(player);
    PracticeProfile profile = ManagerHandler.getPlayerManager().getPlayerProfile(player);
    profile.setStatus(PlayerStatus.LOBBY);

    GameUtils.resetPlayer(player);
    player.updateInventory();

    new BukkitRunnable() {
        public void run() {
            player.getInventory().setContents(GameUtils.getLobbyInventory());
            player.updateInventory();
        }
    }.runTaskLater(PracticePlugin.getInstance(), 2L);

    ManagerHandler.getConfig().teleportToSpawn(player);
    player.sendMessage(ChatColor.GRAY + "You have been returned to spawn.");
}
 
Example 31
Project: ZorahPractice   File: TvTQueue.java   Source Code and License 6 votes vote down vote up
private void startTask() {
    this.queueTask = new BukkitRunnable() {
        public void run() {
            if (playingAmount < 0) {
                playingAmount = 0;
            }

            Iterator<QueueData> iterator = searchList.iterator();

            while (iterator.hasNext()) {
                QueueData search = iterator.next();

                if (!iterator.hasNext()) {
                    continue;
                }

                QueueData found = iterator.next();

                createMatch(search, found);
            }
        }
    }.runTaskTimer(PracticePlugin.getInstance(), 0L, 2L);
}
 
Example 32
Project: ZorahPractice   File: StorageBackend.java   Source Code and License 6 votes vote down vote up
private synchronized void createTables() {
    new BukkitRunnable() {
        public void run() {
            Connection connection = null;

            try {
                connection = poolManager.getConnection();
                connection.prepareStatement("CREATE TABLE IF NOT EXISTS `practice_profiles` (`id` INT(11) NOT NULL AUTO_INCREMENT, `player_name` VARCHAR(16) NOT NULL, `player_uuid` VARCHAR(36) NOT NULL, `playtime` BIGINT(20) NOT NULL DEFAULT '0', `ranked_wins` INT(11) NOT NULL DEFAULT '0', `ranked_losses` INT(11) NOT NULL DEFAULT '0', `unranked_wins` INT(11) NOT NULL DEFAULT '0', `unranked_losses` INT(11) NOT NULL DEFAULT '0', `matches_played` INT(11) NOT NULL DEFAULT '0', `global_rating` INT(11) NOT NULL DEFAULT '1000', PRIMARY KEY (`id`), UNIQUE (`player_uuid`));").executeUpdate();
                connection.prepareStatement("CREATE TABLE IF NOT EXISTS `practice_matches` (`id` int(11) NOT NULL AUTO_INCREMENT, `match_uuid` varchar(36) NOT NULL, `winner_name` varchar(16) NOT NULL, `winner_uuid` varchar(36) NOT NULL, `loser_name` varchar(16) NOT NULL, `loser_uuid` varchar(36) NOT NULL, `ladder` varchar(64) NOT NULL, `competitive` varchar(32) NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `elo_change` int(5) NOT NULL, PRIMARY KEY (`id`));").executeUpdate();
            }
            catch (SQLException e) {
                if (!e.getMessage().contains("already exists")) {
                    PracticePlugin.getInstance().getLogger().severe("Failed createTables");
                    e.printStackTrace();
                }
            }
            finally {
                poolManager.close(connection, null, null);
            }
        }
    }.runTaskAsynchronously(PracticePlugin.getInstance());
}
 
Example 33
Project: HCFCore   File: DeathbanListener.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    Deathban deathban = plugin.getDeathbanManager().applyDeathBan(player, event.getDeathMessage());
    long remaining = deathban.getRemaining();
    if (remaining <= 0L || player.hasPermission(DeathbanListener.DEATH_BAN_BYPASS_PERMISSION)) {
        return;
    }

    if (DeathbanListener.RESPAWN_KICK_DELAY_MILLIS <= 0L || remaining < DeathbanListener.RESPAWN_KICK_DELAY_MILLIS) {
        this.handleKick(player, deathban);
        return;
    }

    // Let the player see the death screen for 10 seconds
    this.respawnTickTasks.put(player.getUniqueId(), new BukkitRunnable() {
        @Override
        public void run() {
            DeathbanListener.this.handleKick(player, deathban);
        }
    }.runTaskLater(plugin, DeathbanListener.RESPAWN_KICK_DELAY_TICKS).getTaskId());
}
 
Example 34
Project: OnlineChecker-Spigot-SQL-Support   File: SQLManager.java   Source Code and License 6 votes vote down vote up
public SQLManager() {
	new BukkitRunnable() {

		@Override
		public void run() {
			if (loadList.size() <= 0) {
				return;
			}
			Iterator<String> iter = loadList.iterator();
			while (iter.hasNext()) {
				try {
					Player p = Bukkit.getPlayer(UUID.fromString(iter.next()));
					if (p == null || !p.isOnline()) {
						iter.remove(); 
						continue;
					}
				} catch (Exception e) {
					iter.remove();
					continue;
				}
			}

		}
	}.runTaskTimer(Core.getInstance(), 0, 10);
}
 
Example 35
Project: RPGInventory   File: InventoryListener.java   Source Code and License 6 votes vote down vote up
private void onItemDisappeared(PlayerEvent event, ItemStack item) {
    final Player player = event.getPlayer();
    final PlayerInventory inventory = player.getInventory();
    final int slotId = inventory.getHeldItemSlot();

    if (!InventoryManager.playerIsLoaded(player)) {
        return;
    }

    if (ItemUtils.isEmpty(inventory.getItemInMainHand()) || item.equals(inventory.getItemInMainHand())) {
        final Slot slot = InventoryManager.getQuickSlot(slotId);
        if (slot != null) {
            new BukkitRunnable() {
                @Override
                public void run() {
                    InventoryUtils.heldFreeSlot(player, slotId, InventoryUtils.SearchType.NEXT);
                    inventory.setItem(slotId, slot.getCup());
                }
            }.runTaskLater(RPGInventory.getInstance(), 1);
        }
    }
}
 
Example 36
Project: HCFCore   File: EnderPearlTimer.java   Source Code and License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onInventoryClick(InventoryClickEvent event) {
    HumanEntity humanEntity = event.getWhoClicked();
    if (humanEntity instanceof Player) {
        Player player = (Player) humanEntity;
        PearlNameFaker pearlNameFaker = itemNameFakes.get(player.getUniqueId());
        if (pearlNameFaker == null)
            return;

        // Required to prevent ghost items.
        int heldSlot = player.getInventory().getHeldItemSlot();
        if (event.getSlot() == heldSlot) {
            pearlNameFaker.setFakeItem(CraftItemStack.asNMSCopy(player.getItemInHand()), heldSlot);
        } else if (event.getHotbarButton() == heldSlot) {
            pearlNameFaker.setFakeItem(CraftItemStack.asNMSCopy(event.getCurrentItem()), event.getSlot());
            new BukkitRunnable() {
                @Override
                public void run() {
                    player.updateInventory();
                }
            }.runTask(plugin);
        }
    }
}
 
Example 37
Project: mczone   File: MySQL.java   Source Code and License 6 votes vote down vote up
public boolean update(final String query) {
	new BukkitRunnable() {
		@Override
		public void run() {
			Statement statement = null;
			try {
				statement = connection.createStatement();
				statement.executeUpdate(query);
			} catch (SQLException e) {
				Chat.log("MySQL update failed: " + query);
				e.printStackTrace();
			}
		}
	}.runTaskAsynchronously(MCZone.getInstance());
	return true;
}
 
Example 38
Project: mczone   File: Map.java   Source Code and License 6 votes vote down vote up
public void loadWorld() {
	new BukkitRunnable() {
		@Override
		public void run() {
			Bukkit.createWorld(new WorldCreator(getWorldName()));
			getWorld().setTime(6000 - (20 * 20));
			for (Location l : getSpawns())
				l.setWorld(getWorld());
			getSpecSpawn().setWorld(getWorld());
			
   			for (Gamer g : Game.getTributes()) {
   				g.clearVariable("parkour");
   				g.setVariable("moveable", true);
   				Location next = getNextSpawn(g.getPlayer());
   				g.setVariable("spawn-block", next);
   				
   				g.teleport(next);
   				g.setInvisible(false);
   				g.setVariable("moveable", false);
   				g.getPlayer().setHealth(20);
   				g.clearInventory();
   				g.clearScoreboard();
   			}
		}
	}.runTask(SurvivalGames.getInstance());
}
 
Example 39
Project: BedwarsXP   File: ActionBarUtils.java   Source Code and License 5 votes vote down vote up
public static void sendActionBar(final Player player, final String message,
		int duration) {
	sendActionBar(player, message);

	if (duration >= 0) {
		// Sends empty message at the end of the duration. Allows messages
		// shorter than 3 seconds, ensures precision.
		new BukkitRunnable() {
			@Override
			public void run() {
				sendActionBar(player, "");
			}
		}.runTaskLater(plugin, duration + 1);
	}

	// Re-sends the messages every 3 seconds so it doesn't go away from the
	// player's screen.
	while (duration > 60) {
		duration -= 60;
		int sched = duration % 60;
		new BukkitRunnable() {
			@Override
			public void run() {
				sendActionBar(player, message);
			}
		}.runTaskLater(plugin, (long) sched);
	}
}
 
Example 40
Project: AsgardAscension   File: RuneManager.java   Source Code and License 5 votes vote down vote up
private void handleInvisibility(Player player, Rune rune) {
	for(Player p : Bukkit.getOnlinePlayers()) {
		p.hidePlayer(player);
	}
	new BukkitRunnable() {
		public void run() {
			if(player != null && player.isOnline()) {
				finish(player, true);
			}
		}
	}.runTaskLater(plugin, 100L);
}
 
Example 41
Project: uppercore   File: TestBoardPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public void onEnable() {
    instance = this;

    // When the plugin enables, we save the millis
    startedAt = System.currentTimeMillis();

    // Scoreboard initialization
    myTestBoard = new TestBoard();

    // Opens the board to current online players
    for (Player player : Bukkit.getOnlinePlayers()) {
        BoardView viewForPlayer = myTestBoard.create(player);
        views.add(viewForPlayer);
    }

    Bukkit.getPluginManager().registerEvents(this, this);

    // Each second we want to update the timer contained in the board
    new BukkitRunnable() {
        @Override
        public void run() {
            for (BoardView view : views) {
                view.update();
            }
        }
    }.runTaskTimer(this, 0, 20);
}
 
Example 42
Project: RPGPlus   File: Effects.java   Source Code and License 5 votes vote down vote up
public static void heartBeam(PlayerInteractEvent event) {
final Player player = event.getPlayer();
List<String> combo = Datafiles.getCombos(event.getPlayer().getName());
	new BukkitRunnable() {
		double t = 0;
		Location loc = player.getLocation();
		Vector direction = loc.getDirection().normalize();
		public void run() {
			t = t + 0.5;
			double x = direction.getX() * t;
			double y = direction.getY() * t + 1.5;
			double z = direction.getZ() * t;
			loc.add(x, y, z);
			ParticleEffect.HEART.display(0, 0, 0, 4, 5, loc, 30);
			
			for(Entity e: loc.getChunk().getEntities()){
				if(e.getLocation().distance(loc) < 1.0){
					if(!e.equals(player)){
						if(e instanceof Player){
							Player p = (Player) e;
							p.setHealth(p.getHealth()-10);
					}
				}
			}
			}
			loc.subtract(x, y, z);
			if(t == 0.5){
				ActionBarAPI.sendActionBar(player, "§c§lHEAL SPELL §7§lACTIVATED");	
				}
			if (t > 30) {
				this.cancel();
				Location loc1 = new Location(player.getWorld(), x, y, z);
				Bukkit.getWorld(player.getWorld().getName()).createExplosion(loc1, 4.0F);
			}
		}
	}.runTaskTimer(Main.getInstance(), 0, 1);

}
 
Example 43
Project: RPGPlus   File: Effects.java   Source Code and License 5 votes vote down vote up
public static void waterBarrier(PlayerInteractEvent event){
	final Player player = (Player) event.getPlayer();
	final Location loc = (Location) player.getLocation();
	new BukkitRunnable() {
		double phi = 0;
		@Override
		public void run() {
			phi += (Math.PI/10);
			for(double theta = 0; theta <= 2*Math.PI; theta += Math.PI/40){
				double r = 1.5;
				double x = r*Math.cos(theta)*Math.sin(phi);
				double y = r* Math.cos(phi) + 1.5;
				double z = r*Math.sin(theta)*Math.sin(phi);
				loc.add(x,y,z);
				ParticleEffect.DRIP_WATER.display(0, 0, 0, 3, 3, loc, 40);
				loc.subtract(x,y,z);
				if(theta == 0){
					ActionBarAPI.sendActionBar(player, "§c§lWATER BARRIER SPELL §7§lACTIVATED");	

				}
			}
			if(phi > Math.PI){
				this.cancel();
			}
			
		}
	}.runTaskTimer(Main.getInstance(), 0, 1);
}
 
Example 44
Project: RPGPlus   File: Effects.java   Source Code and License 5 votes vote down vote up
public static void fireBarrier(PlayerInteractEvent event){
	final Player player = (Player) event.getPlayer();
	final Location loc = (Location) player.getLocation();
	new BukkitRunnable() {
		double phi = 0;
		@Override
		public void run() {
			phi += (Math.PI/10);
			for(double theta = 0; theta <= 2*Math.PI; theta += Math.PI/40){
				double r = 1.5;
				double x = r*Math.cos(theta)*Math.sin(phi);
				double y = r* Math.cos(phi) + 1.5;
				double z = r*Math.sin(theta)*Math.sin(phi);
				loc.add(x,y,z);
				ParticleEffect.FLAME.display(0, 0, 0, 3, 3, loc, 40);
				loc.subtract(x,y,z);
				if(theta == 0){
					ActionBarAPI.sendActionBar(player, Main.colorThis("&c&lFire BARRIER SPELL &7&lACTIVATED"));	

				}
			}
			if(phi > 4*Math.PI){
				this.cancel();
			}
			
		}
	}.runTaskTimer(Main.getInstance(), 0, 1);
}
 
Example 45
Project: Warzone   File: InfectedTimeLimit.java   Source Code and License 5 votes vote down vote up
public void startCountdown(int length) {

        new BukkitRunnable() {
            @Override
            public void run() {
                if (match.getMatchStatus().equals(MatchStatus.MID) && teamManager.getTeamById("humans").getMembers().size() != 0) {
                    TGM.get().getMatchManager().endMatch(teamManager.getTeamById("humans"));
                }
            }
        }.runTaskLater(TGM.get(), length * 60 * 20);
    }
 
Example 46
Project: TruenoNPC   File: TinyProtocol.java   Source Code and License 5 votes vote down vote up
/**
 * Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future clients.
 * <p>
 * You can construct multiple instances per plugin.
 *
 * @param plugin - the plugin.
 */
public TinyProtocol(final Plugin plugin) {
    this.plugin = plugin;

    // Compute handler name
    this.handlerName = getHandlerName();

    // Prepare existing players
    registerBukkitEvents();

    try {
        registerChannelHandler();
        registerPlayers(plugin);
    } catch (IllegalArgumentException ex) {
        // Damn you, late bind
        plugin.getLogger().info("[TinyProtocol] Delaying server channel injection due to late bind.");

        new BukkitRunnable() {
            @Override
            public void run() {
                registerChannelHandler();
                registerPlayers(plugin);
                plugin.getLogger().info("[TinyProtocol] Late bind injection successful.");
            }
        }.runTask(plugin);
    }
}
 
Example 47
Project: Arcadia-Spigot   File: PotionDropGame.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onPotionUse(PlayerItemConsumeEvent event) {
    if(event.getItem().getType() == Material.POTION) {
        new BukkitRunnable() {
            public void run() {
                if(event.getPlayer().isOnline()) {
                    event.getPlayer().getInventory().remove(Material.GLASS_BOTTLE);
                }
            }
        }.runTaskLater(this.getAPI().getPlugin(), 3L);
    }
}
 
Example 48
Project: EchoPet   File: PetOwnerListener.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
    final Player p = event.getPlayer();
    new BukkitRunnable() {

        @Override
        public void run() {
IPet pet = EchoPet.getManager().getPet(p);
if(pet != null) pet.spawnPet(p, false);
        }

    }.runTaskLater(EchoPet.getPlugin(), 20L);
}
 
Example 49
Project: VoxelGamesLibv2   File: LoggedScheduler.java   Source Code and License 5 votes vote down vote up
@Override
public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task, long delay) {
    TaskedRunnable wrapped = new TaskedRunnable(task);

    wrapped.setTaskID(delegate.scheduleSyncDelayedTask(plugin, wrapped, delay));
    return wrapped.getTaskID();
}
 
Example 50
Project: mczone   File: Pets.java   Source Code and License 5 votes vote down vote up
public void startFollowTask() {
 	new BukkitRunnable() {
@Override
public void run() {
             for (final Player p : Bukkit.getOnlinePlayers()) {
                 if (isPetOwner(p)) {
                 	for (PetInstance pet : PetInstance.getList()) {
                 		if (pet.getOwner().equalsIgnoreCase(p.getName()) == false)
                 			continue;
                 		
                 		if (pet.isSpawned()) {
                 			final Entity e = pet.getEntity();
                 			if (e == null)
                 				continue;
                 			
                 			if (e.isDead()) {
                 				pet.spawn();
                 				return;
                 			}
                 			double distance = p.getLocation().distance(e.getLocation());
                 			if (distance > 3.0) {
                   		Control.walkToPlayer(e, p);
                 			}
                 		}
                 	}
                 }
             }
}
 	}.runTaskTimerAsynchronously(this, 0, 20);
 }
 
Example 51
Project: AsgardAscension   File: GodTokensInventoryListener.java   Source Code and License 5 votes vote down vote up
private void handleGTWithdrawal(Player player) {
	player.closeInventory();
	player.sendMessage(Lang.HEADERS_TOKENS.toString() + "Type amount of GT to withdraw");
	SetupListener.withdrawal.put(player.getName(), true);
	new BukkitRunnable() {
		public void run() {
			if(SetupListener.withdrawal.containsKey(player.getName())) {
				SetupListener.withdrawal.remove(player.getName());
				player.sendMessage(Lang.HEADERS_TOKENS.toString() + "You didn't withdrawn any GT in time!");
			}
		}
	}.runTaskLater(plugin, 200L);
}
 
Example 52
Project: VoxelGamesLibv2   File: LoggedScheduler.java   Source Code and License 5 votes vote down vote up
@Override
public BukkitTask runTaskLater(Plugin plugin, BukkitRunnable bukkitRunnable, long l)
        throws IllegalArgumentException {
    TaskedRunnable wrapped = new TaskedRunnable(bukkitRunnable);

    BukkitTask bukkitTask = delegate.runTaskLater(plugin, wrapped, l);
    wrapped.setTaskID(bukkitTask.getTaskId());
    return bukkitTask;
}
 
Example 53
Project: Capatchafy   File: Listeners.java   Source Code and License 5 votes vote down vote up
public void setThrottleSettings()
{
    this.throttleTime = startupThrottleTime;
    this.throttleLogins = startupThrottleLogins;
    new BukkitRunnable() 
    {
        @Override
        public void run() 
        {
            throttleTime = defaultThrottleTime;
            throttleLogins = defaultThrottleLogins;
        }           
    }.runTaskLater(Capatchafy.plugin, 1200);
}
 
Example 54
Project: ChatAssets   File: Cooldowner.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) {
	Player player = event.getPlayer();
	long timecount = 20 * config.getInt("cooldowner.secs-before-next-message");
	String cooldownerror = ChatColor.YELLOW + "You need to wait for " + Long.toString(timecount / 20) + " seconds between sending two messages.";
	boolean enablation = config.getBoolean("enable.cooldowner");
	List<Player> cooldownplayer = new ArrayList<Player>();

	if (enablation) {
		if (cooldownplayer.contains(player)) {
			if (!(player.hasPermission("chatassets.cooldowner.bypass"))) {
				event.setCancelled(true);
				Main.sendMessage(cooldownerror, player);
			} else {
				cooldownplayer.remove(player);
			}
		} else {
			if (!(player.hasPermission("chatassets.cooldowner.bypass"))) {
				cooldownplayer.add(player);
				new BukkitRunnable() {

					@Override
					public void run() {
						cooldownplayer.remove(player);
					}
				}.runTaskLater(plugin, timecount);
			}
		}
	}
}
 
Example 55
Project: Chambers   File: GameManager.java   Source Code and License 5 votes vote down vote up
/**
 * Stops the Game
 */
public void stop(Team winner) {
	game.setWinner(winner);
	game.setStatus(GameStatus.OVER);
	game.setTotalTime(0);
	clearAllMobs();
	Bukkit.getOnlinePlayers().stream().forEach(player -> {
		Bukkit.getOnlinePlayers().stream().forEach(other -> {
			player.showPlayer(other);
			other.showPlayer(player);
		});
		player.setGameMode(GameMode.CREATIVE);
		player.getInventory().clear();
		player.updateInventory();
		player.getInventory().setArmorContents(null);
		player.setHealth(20.0);
		player.setFoodLevel(20);
		player.setFireTicks(0);
		player.setGameMode(GameMode.SURVIVAL);
		player.setExp(0.0F);
		player.setAllowFlight(true);
		player.setFlying(true);
		player.getActivePotionEffects().stream().forEach(effect -> player.removePotionEffect(effect.getType()));
	});
	Bukkit.getScheduler().scheduleSyncRepeatingTask(Chambers.getInstance(), new BukkitRunnable() {
		int time = 15;
		@Override
		public void run() {
			if (time == -2) {
				Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "restart");
			} else if (time == 0) {
				Bukkit.getOnlinePlayers().stream().forEach(player -> player.kickPlayer("Thanks for playing Chambers beta, join back soon!"));
			} else if (time % 2 == 0) {
				Bukkit.broadcastMessage(ChatColor.YELLOW + (winner == null ? "The game was forcefully stopped." : "The team " + winner.getFormattedName() + ChatColor.YELLOW + "has won the game!"));
			}
			time--;
		}
	}, 0, 20L);
}
 
Example 56
Project: AutoUpdaterAPI   File: Updater.java   Source Code and License 5 votes vote down vote up
private void sendActionBar(Player player, String message) {
    new BukkitRunnable() {
        @Override
        public void run() {
            if (player != null) {
                player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.translateAlternateColorCodes('&', message)));
            }
            if (AutoUpdaterAPI.getInstance().isDebug()) {
                AutoUpdaterAPI.getInstance().getLogger().info(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', message)));
            }

        }
    }.runTask(AutoUpdaterAPI.getInstance());
}
 
Example 57
Project: VoxelGamesLibv2   File: VoteFeature.java   Source Code and License 5 votes vote down vote up
public void giveVoteMenuItem(@Nonnull User user) {
    new BukkitRunnable() {

        @Override
        public void run() {
            if (!getPhase().isRunning()) return;
            user.getPlayer().getInventory().setItem(0, openMenuItem);
            user.getPlayer().updateInventory();
        }
    }.runTaskLater(voxelGamesLib, 5); // delay because we might be in progress of switching worlds
}
 
Example 58
Project: AsgardAscension   File: AbilityManager.java   Source Code and License 5 votes vote down vote up
/**
 * Starts timer To add potion effect abilities
 * @param player The player
 */
public void startTimer(Player player) {
	new BukkitRunnable() {
		public void run() {
			handleTimedEffects(player, player.getInventory().getItemInMainHand());
			handleTimedEffects(player, player.getInventory().getHelmet());
			handleTimedEffects(player, player.getInventory().getChestplate());
			handleTimedEffects(player, player.getInventory().getLeggings());
			handleTimedEffects(player, player.getInventory().getBoots());
		}
	}.runTaskTimer(plugin, 0L, 40L);
}
 
Example 59
Project: KingdomFactions   File: Leap.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(KingdomFactionsPlayer player) {

	noFallDamage.add(player.getName());

	double forwardPowerModifier = 1.5D;
	double upwardPowerModifier = forwardPowerModifier * 2.0D;
	double fwv = 2.0D;
	double uwv = 0.7D;

	Vector dir = player.getLocation().getDirection();

	dir.setY(0).normalize().multiply(fwv * forwardPowerModifier).setY(uwv * upwardPowerModifier);

	player.getPlayer().setVelocity(dir);

	final World w = player.getPlayer().getWorld();
	w.playSound(player.getLocation(), Sound.ENTITY_ENDERMEN_TELEPORT, 1.0F, 1.0F);

	new BukkitRunnable() {
		int autoStopCount = 0;

		@SuppressWarnings("deprecation")
		public void run() {
			if ((this.autoStopCount <= 30) && (Leap.noFallDamage.contains(player.getName()))
					&& (Bukkit.getPlayer(player.getName()) != null)
					&& (!Bukkit.getPlayer(player.getName()).isOnGround())) {
				Player p = Bukkit.getPlayer((player.getName()));
				w.playEffect(p.getLocation(), Effect.ENDER_SIGNAL, 1);

				this.autoStopCount += 1;
			} else {
				if ((Leap.noFallDamage.contains(player.getName()))) {
					Leap.noFallDamage.remove(player.getName());
				}
				cancel();
			}
		}
	}.runTaskTimer(KingdomFactionsPlugin.getInstance(), 5L, 3L);
}
 
Example 60
Project: MystiCraft   File: ArrowStormSpell.java   Source Code and License 5 votes vote down vote up
@Override
public void cast(Caster caster) {
	new BukkitRunnable() {
		int current = 0;
		public void run() {
			caster.getPlayer().launchProjectile(Arrow.class).setPickupStatus(PickupStatus.DISALLOWED);
			current++;
			if (current == count)
				this.cancel();
		}
	}.runTaskTimer(MystiCraft.getInstance(), 1, 1);
}