Ejemplo n.º 1
0
  @Listener
  public void onServerStarting(GameStartingServerEvent event) {
    GlobalCommands globalCommands = new GlobalCommands(this);
    CommandSpec map =
        CommandSpec.builder()
            .description(Text.of("All commands related to the chunk protection"))
            .executor(globalCommands::map)
            .build();

    CommandSpec claim =
        CommandSpec.builder()
            .description(Text.of("Claims the chunk that you are standing"))
            .executor(globalCommands::claim)
            .build();

    CommandSpec chunk =
        CommandSpec.builder()
            .description(Text.of("Commands related to chunk protection"))
            .child(map, "map")
            .child(claim, "claim")
            .build();

    CommandSpec mychunk =
        CommandSpec.builder()
            .description(Text.of("All mychunk commands"))
            .child(chunk, "chunk", "c")
            .build();

    Sponge.getCommandManager().register(this, chunk, "chunk");
    Sponge.getCommandManager().register(this, mychunk, "mychunk");
  }
Ejemplo n.º 2
0
  @Listener
  public void onPlayerRespawn(RespawnPlayerEvent event) {
    Player player = event.getTargetEntity();

    if (this.teamA.contains(player)) {
      event.setToTransform(
          event.getToTransform().setLocation(this.arena.getTeamASpawn().getLocation()));

      Sponge.getScheduler()
          .createTaskBuilder()
          .execute(
              () -> {
                if (this.arena.getTeamALoadout() != null)
                  UltimateGames.game
                      .getCommandManager()
                      .process(
                          Sponge.getServer().getConsole(),
                          "kit " + this.arena.getTeamALoadout() + " " + player.getName());
              })
          .delayTicks(10)
          .name("UltimateGames - Give Player Loadout")
          .submit(
              UltimateGames.game
                  .getPluginManager()
                  .getPlugin("io.github.hsyyid.ultimategames")
                  .get()
                  .getInstance()
                  .get());
    } else if (this.teamB.contains(player)) {
      event.setToTransform(
          event.getToTransform().setLocation(this.arena.getTeamBSpawn().getLocation()));

      Sponge.getScheduler()
          .createTaskBuilder()
          .execute(
              () -> {
                if (this.arena.getTeamBLoadout() != null)
                  UltimateGames.game
                      .getCommandManager()
                      .process(
                          Sponge.getServer().getConsole(),
                          "kit " + this.arena.getTeamBLoadout() + " " + player.getName());
              })
          .delayTicks(10)
          .name("UltimateGames - Give Player Loadout")
          .submit(
              UltimateGames.game
                  .getPluginManager()
                  .getPlugin("io.github.hsyyid.ultimategames")
                  .get()
                  .getInstance()
                  .get());
    }
  }
Ejemplo n.º 3
0
  @Override
  public CommandResult executeCommand(final CommandSource src, CommandContext args)
      throws Exception {
    if (service == null) {
      service = Sponge.getServiceManager().provideUnchecked(NucleusWarpService.class);
    }

    PaginationService ps = Sponge.getServiceManager().provideUnchecked(PaginationService.class);

    // Get the warp list.
    Set<String> ws = service.getWarpNames();
    if (ws.isEmpty()) {
      src.sendMessage(Util.getTextMessageWithFormat("command.warps.list.nowarps"));
      return CommandResult.empty();
    }

    List<Text> lt =
        ws.stream()
            .filter(s -> canView(src, s.toLowerCase()))
            .map(
                s -> {
                  if (service.getWarp(s).isPresent()) {
                    return Text.builder(s)
                        .color(TextColors.GREEN)
                        .style(TextStyles.UNDERLINE)
                        .onClick(TextActions.runCommand("/warp " + s))
                        .onHover(
                            TextActions.showText(
                                Util.getTextMessageWithFormat("command.warps.warpprompt", s)))
                        .build();
                  } else {
                    return Text.builder(s)
                        .color(TextColors.RED)
                        .onHover(
                            TextActions.showText(
                                Util.getTextMessageWithFormat("command.warps.unavailable")))
                        .build();
                  }
                })
            .collect(Collectors.toList());

    PaginationList.Builder pb =
        ps.builder()
            .title(Util.getTextMessageWithFormat("command.warps.list.header"))
            .padding(Text.of(TextColors.GREEN, "-"))
            .contents(lt);
    if (!(src instanceof Player)) {
      pb.linesPerPage(-1);
    }

    pb.sendTo(src);
    return CommandResult.success();
  }
Ejemplo n.º 4
0
  private Optional<Player> validPlayer(Cause cause) {
    Optional<EntityDamageSource> optionalSrc = cause.first(EntityDamageSource.class);

    if (optionalSrc.isPresent()) {
      Entity src = optionalSrc.get().getSource();

      if (src instanceof Player) {
        return Optional.of((Player) src);
      } else if (src instanceof Projectile) {
        Projectile projectile = (Projectile) src;

        Optional<UUID> optionalUUID = projectile.getCreator();

        if (!optionalUUID.isPresent()) {
          return Optional.empty();
        }

        Optional<Player> optionalPlayer = Sponge.getServer().getPlayer(optionalUUID.get());

        if (!optionalPlayer.isPresent()) {
          return Optional.empty();
        }

        return Optional.of(optionalPlayer.get());
      }
    }

    return Optional.empty();
  }
  @Inject(
      method = "onUpdate",
      at =
          @At(
              value = "INVOKE",
              target = "Lnet/minecraft/entity/effect/EntityLightningBolt;setDead()V"))
  public void onSetDead(CallbackInfo ci) {
    if (this.isDead) {
      return;
    }
    World world = (World) this.worldObj;
    LightningEvent.Strike strike =
        SpongeEventFactory.createLightningEventStrike(
            this.cause, this.struckEntities, this.struckEntitySnapshots, world, this.struckBlocks);
    Sponge.getEventManager().post(strike);

    if (!strike.isCancelled()) {
      for (Transaction<BlockSnapshot> bt : strike.getTransactions()) {
        if (bt.isValid()) {
          BlockSnapshot bs = bt.getFinal();
          world.setBlock(bs.getPosition(), bs.getState());
        }
      }
      for (Entity e : strike.getEntities()) {
        ((net.minecraft.entity.Entity) e).onStruckByLightning((EntityLightningBolt) (Object) this);
      }
      SpongeImpl.postEvent(SpongeEventFactory.createLightningEventPost(this.cause));
    }
  }
Ejemplo n.º 6
0
 public void init() {
   SqlService sql =
       Sponge.getServiceManager()
           .provide(SqlService.class)
           .orElseThrow(() -> new IllegalStateException("NoSQL?"));
   String jdbcUrl = Planetesimals.getInstance().getJDBCUrl();
   String[] dbParts = jdbcUrl.split(":");
   if (dbParts.length < 2 || !dbParts[1].equals("h2")) {
     throw new IllegalStateException("Not H2. Dunno what to do.");
   }
   try {
     this.data = sql.getDataSource(jdbcUrl);
   } catch (SQLException e) {
     throw new IllegalStateException("Couldn't load DB", e);
   }
   this.db = using(this.data, SQLDialect.H2);
   if (getDB()
       .meta()
       .getTables()
       .stream()
       .noneMatch(t -> t.getName().equalsIgnoreCase(PLANETS_TABLE.getName()))) {
     getDB()
         .createTable(PLANETS_TABLE)
         .column(CHUNK_X_FIELD, getDataType(Integer.class))
         .column(CHUNK_Y_FIELD, getDataType(Integer.class))
         .column(CHUNK_Z_FIELD, getDataType(Integer.class))
         .column(PLANET_X_FIELD, getDataType(Integer.class))
         .column(PLANET_Y_FIELD, getDataType(Integer.class))
         .column(PLANET_Z_FIELD, getDataType(Integer.class))
         .column(PLANET_RADIUS_FIELD, getDataType(Integer.class))
         .execute();
   }
 }
Ejemplo n.º 7
0
 @Override
 public Optional<Text> getValue(@Nullable Object player) {
   if (player == null) return Optional.empty();
   if (player instanceof Player) {
     Player p = (Player) player;
     if (Sponge.getServiceManager().provide(EconomyService.class).isPresent()) {
       EconomyService es = Sponge.getServiceManager().provide(EconomyService.class).get();
       if (es.getOrCreateAccount(p.getUniqueId()).isPresent()) {
         BigDecimal balance =
             es.getOrCreateAccount(p.getUniqueId()).get().getBalance(es.getDefaultCurrency());
         return Optional.of(Text.of(balance.toString()));
       }
     }
     return Optional.empty();
   }
   return Optional.empty();
 }
Ejemplo n.º 8
0
 public void cancel() {
   cancelled = true;
   tasks
       .values()
       .forEach(
           task -> {
             Sponge.getEventManager().unregisterListeners(task);
           });
 }
Ejemplo n.º 9
0
 final boolean unregister() {
   if (this.registered) {
     this.registered = false;
     Sponge.getEventManager().unregisterListeners(this);
     return true;
   } else {
     return false;
   }
 }
Ejemplo n.º 10
0
  @Listener(order = Order.POST)
  public void onAffectSlotEvent(AffectSlotEvent event, @Root Player player) {
    for (SlotTransaction transaction : event.getTransactions()) {
      ItemStack itemStack = transaction.getFinal().createStack();

      BigDecimal amount = WalletDrop.getValue(itemStack);

      if (amount.compareTo(BigDecimal.ZERO) == 0) {
        continue;
      }

      WorldSettings settings = WorldSettings.get(player.getWorld());

      if (player.gameMode().get().equals(GameModes.CREATIVE) && !settings.isCreativeModeAllowed()) {
        event.setCancelled(true);
        return;
      }

      if (settings.isUsePermissions()) {
        if (!player.hasPermission("walletdrop.enable")) {
          return;
        }
      }

      WalletPickupEvent moneyPickupEvent =
          new WalletPickupEvent(itemStack, amount, Cause.of(NamedCause.source(player)));

      if (!Sponge.getEventManager().post(moneyPickupEvent)) {
        Sponge.getScheduler()
            .createTaskBuilder()
            .delayTicks(2)
            .execute(
                c -> {
                  player.getInventory().query(itemStack).clear();
                })
            .submit(Main.getPlugin());

        WalletDrop.depositOrWithdraw(player, moneyPickupEvent.getAmount());

        WalletDrop.sendPickupMessage(player, amount);
      }
    }
  }
Ejemplo n.º 11
0
 @Override
 public Optional<Text> getBanReason(GameProfile profile) {
   checkNotNull(profile, "Game profile cannot be null!");
   BanService service = Sponge.getServiceManager().provide(BanService.class).get();
   Optional<Ban.Profile> optionalBan = service.getBanFor(profile);
   if (optionalBan.isPresent()) {
     return optionalBan.get().getReason();
   }
   return Optional.empty();
 }
Ejemplo n.º 12
0
 final boolean register(Class<S> event) {
   if (this.registered) {
     return false;
   } else {
     this.registered = true;
     Sponge.getEventManager()
         .registerListener(
             Pore.getPlugin(), event, EventPriorityConverter.of(this.priority), this);
     return true;
   }
 }
Ejemplo n.º 13
0
 @Listener
 public void onWorldLoad(LoadWorldEvent event) {
   World world = event.getTargetWorld();
   logger.info("World loaded: " + world.getName());
   UUID uniqueId = world.getUniqueId();
   claimedChunks.put(uniqueId, new HashMap<>());
   try {
     worldContexts.put(uniqueId, loadWorldContext(world));
   } catch (IOException e) {
     logger.error("Failed to load world data");
     Sponge.getServer().shutdown();
   }
 }
Ejemplo n.º 14
0
 public CreatingJob(UUID uuid) {
   this.uuid = uuid;
   // Add tasks
   addTasks(
       new NameTask(this),
       new MaxLevelTask(this),
       new ColorTask(this),
       new BlockDataTask(this),
       new BreakTask(this),
       new PlaceTask(this),
       new KillTask(this),
       new SilkTouchTask(this),
       new WorldGenTask(this),
       new FinalTask(this));
   // Send cancel message
   for (Player player : Sponge.getServer().getOnlinePlayers()) {
     if (player.getUniqueId().equals(uuid))
       player.sendMessage(messages.getMessage("creation.cancel"));
   }
   // Register listener
   Sponge.getEventManager().registerListeners(JobsLite.getInstance(), this);
   // Start task
   nextTask();
 }
Ejemplo n.º 15
0
 public void submitInventory(Class owner, boolean openInventory) {
   this.owner = owner;
   em.registerListener(owner, this);
   if (openInventory) {
     for (UUID user : users) {
       Optional<Player> player = Sponge.getServer().getPlayer(user);
       if (player.isPresent()) {
         this.container =
             player
                 .get()
                 .openInventory(this.inventory, Cause.of(NamedCause.source(player)))
                 .orElse(null);
         // TODO check if not opened
       }
     }
   }
 }
Ejemplo n.º 16
0
  @Listener
  public void onSpawnEntityEvent(SpawnEntityEvent event, @Root SpawnCause cause) {
    WorldSettings settings = WorldSettings.get(event.getTargetWorld());

    if (!settings.isVanillaSpawnerAllowed() && cause.getType().equals(SpawnTypes.MOB_SPAWNER)) {
      return;
    } else if (!settings.isModSpawnerAllowed() && cause.getType().equals(SpawnTypes.CUSTOM)) {
      return;
    } else if (!settings.isPluginSpawnerAllowed() && cause.getType().equals(SpawnTypes.PLUGIN)) {
      return;
    } else if (!settings.isEggSpawnerAllowed() && cause.getType().equals(SpawnTypes.SPAWN_EGG)) {
      return;
    }

    for (Entity entity : event.getEntities()) {
      entity.offer(Sponge.getDataManager().getManipulatorBuilder(MoneyData.class).get().create());
    }
  }
Ejemplo n.º 17
0
  @Listener
  public void onChunkLoad(LoadChunkEvent event) {
    Chunk chunk = event.getTargetChunk();
    UUID worldId = chunk.getWorld().getUniqueId();
    Vector3i position = chunk.getPosition();

    WorldFallbackContext context = worldContexts.get(worldId);
    if (context == null) {
      IllegalStateException exception =
          new IllegalStateException(
              "Failed to find the world context for the world " + chunk.getWorld().getName());
      logger.error(
          "An error happened while loading the chunk " + chunk.getWorld().getName() + position,
          exception);
      Sponge.getServer().shutdown();
      throw exception;
    }

    try {
      dataStorage
          .loadChunk(worldId, position)
          .ifPresent(
              claimedChunk -> {
                logger.info("Chunk loaded: " + chunk.getWorld().getName() + position);
                getChunkMap(worldId)
                    .orElseThrow(IllegalStateException::new)
                    .put(position, claimedChunk);
              });
    } catch (DataStorageException e) {
      logger.error(
          "Failed to load chunk information on " + chunk.getWorld().getName() + position, e);
      getChunkMap(worldId)
          .orElseThrow(IllegalStateException::new)
          .put(position, new ClaimedChunk(context, position));
    }
  }
 @Override
 protected Optional<FireworkEffect> buildContent(DataView container) throws InvalidDataException {
   if (container.contains(
       DataQueries.FIREWORK_SHAPE,
       DataQueries.FIREWORK_COLORS,
       DataQueries.FIREWORK_FADE_COLORS,
       DataQueries.FIREWORK_FLICKERS,
       DataQueries.FIREWORK_TRAILS)) {
     final String fireworkShapeId =
         DataUtil.getData(container, DataQueries.FIREWORK_SHAPE, String.class);
     final Optional<FireworkShape> shapeOptional =
         Sponge.getRegistry().getType(FireworkShape.class, fireworkShapeId);
     if (!shapeOptional.isPresent()) {
       throw new InvalidDataException(
           "Could not find the FireworkShape for the provided id: " + fireworkShapeId);
     }
     final FireworkShape shape = shapeOptional.get();
     final boolean trails =
         DataUtil.getData(container, DataQueries.FIREWORK_TRAILS, Boolean.class);
     final boolean flickers =
         DataUtil.getData(container, DataQueries.FIREWORK_FLICKERS, Boolean.class);
     final List<Color> colors =
         container.getSerializableList(DataQueries.FIREWORK_COLORS, Color.class).get();
     final List<Color> fadeColors =
         container.getSerializableList(DataQueries.FIREWORK_FADE_COLORS, Color.class).get();
     return Optional.of(
         FireworkEffect.builder()
             .colors(colors)
             .flicker(flickers)
             .fades(fadeColors)
             .trail(trails)
             .shape(shape)
             .build());
   }
   return Optional.empty();
 }
Ejemplo n.º 19
0
 @Override
 public Set<Context> getActiveContexts() {
   time().onGetActiveContexts().startTimingIfSync();
   try {
     int ticks;
     ActiveContextsHolder holder, newHolder;
     do {
       ticks = Sponge.getGame().getServer().getRunningTimeTicks();
       holder = this.cachedContexts.get();
       if (holder != null && ticks == holder.getUpdateTicks()) {
         return holder.getContexts();
       }
       Set<Context> set = new HashSet<>();
       for (ContextCalculator<Subject> calc :
           this.collection.getPlugin().getContextCalculators()) {
         calc.accumulateContexts(this, set);
       }
       newHolder = new ActiveContextsHolder(ticks, ImmutableSet.copyOf(set));
     } while (!this.cachedContexts.compareAndSet(holder, newHolder));
     return newHolder.getContexts();
   } finally {
     time().onGetActiveContexts().stopTimingIfSync();
   }
 }
 public static void init() {
   channel =
       Sponge.getChannelRegistrar().createRawChannel(SpongeWorldEdit.inst(), CUI_PLUGIN_CHANNEL);
   channel.addListener(Platform.Type.SERVER, new CUIChannelHandler());
 }
Ejemplo n.º 21
0
  @Listener(order = Order.PRE)
  public void onDestructEntityEventDeathPlayer(
      DestructEntityEvent.Death event, @First EntityDamageSource damageSrc) {
    if (!(event.getTargetEntity() instanceof Player)) {
      return;
    }
    Player player = (Player) event.getTargetEntity();

    WorldSettings settings = WorldSettings.get(player.getWorld());

    DeathReason reason = DeathReason.GENERIC;

    Entity src = damageSrc.getSource();

    if (src instanceof Player) {
      reason = DeathReason.PLAYER;
    } else if (src instanceof Projectile) {
      Projectile projectile = (Projectile) src;

      Optional<UUID> optionalUUID = projectile.getCreator();

      if (!optionalUUID.isPresent()) {
        return;
      }

      Optional<Player> optionalPlayer = Sponge.getServer().getPlayer(optionalUUID.get());

      if (optionalPlayer.isPresent()) {
        reason = DeathReason.PLAYER;
      } else {
        reason = DeathReason.PROJECTILE;
      }
    } else {
      DamageType cause = damageSrc.getType();
      reason = DeathReason.valueOf(cause.getName().toUpperCase());
    }

    Optional<EconomyService> optionalEconomy =
        Sponge.getServiceManager().provide(EconomyService.class);

    if (!optionalEconomy.isPresent()) {
      Main.instance().getLog().error("Economy plugin not found");
      return;
    }
    EconomyService economy = optionalEconomy.get();

    BigDecimal balance =
        economy
            .getOrCreateAccount(player.getUniqueId())
            .get()
            .getBalance(WorldSettings.get(player.getWorld()).getCurrency());

    PlayerWallet wallet = settings.getPlayerWallet();

    BigDecimal amount = wallet.getAmount(reason, balance);

    WalletDropEvent walletDropEvent = new WalletDropEvent(amount, player);

    if (walletDropEvent.getAmount().compareTo(BigDecimal.ZERO) != 0
        && (!Sponge.getEventManager().post(walletDropEvent))) {
      WalletDrop.depositOrWithdraw(
          player, walletDropEvent.getAmount().multiply(BigDecimal.valueOf(-1)));

      if (settings.isDropsEnabled()) {
        for (MoneyStack moneyStack : walletDropEvent.getMoneyStacks()) {
          moneyStack.drop(walletDropEvent.getLocation());
        }
      }

      WalletDrop.sendDeathMessage(
          WorldSettings.get(player.getWorld()), player, walletDropEvent.getAmount());
    }
  }
Ejemplo n.º 22
0
 public void registerListener(EventListener eventListener) {
   Sponge.getGame().getEventManager().registerListeners(TowerOfBabel.instance, eventListener);
 }
Ejemplo n.º 23
0
 /**
  * Get the loaded chunk at the given block coordinate position.
  *
  * @param bx The x coordinate
  * @param by The y coordinate
  * @param bz The z coordinate
  * @return The chunk, if available
  */
 default Optional<Chunk> getChunkAtBlock(int bx, int by, int bz) {
   return getChunk(Sponge.getServer().getChunkLayout().forceToChunk(bx, by, bz));
 }
Ejemplo n.º 24
0
 @Override
 protected MapValue<K, V> getValueGetter() {
   return Sponge.getRegistry()
       .getValueFactory()
       .createMapValue((Key<MapValue<K, V>>) this.usedKey, this.getValue());
 }
Ejemplo n.º 25
0
  /**
   * Creates a new DeathmatchMinigame instance.
   *
   * @param arena the arena to be played.
   * @param teamA the players on team A.
   * @param teamB the players on team B.
   * @throws Exception If the match failed to register.
   */
  public DeathmatchMinigame(UltimateGamesArena arena, List<Player> teamA, List<Player> teamB)
      throws Exception {
    this.teamA = teamA;
    this.teamB = teamB;
    this.arena = arena;

    Objective.Builder objectiveBuilder =
        Sponge.getRegistry().createBuilder(Objective.Builder.class);

    Text title = Text.of(TextColors.AQUA, "UltimateGames");
    final Objective mainObjective =
        objectiveBuilder.name("<Arena>").criterion(Criteria.DUMMY).displayName(title).build();

    Score teamAName =
        mainObjective.getOrCreateScore(Text.of(TextColors.BLUE, TextStyles.BOLD, "Team A"));
    teamAName.setScore(4);

    this.teamAScoreboardTeam =
        Team.builder()
            .name("TeamA")
            .displayName(Text.of("TeamA"))
            .prefix(Text.of(TextColors.BLUE))
            .nameTagVisibility(Visibilities.ALL)
            .canSeeFriendlyInvisibles(true)
            .allowFriendlyFire(false)
            .members(Sets.newHashSet(Text.of(TextColors.BLUE, TextStyles.BOLD, "Team A")))
            .build();

    Score teamAScore = mainObjective.getOrCreateScore(Text.of(TextColors.BLUE, "Kills: "));
    teamAScore.setScore(3);

    Team teamAScoreTeam =
        Team.builder()
            .name("TeamAScore")
            .displayName(Text.of("TeamAScore"))
            .members(Sets.newHashSet(Text.of(TextColors.BLUE, "Kills: ")))
            .build();

    Score teamBName =
        mainObjective.getOrCreateScore(Text.of(TextColors.RED, TextStyles.BOLD, "Team B"));
    teamBName.setScore(2);

    this.teamBScoreboardTeam =
        Team.builder()
            .name("TeamB")
            .displayName(Text.of("TeamB"))
            .prefix(Text.of(TextColors.RED))
            .nameTagVisibility(Visibilities.ALL)
            .canSeeFriendlyInvisibles(true)
            .allowFriendlyFire(false)
            .members(Sets.newHashSet(Text.of(TextColors.RED, TextStyles.BOLD, "Team B")))
            .build();

    Score teamBScore = mainObjective.getOrCreateScore(Text.of(TextColors.RED, "Kills: "));
    teamBScore.setScore(1);

    Team teamBScoreTeam =
        Team.builder()
            .name("TeamBScore")
            .displayName(Text.of("TeamBScore"))
            .members(Sets.newHashSet(Text.of(TextColors.RED, "Kills: ")))
            .build();

    List<Objective> objectives = new ArrayList<Objective>();
    objectives.add(mainObjective);

    scoreboard = Scoreboard.builder().objectives(objectives).build();
    scoreboard.registerTeam(this.teamAScoreboardTeam);
    scoreboard.registerTeam(teamAScoreTeam);
    scoreboard.registerTeam(this.teamBScoreboardTeam);
    scoreboard.registerTeam(teamBScoreTeam);
    scoreboard.updateDisplaySlot(mainObjective, DisplaySlots.SIDEBAR);

    Scheduler scheduler = Sponge.getScheduler();

    scheduler
        .createTaskBuilder()
        .execute(
            () -> {
              try {
                teamAScoreTeam.setSuffix(Text.of(TextColors.GRAY, teamAPoints));
                teamBScoreTeam.setSuffix(Text.of(TextColors.GRAY, teamBPoints));
              } catch (Exception e) {
                e.printStackTrace();
              }
            })
        .interval(1, TimeUnit.MILLISECONDS)
        .name("UltimateGames - Update scoreboard")
        .submit(
            Sponge.getPluginManager()
                .getPlugin("io.github.hsyyid.ultimategames")
                .get()
                .getInstance()
                .get());

    Ember.register(arena, this);
  }
Ejemplo n.º 26
0
  @Listener
  public void onStart(MinigameStartedEvent event) {
    if (event.getMinigame().equals(this)) {
      for (Player player : players()) {
        player.sendMessage(
            Text.of(
                TextColors.BLUE, "[UltimateGames]: ", TextColors.GREEN, "Deathmatch starting..."));
      }

      for (Player player : this.teamA) {
        player.offer(Keys.GAME_MODE, GameModes.SURVIVAL);
        player.setScoreboard(scoreboard);
        this.teamAScoreboardTeam.addMember(player.getTeamRepresentation());

        if (this.arena.getTeamALoadout() != null)
          UltimateGames.game
              .getCommandManager()
              .process(
                  Sponge.getServer().getConsole(),
                  "kit " + this.arena.getTeamALoadout() + " " + player.getName());

        if (player
            .getWorld()
            .getUniqueId()
            .equals(this.arena.getTeamASpawn().getLocation().getExtent().getUniqueId())) {
          player.setLocation(this.arena.getTeamASpawn().getLocation());
        } else {
          player.transferToWorld(
              this.arena.getTeamASpawn().getLocation().getExtent().getUniqueId(),
              this.arena.getTeamASpawn().getLocation().getPosition());
        }

        player.sendMessage(
            Text.of(TextColors.BLUE, "[UltimateGames]: ", TextColors.GOLD, "May the games begin!"));
      }

      for (Player player : this.teamB) {
        player.offer(Keys.GAME_MODE, GameModes.SURVIVAL);
        player.setScoreboard(scoreboard);
        this.teamBScoreboardTeam.addMember(player.getTeamRepresentation());

        if (this.arena.getTeamBLoadout() != null)
          UltimateGames.game
              .getCommandManager()
              .process(
                  Sponge.getServer().getConsole(),
                  "kit " + this.arena.getTeamBLoadout() + " " + player.getName());

        if (player
            .getWorld()
            .getUniqueId()
            .equals(this.arena.getTeamBSpawn().getLocation().getExtent().getUniqueId())) {
          player.setLocation(this.arena.getTeamBSpawn().getLocation());
        } else {
          player.transferToWorld(
              this.arena.getTeamBSpawn().getLocation().getExtent().getUniqueId(),
              this.arena.getTeamBSpawn().getLocation().getPosition());
        }

        player.sendMessage(
            Text.of(TextColors.BLUE, "[UltimateGames]: ", TextColors.GOLD, "May the games begin!"));
      }

      Scheduler scheduler = UltimateGames.game.getScheduler();
      Task.Builder taskBuilder = scheduler.createTaskBuilder();

      taskBuilder
          .execute(
              () -> {
                try {
                  Ember.unregister(this.arena);
                } catch (Exception e) {
                  System.out.println(
                      "[UltimateGames]: Error when ending deathmatch in arena " + arena.getName());
                }
              })
          .delay(this.arena.getLength(), TimeUnit.MINUTES)
          .name("UltimateGames - End Deathmatch")
          .submit(
              UltimateGames.game
                  .getPluginManager()
                  .getPlugin("io.github.hsyyid.ultimategames")
                  .get()
                  .getInstance()
                  .get());
    }
  }
Ejemplo n.º 27
0
  @Listener
  public void onSendCommandEvent(SendCommandEvent event, @First CommandSource src) {
    String command = event.getCommand();

    if (!command.equalsIgnoreCase("say")) {
      return;
    }

    if (Sponge.getPluginManager().isLoaded("simplechat")) {
      return;
    }

    String message = event.getArguments();

    if (message == null || message.equals("")) {
      return;
    }

    MutableMessageChannel channel = MessageChannel.TO_ALL.asMutable();

    if (message.startsWith("@")) {
      channel = MessageChannel.TO_NONE.asMutable();

      String selector = message.substring(0, message.indexOf(" "));

      for (Entity entity : Selector.parse(selector).resolve(src)) {

        if (entity instanceof Player) {
          channel.addMember((MessageReceiver) entity);
        }
      }

      if (channel.getMembers().size() == 0) {
        src.sendMessage(Text.of(TextColors.RED, "Selector returned no players"));
        return;
      }

      channel.addMember(Sponge.getServer().getConsole());

      message = message.replace(selector, "");
    }

    Text text = TextSerializers.FORMATTING_CODE.deserialize(message);

    if (src instanceof Player) {
      Player player = (Player) src;

      Optional<PlayerTag> optionalPlayerTag = PlayerTag.get(player);

      if (optionalPlayerTag.isPresent()) {
        text = Text.join(optionalPlayerTag.get().getTag(), Text.of(" "), text);
      } else {
        text = Text.join(PlayerTag.getDefault(player), Text.of(" "), text);
      }
    } else {
      Optional<SingleTag> optionalTag = SingleTag.get("simpletags", "console");

      if (optionalTag.isPresent()) {
        text = Text.join(optionalTag.get().getTag(), Text.of(" "), text);
      }
    }

    channel.send(text);

    event.setCancelled(true);
  }
 static Builder builder() {
   return Sponge.getRegistry().createBuilder(Builder.class);
 }
Ejemplo n.º 29
0
  @Listener
  public void onGameInit(GameInitializationEvent event) {
    ConfigurationOptions options = ConfigurationOptions.defaults().setShouldCopyDefaults(true);
    try {
      HoconConfigurationLoader defaultConfigLoader =
          HoconConfigurationLoader.builder()
              .setPath(configDir.resolve("default-permissions.conf"))
              .build();

      CommentedConfigurationNode defaultPermissions = defaultConfigLoader.load(options);

      CommentedConfigurationNode fallback = defaultPermissions.getNode("fallback");
      fallback.setComment(
          "Defines the fallback values for permission flags that are not defined on any context of a protected terrain.");

      CommentedConfigurationNode wild = defaultPermissions.getNode("default-world-permissions");
      wild.setComment(
          "The default permissions for new worlds/dimensions that affects unclaimed chunks");

      loadWorldConfig(null, wild, true);
      loadWorldConfig(null, fallback, false);

      try {
        defaultConfigLoader.save(defaultPermissions);
      } catch (IOException e) {
        logger.error("Failed to save the default-permissions.config file", e);
      }
    } catch (IOException e) {
      logger.error("Failed to load the default-permissions.config file", e);
      Sponge.getServer().shutdown();
    }

    try {
      CommentedConfigurationNode mainConfig = mainConfigLoader.load(options);
      mainConfig.setComment("This configuration defines the fundamental settings from MyChunks");

      CommentedConfigurationNode dataStorageNode = mainConfig.getNode("data-storage");
      CommentedConfigurationNode engineNode = dataStorageNode.getNode("engine");
      engineNode.setComment("The storage engine can only be \"binary\" currently");

      CommentedConfigurationNode binaryNode = dataStorageNode.getNode("binary");
      binaryNode.setComment("Configurations used by the binary engine.");

      CommentedConfigurationNode node = binaryNode.getNode("save-dir");
      node.setComment("The directory where the binary data will be saved. It must be writable");
      String binarySaveDir = node.getString(configDir.resolve("data").resolve("binary").toString());

      String engine = engineNode.getString("binary");
      if ("binary".equalsIgnoreCase(engine.trim()))
        dataStorage = new BinaryDataStorage(Paths.get(binarySaveDir).toFile());
      else
        throw new IllegalArgumentException("The storage engine '" + engine + "' is not supported");

      try {
        mainConfigLoader.save(mainConfig);
      } catch (IOException e) {
        logger.error("Failed to save the main config file", e);
      }

    } catch (Exception e) {
      logger.error("Failed to load the main config file", e);
      Sponge.getServer().shutdown();
    }
  }
Ejemplo n.º 30
0
  @Listener
  public void onServerInit(GameInitializationEvent event) {
    getLogger().info("CommandSigns loading...");

    HashMap<List<String>, CommandSpec> subcommands = new HashMap<List<String>, CommandSpec>();

    subcommands.put(
        Arrays.asList("setcommandsign"),
        CommandSpec.builder()
            .description(Text.of("Creates CommandSigns"))
            .permission("commandsigns.setcommandsign")
            .arguments(
                GenericArguments.seq(
                    GenericArguments.onlyOne(GenericArguments.bool(Text.of("one time"))),
                    GenericArguments.onlyOne(
                        GenericArguments.remainingJoinedStrings(Text.of("command")))))
            .executor(new SetCommandSignExecutor())
            .build());

    subcommands.put(
        Arrays.asList("addcommand"),
        CommandSpec.builder()
            .description(Text.of("Adds Command to CommandSign"))
            .permission("commandsigns.addcommand")
            .arguments(
                GenericArguments.onlyOne(
                    GenericArguments.remainingJoinedStrings(Text.of("command"))))
            .executor(new AddCommandExecutor())
            .build());

    subcommands.put(
        Arrays.asList("removecommand"),
        CommandSpec.builder()
            .description(Text.of("Removes Command on CommandSign"))
            .permission("commandsigns.removecommand")
            .arguments(
                GenericArguments.onlyOne(GenericArguments.integer(Text.of("command number"))))
            .executor(new RemoveCommandExecutor())
            .build());

    subcommands.put(
        Arrays.asList("listcommands"),
        CommandSpec.builder()
            .description(Text.of("List Commands on CommandSign"))
            .permission("commandsigns.listcommands")
            .executor(new ListCommandsExecutor())
            .build());

    CommandSpec commandSignsCommandSpec =
        CommandSpec.builder()
            .description(Text.of("CommandSigns Command"))
            .permission("commandsigns.command")
            .executor(new CommandSignsExecutor())
            .children(subcommands)
            .build();

    Sponge.getCommandManager()
        .register(this, commandSignsCommandSpec, "cs", "commandsign", "commandsigns");

    // One-Time
    Sponge.getDataManager()
        .register(IsOneTimeData.class, ImmutableIsOneTimeData.class, new IsOneTimeDataBuilder());
    Sponge.getDataManager()
        .register(
            SpongeIsOneTimeData.class,
            ImmutableSpongeIsOneTimeData.class,
            new IsOneTimeDataBuilder());

    // IsCommandSign
    Sponge.getDataManager()
        .register(
            IsCommandSignData.class,
            ImmutableIsCommandSignData.class,
            new IsCommandSignDataBuilder());
    Sponge.getDataManager()
        .register(
            SpongeIsCommandSignData.class,
            ImmutableSpongeIsCommandSignData.class,
            new IsCommandSignDataBuilder());

    // Commands
    Sponge.getDataManager()
        .register(CommandsData.class, ImmutableCommandsData.class, new CommandsDataBuilder());
    Sponge.getDataManager()
        .register(
            SpongeCommandsData.class, ImmutableSpongeCommandsData.class, new CommandsDataBuilder());

    // Users
    Sponge.getDataManager()
        .register(UsersData.class, ImmutableUsersData.class, new UsersDataBuilder());
    Sponge.getDataManager()
        .register(SpongeUsersData.class, ImmutableSpongeUsersData.class, new UsersDataBuilder());

    Sponge.getEventManager().registerListeners(this, new HitBlockListener());
    Sponge.getEventManager().registerListeners(this, new InteractBlockListener());

    getLogger().info("-----------------------------");
    getLogger().info("CommandSigns was made by HassanS6000!");
    getLogger().info("Please post all errors on the Sponge Thread or on GitHub!");
    getLogger().info("Have fun, and enjoy! :D");
    getLogger().info("-----------------------------");
    getLogger().info("CommandSigns loaded!");
  }