private void onMouseMove(Player player, int dx, int dy, int x, int y) {
    // Mouse hasn't moved
    if (dx == 0 && dy == 0) {
      return;
    }

    Screen screen = getInputScreen();
    if (screen != null) {
      IntVector2 prev = new IntVector2(x - dx, y - dy);
      IntVector2 pos = new IntVector2(x, y);
      for (Widget w : screen.getWidgets()) {
        w.onMouseMoved(prev, pos, w == screen.getWidgetAt(x, y));
      }
    }

    // Mouse moved on x-axis
    if (!redirected) {
      if (dx != 0) {
        player.processCommand("dx", new ChatArguments(dx));
      }

      // Mouse moved on y-axis
      if (dy != 0) {
        player.processCommand("dy", new ChatArguments(dy));
      }
    }
  }
 public void updatePlayerTimers() {
   if (this.weather.getCurrent() == Weather.THUNDERSTORM) {
     if (getIntensity() == null) {
       setIntensity(Intensity.getRandomIntensity(ra, false));
     }
     List<Player> toStrike = new ArrayList<Player>();
     for (Player player : getWorld().getPlayers()) {
       if (!player.isOnline()) {
         continue;
       }
       Integer ticksLeft = playerCountdown.get(player);
       if (ticksLeft == null) {
         playerCountdown.put(player, getTicksBeforeNextLightning(ra));
       } else if (ticksLeft == 1) {
         // weed out dc'd players
         if (player.isOnline()) {
           toStrike.add(player);
           playerCountdown.put(player, getTicksBeforeNextLightning(ra));
         }
       } else {
         playerCountdown.put(player, ticksLeft - 1);
       }
     }
     strikePlayers(toStrike);
   } else {
     setIntensity(null);
   }
 }
Beispiel #3
0
  @Override
  public void handleServer(ServerSession session, PlayerChatMessage message) {
    if (!session.hasPlayer()) {
      return;
    }

    Player player = session.getPlayer();
    String text = message.getMessage().trim();
    if (text.length() > 100) {
      text = text.substring(0, 99);
    }

    String command;
    String[] args;

    if (text.startsWith("/")) {
      command = text.split(" ")[0].replaceFirst("/", "");
      int argsIndex = text.indexOf(" ") + 1;
      args = argsIndex > 0 ? text.substring(argsIndex).split(" ") : new String[0];
    } else {
      command = "say";
      args = text.split(" ");
    }

    player.processCommand(command, args);
  }
 @Command(
     aliases = {"biome"},
     usage = "",
     desc = "Print out the name of the biome at the current location",
     min = 0,
     max = 0)
 @CommandPermissions("vanilla.command.biome")
 public void getBiomeName(CommandContext args, CommandSource source) throws CommandException {
   if (!(source instanceof Player)) {
     throw new CommandException("Only a player may call this command.");
   }
   Player player = (Player) source;
   if (!(player.getTransform().getPosition().getWorld().getGenerator()
       instanceof BiomeGenerator)) {
     throw new CommandException("This map does not appear to have any biome data.");
   }
   Point pos = player.getTransform().getPosition();
   Biome biome = pos.getWorld().getBiome(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ());
   source.sendMessage(
       plugin.getPrefix(),
       ChatStyle.BRIGHT_GREEN,
       "Current biome: ",
       ChatStyle.WHITE,
       (biome != null ? biome.getName() : "none"));
 }
 @Command(aliases = "clear", usage = "[player]", desc = "Clears your inventory", min = 0, max = 1)
 @CommandPermissions("vanilla.command.clear")
 public void clear(CommandContext args, CommandSource source) throws CommandException {
   if (args.length() == 0) {
     if (!(source instanceof Player)) {
       throw new CommandException("You must be a player to clear your own inventory.");
     }
     PlayerInventory inv = ((Player) source).get(PlayerInventory.class);
     if (inv == null) {
       source.sendMessage(plugin.getPrefix(), ChatStyle.RED, "You have no inventory!");
       return;
     }
     inv.clear();
   }
   if (args.length() == 1) {
     Player player = args.getPlayer(0, false);
     if (player == null) {
       source.sendMessage(plugin.getPrefix(), ChatStyle.RED, "Player is not online!");
       return;
     }
     PlayerInventory inv = player.get(PlayerInventory.class);
     if (inv == null) {
       source.sendMessage(plugin.getPrefix(), ChatStyle.RED, "Player has no inventory!");
       return;
     }
     player.sendMessage(
         plugin.getPrefix(), ChatStyle.BRIGHT_GREEN, "Your inventory has been cleared.");
     if (source instanceof Player && source.equals(player)) {
       return;
     }
   }
   source.sendMessage(plugin.getPrefix(), ChatStyle.BRIGHT_GREEN, "Inventory cleared.");
 }
  @Command(
      aliases = {"gamemode", "gm"},
      usage =
          "[player] <0|1|2|survival|creative|adventure> (0 = SURVIVAL, 1 = CREATIVE, 2 = ADVENTURE)",
      desc = "Change a player's game mode",
      min = 1,
      max = 2)
  @CommandPermissions("vanilla.command.gamemode")
  public void gamemode(CommandContext args, CommandSource source) throws CommandException {
    int index = 0;
    Player player;
    if (args.length() == 2) {
      if (Spout.getEngine() instanceof Client) {
        throw new CommandException("You cannot search for players unless you are in server mode.");
      }
      player = Spout.getEngine().getPlayer(args.getString(index++), true);
      if (player == null) {
        throw new CommandException(args.getString(0) + " is not online.");
      }
    } else {
      if (!(source instanceof Player)) {
        throw new CommandException("You must be a player to toggle your game mode.");
      }

      player = (Player) source;
    }

    if (!player.has(Human.class)) {
      throw new CommandException("Invalid player!");
    }

    GameMode mode;

    try {
      if (args.isInteger(index)) {
        mode = GameMode.get(args.getInteger(index));
      } else {
        mode = GameMode.get(args.getString(index));
      }
    } catch (Exception e) {
      throw new CommandException(
          "A game mode must be either a number between 0 and 2, 'CREATIVE', 'SURVIVAL' or 'ADVENTURE'");
    }

    player.get(Human.class).setGamemode(mode);

    if (!player.equals(source)) {
      source.sendMessage(
          plugin.getPrefix(),
          ChatStyle.WHITE,
          player.getName(),
          "'s ",
          ChatStyle.BRIGHT_GREEN,
          "gamemode has been changed to ",
          ChatStyle.WHITE,
          mode.name(),
          ChatStyle.BRIGHT_GREEN,
          ".");
    }
  }
  @EventHandler(order = Order.LATEST)
  public void entityDeath(EntityDeathEvent event) {
    Entity entity = event.getEntity();
    Engine engine = Spout.getEngine();

    // kill count criteria
    Object lastDamager = event.getLastDamager();
    if (lastDamager instanceof Player) {
      Player killer = (Player) lastDamager;
      String killerName = killer.getName();
      String[] criteria = {
        Objective.CRITERIA_TOTAL_KILL_COUNT, Objective.CRITERIA_PLAYER_KILL_COUNT
      };
      if (entity instanceof Player) {
        // killed a player? update total and player kill count
        evaluateCriteria(killerName, 1, true, criteria);
      } else {
        // just an entity? only update total kill count
        evaluateCriteria(killerName, 1, true, criteria[0]);
      }
    }

    if (!(entity instanceof Player) || !(engine instanceof Server)) {
      return;
    }

    // player death criteria
    Player player = (Player) entity;
    evaluateCriteria(player.getName(), 1, true, Objective.CRITERIA_DEATH_COUNT);
  }
 private void evaluateCriteria(String key, int value, boolean add, String... criteria) {
   for (Player player : ((Server) Spout.getEngine()).getOnlinePlayers()) {
     Scoreboard scoreboard = player.get(Scoreboard.class);
     if (scoreboard != null) {
       scoreboard.evaluateCriteria(key, value, add, criteria);
     }
   }
 }
Beispiel #9
0
  /** Update the player UI bar. */
  private void updateUi() {

    if (!(getOwner() instanceof Player)) {
      return;
    }
    Player p = (Player) getOwner();
    p.getSession()
        .send(false, new PlayerExperienceMessage(getProgress(), getLevel(), getExperience()));
  }
  @Command(
      aliases = "xp",
      usage = "[player] <amount>",
      desc = "Give/take experience from a player",
      min = 1,
      max = 2)
  @CommandPermissions("vanilla.command.xp")
  public void xp(CommandContext args, CommandSource source) throws CommandException {
    // If source is player
    if (args.length() == 1) {
      if (source instanceof Player) {
        @SuppressWarnings("unused")
        Player sender = (Player) source;
        int amount = args.getInteger(0);
        source.sendMessage(
            plugin.getPrefix(),
            ChatStyle.BRIGHT_GREEN,
            "You have been given ",
            ChatStyle.WHITE,
            amount,
            ChatStyle.BRIGHT_GREEN,
            " xp.");
        // TODO: Give player 'amount' of xp.
      } else {
        throw new CommandException("You must be a player to give yourself xp.");
      }
    } else {
      if (Spout.getEngine() instanceof Client) {
        throw new CommandException("You cannot search for players unless you are in server mode.");
      }
      Player player = ((Server) Spout.getEngine()).getPlayer(args.getString(0), true);
      if (player != null) {
        short amount = (short) args.getInteger(1);
        LevelComponent level = player.get(LevelComponent.class);

        if (level == null) {
          return;
        }

        if (amount > 0) {
          level.addExperience(amount);
        } else {
          level.removeExperience(amount);
        }
        player.sendMessage(
            plugin.getPrefix(),
            ChatStyle.BRIGHT_GREEN,
            "Your experience has been set to ",
            ChatStyle.WHITE,
            amount,
            ChatStyle.BRIGHT_GREEN,
            ".");
      } else {
        throw new CommandException(args.getString(0) + " is not online.");
      }
    }
  }
Beispiel #11
0
  public void strikePlayers(List<Player> toStrike) {
    for (Player player : toStrike) {
      Point playerPos = player.getScene().getPosition();
      final int posX = GenericMath.floor(playerPos.getX());
      final int posY = GenericMath.floor(playerPos.getY());
      final int posZ = GenericMath.floor(playerPos.getZ());
      for (int tries = 0; tries < 10; tries++) {
        // pick a random chunk between -4, -4, to 4, 4 relative to the player's position to strike
        // at
        int cx = (ra.nextBoolean() ? -1 : 1) * ra.nextInt(5);
        int cz = (ra.nextBoolean() ? -1 : 1) * ra.nextInt(5);

        // pick random coords to try to strike at inside the chunk (0, 0) to (15, 15)
        int rx = ra.nextInt(16);
        int rz = ra.nextInt(16);

        // pick a offset from the player's y position to strike at (-15 - +15) of their position
        int offsetY = (ra.nextBoolean() ? -1 : 1) * ra.nextInt(15);

        int x = posX + cx * 16 + rx;
        int y = posY + offsetY;
        int z = posZ + cz * 16 + rz;

        if (weather.isRainingAt(x, y, z, false)) {
          int lightning = 1;
          // 30% chance of extra lightning at the spot
          if (ra.nextInt(10) < 3) {
            lightning += ra.nextInt(MAX_LIGHTNING_BRANCHES);
          }
          for (int strikes = 0; strikes < lightning; strikes++) {
            float adjustX = 0.5F;
            float adjustY = 0.0F;
            float adjustZ = 0.5F;
            // if there are extra strikes, tweak their placement slightly
            if (strikes > 0) {
              adjustX += (ra.nextBoolean() ? -1 : 1) * ra.nextInt(2);
              adjustY += (ra.nextBoolean() ? -1 : 1) * ra.nextInt(8);
              adjustZ += (ra.nextBoolean() ? -1 : 1) * ra.nextInt(2);
            }
            World world = getWorld();
            Point point = new Point(world, x + adjustX, y + adjustY, z + adjustZ);
            world.createAndSpawnEntity(point, Lightning.class, LoadOption.NO_LOAD);
            for (Player p : GeneralEffects.LIGHTNING_THUNDER.getNearbyPlayers(point, null, 600)) {
              double dist = p.getScene().getPosition().distanceSquared(point);
              float volume = (float) (10000F - Math.pow(dist, 0.73));
              if (volume > 0) {
                GeneralEffects.LIGHTNING_THUNDER.adjust(volume, 0.7F).play(p, point);
              }
            }
          }
          // success, go to the next player
          break;
        }
      }
    }
  }
 @Override
 public BlockIterator getAlignedBlocks() {
   Player player = (Player) getOwner();
   Transform ptr = player.get(PlayerHead.class).getHeadTransform();
   Transform tr = new Transform();
   tr.setRotation(
       QuaternionMath.rotationTo(Vector3.FORWARD, ptr.getRotation().getDirection().multiply(-1)));
   tr.setPosition(ptr.getPosition());
   return new BlockIterator(player.getWorld(), tr, getRange());
 }
Beispiel #13
0
 public void play(Player player, Point position, float volume, float pitch) {
   // TODO Fix this, these should NEVER BE NULL
   if (player == null
       || player.getSession() == null | player.getSession().getNetworkSynchronizer() == null) {
     return;
   }
   player
       .getSession()
       .getNetworkSynchronizer()
       .callProtocolEvent(new PlaySoundEffectEvent(position, this, volume, pitch));
 }
  @Override
  public void handleClient(Session session, EntityVelocityMessage message) {
    if (!session.hasPlayer()) {
      return;
    }

    Player player = session.getPlayer();
    World world = player.getWorld();
    Entity entity = world.getEntity(message.getEntityId());

    System.out.println(message.toString());
  }
 @Override
 public void onInteract(final EntityInteractEvent<?> event) {
   if (event instanceof PlayerInteractEntityEvent) {
     final PlayerInteractEntityEvent pie = (PlayerInteractEntityEvent) event;
     final Player player = (Player) pie.getEntity();
     switch (pie.getAction()) {
       case RIGHT_CLICK:
         // TODO: Make player enter Minecart here
         System.out.println("MINECART ENTER: " + player.getName());
     }
   }
 }
Beispiel #16
0
 @Override
 public boolean open(Player player) {
   BrewingStandOpenEvent event =
       player.getEngine().getEventManager().callEvent(new BrewingStandOpenEvent(this, player));
   if (!event.isCancelled()) {
     player
         .get(WindowHolder.class)
         .openWindow(new BrewingStandWindow(player, this, getInventory()));
     return true;
   }
   return false;
 }
Beispiel #17
0
 @Override
 public void updateWeather(Weather oldWeather, Weather newWeather) {
   WeatherChangeEvent event =
       Spout.getEventManager().callEvent(new WeatherChangeEvent(this, oldWeather, newWeather));
   if (event.isCancelled()) {
     return;
   }
   this.getWorld().getDataMap().put(VanillaData.WEATHER, newWeather);
   for (Player player : this.getWorld().getPlayers()) {
     player.getNetworkSynchronizer().callProtocolEvent(event);
   }
 }
  @EventHandler(order = Order.LATEST)
  public void entityHealth(EntityHealthChangeEvent event) {
    Entity entity = event.getEntity();
    Engine engine = Spout.getEngine();
    if (!(entity instanceof Player) || !(engine instanceof Server)) {
      return;
    }

    Player player = (Player) entity;
    evaluateCriteria(
        player.getName(),
        (int) (player.get(Health.class).getHealth() + event.getChange()),
        false,
        Objective.CRITERIA_HEALTH);
  }
  @Override
  protected void worldChanged(World world) {
    GameMode gamemode = world.getComponentHolder().getData().get(VanillaData.GAMEMODE);
    // The world the player is entering has a different gamemode...
    if (gamemode != null) {
      if (gamemode != getPlayer().getData().get(VanillaData.GAMEMODE)) {
        PlayerGameModeChangedEvent event =
            Spout.getEngine()
                .getEventManager()
                .callEvent(new PlayerGameModeChangedEvent(player, gamemode));
        if (!event.isCancelled()) {
          gamemode = event.getMode();
        }
      }
    } else {
      // The world has no gamemode setting in its map so default to the Player's GameMode.
      gamemode = getPlayer().getData().get(VanillaData.GAMEMODE);
    }
    Difficulty difficulty = world.getComponentHolder().getData().get(VanillaData.DIFFICULTY);
    Dimension dimension = world.getComponentHolder().getData().get(VanillaData.DIMENSION);
    WorldType worldType = world.getComponentHolder().getData().get(VanillaData.WORLD_TYPE);

    // TODO Handle infinite height
    if (first) {
      first = false;
      int entityId = player.getId();
      Server server = (Server) session.getEngine();
      PlayerLoginRequestMessage idMsg =
          new PlayerLoginRequestMessage(
              entityId,
              worldType.toString(),
              gamemode.getId(),
              (byte) dimension.getId(),
              difficulty.getId(),
              (byte) server.getMaxPlayers());
      player.getSession().send(false, true, idMsg);
      player.getSession().setState(State.GAME);
      for (int slot = 0; slot < 4; slot++) {
        ItemStack slotItem = owner.get(Human.class).getInventory().getArmor().get(slot);
        player.getSession().send(false, new EntityEquipmentMessage(entityId, slot, slotItem));
      }
    } else {
      player
          .getSession()
          .send(
              false,
              new PlayerRespawnMessage(
                  dimension.getId(),
                  difficulty.getId(),
                  gamemode.getId(),
                  256,
                  worldType.toString()));
    }

    Point pos = world.getSpawnPoint().getPosition();
    PlayerSpawnPositionMessage SPMsg =
        new PlayerSpawnPositionMessage((int) pos.getX(), (int) pos.getY(), (int) pos.getZ());
    player.getSession().send(false, SPMsg);
  }
Beispiel #20
0
 @Override
 public boolean close(Player player) {
   BrewingStandCloseEvent event =
       player.getEngine().getEventManager().callEvent(new BrewingStandCloseEvent(this, player));
   if (!event.isCancelled()) {
     return super.close(player);
   }
   return false;
 }
Beispiel #21
0
 @Override
 public void play(Player player, Point position, int note) {
   Block block = position.getWorld().getBlock(position);
   player
       .getSession()
       .getNetworkSynchronizer()
       .callProtocolEvent(
           new BlockActionEvent(block, VanillaMaterials.NOTEBLOCK, (byte) 0, (byte) note));
 }
  @Override
  public void handleServer(Session session, HeldItemChangeMessage message) {
    if (!session.hasPlayer()) {
      return;
    }

    Player player = session.getPlayer();

    int newSlot = message.getSlot();
    if (newSlot < 0 || newSlot > 8) {
      return;
    }

    ((VanillaPlayerController) player.getController())
        .getInventory()
        .getQuickbar()
        .setCurrentSlot(newSlot);
  }
 private void executeBindings(Set<Binding> bindings, Player player, boolean pressed) {
   ChatArguments args = new ChatArguments(pressed ? "+" : "-");
   // Queue up sync bindings first
   for (Binding binding : bindings) {
     if (!binding.isAsync()) {
       player
           .getEngine()
           .getScheduler()
           .scheduleSyncDelayedTask(null, new BindingTask(player, binding.getCommand(), args));
     }
   }
   // Execute async bindings
   for (Binding binding : bindings) {
     if (binding.isAsync()) {
       player.processCommand(binding.getCommand(), args);
     }
   }
 }
Beispiel #24
0
 private void updateProgressArrow(Player player) {
   float increment = 0;
   if (getBrewTime() >= 0) {
     increment = (BREW_TIME_INCREMENT - getBrewTime()) * 20;
   }
   player
       .get(WindowHolder.class)
       .getActiveWindow()
       .setProperty(BrewingStandProperty.PROGRESS_ARROW, (int) increment);
 }
Beispiel #25
0
 // TODO Make method faster and better. [quick fix]
 @SuppressWarnings("static-access")
 @EventHandler
 public void onChat(PlayerChatEvent e) {
   Player p = e.getPlayer();
   String Nickname = plugin.PDC().getNode(p.getName() + ".GeneralData.prefix").getString();
   e.NAME.equals(Nickname);
   e.setFormat(
       new ChatArguments(
           "[",
           plugin.PharseStringColors(
               plugin.PDC().getNode(p.getName() + ".GeneralData.prefix").getString()),
           ChatStyle.BRIGHT_GREEN,
           e.NAME,
           ChatStyle.WHITE,
           "]",
           ChatStyle.YELLOW,
           ": ",
           ChatStyle.WHITE,
           e.MESSAGE));
 }
Beispiel #26
0
  /**
   * Updates the time as a celestial sky system
   *
   * @param time to use
   * @param timeFactor unknown factor, use 1.0f
   */
  public void updateCelestialTime(long time, float timeFactor) {
    float celestial = MathHelper.getRealCelestialAngle(time, timeFactor);
    WeatherSimulator weather = this.getWeatherSimulator();
    if (weather != null) {
      celestial =
          (float)
              ((double) celestial
                  * (1.0d - (double) (weather.getRainStrength(timeFactor) * 5f) / 16d));
      celestial =
          (float)
              ((double) celestial
                  * (1.0d - (double) (weather.getThunderStrength(timeFactor) * 5f) / 16d));
    }
    this.getWorld().setSkyLight((byte) (celestial * (float) SKY_LIGHT_RANGE + MIN_SKY_LIGHT));

    TimeUpdateEvent event = new TimeUpdateEvent(getWorld(), time);
    for (Player player : getWorld().getPlayers()) {
      player.getNetworkSynchronizer().callProtocolEvent(event);
    }
  }
    @Command(
        aliases = {"create", "make", "mk"},
        desc = "Creates a new waypoint",
        min = 1,
        max = 1)
    @Permissible("plugintest.waypoint.create")
    public void create(CommandSource source, CommandArguments args) throws CommandException {
      if (!(source instanceof Player)) {
        throw new CommandException("Only players may create waypoints.");
      }

      String name = args.getString(0);
      Player player = (Player) source;

      if (this.waypoints.containsKey(name)) {
        throw new CommandException("The \"" + name + "\" waypoint already exists.");
      }

      this.waypoints.put(name, player.getScene().getPosition());
      player.sendMessage("Waypoint \"" + name + "\" has been created.");
    }
  @Command(
      aliases = {"op"},
      usage = "<player>",
      desc = "Make a player an operator",
      min = 1,
      max = 1)
  @CommandPermissions("vanilla.command.op")
  public void op(CommandContext args, CommandSource source) throws CommandException {
    if (Spout.getEngine() instanceof Client) {
      throw new CommandException("You cannot search for players unless you are in server mode.");
    }

    String playerName = args.getString(0);
    OpConfiguration ops = VanillaConfiguration.OPS;
    ops.setOp(playerName, true);
    source.sendMessage(plugin.getPrefix(), ChatStyle.RED, playerName, " is now an operator!");
    Player player = Spout.getEngine().getPlayer(playerName, true);
    if (player != null && !source.equals(player)) {
      player.sendMessage(plugin.getPrefix(), ChatStyle.YELLOW, "You are now an operator!");
    }
  }
    @Command(
        aliases = {"teleportto", "tpto"},
        desc = "Teleports the player to the waypoint",
        min = 1,
        max = 1)
    @Permissible("plugintest.waypoint.tpto")
    public void tpto(CommandSource source, CommandArguments args) throws CommandException {
      if (!(source instanceof Player)) {
        throw new CommandException("Only players may teleport to waypoints, silly.");
      }

      String name = args.getString(0);
      Player player = (Player) source;
      Point destination = this.waypoints.get(name);

      if (destination == null) {
        throw new CommandException("The \"" + name + "\" waypoint does not exist.");
      }

      player.teleport(destination);
      player.sendMessage("Teleported to waypoint.");
    }
 @Command(
     aliases = {"kill"},
     usage = "[player]",
     desc = "Kill yourself or another player",
     min = 0,
     max = 1)
 @CommandPermissions("vanilla.command.kill")
 public void kill(CommandContext args, CommandSource source) throws CommandException {
   if (args.length() == 0) {
     if (!(source instanceof Player)) {
       throw new CommandException("Don't be silly...you cannot kill yourself as the console.");
     }
     ((Player) source).get(HealthComponent.class).kill(HealthChangeCause.COMMAND);
   } else {
     if (Spout.getEngine() instanceof Client) {
       throw new CommandException("You cannot search for players unless you are in server mode.");
     }
     Player victim = ((Server) Spout.getEngine()).getPlayer(args.getString(0), true);
     if (victim != null) {
       victim.get(HealthComponent.class).kill(HealthChangeCause.COMMAND);
     }
   }
 }