Minecraft selectors (@A, @p, @r, @e, @s) added to pocketmine.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClosestPlayer.php 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. declare(strict_types=1);
  3. namespace Ad5001\PlayerSelectors\selector;
  4. use pocketmine\command\CommandSender;
  5. use pocketmine\Server;
  6. use pocketmine\Player;
  7. class ClosestPlayer extends Selector{
  8. public function __construct(){
  9. parent::__construct("Closest player", "p", false);
  10. }
  11. /**
  12. * Executes the selector.
  13. * Documentation is in the Selector.php file.
  14. *
  15. * @param CommandSender $sender
  16. * @param array $parameters
  17. * @return array
  18. */
  19. public function applySelector(CommandSender $sender, array $parameters = []): array{
  20. $online = Server::getInstance()->getOnlinePlayers();
  21. // Console
  22. if(!($sender instanceof Player)) {
  23. if(count($online) > 0){
  24. return [$online[array_keys($online)[0]]->getName()];
  25. } else {
  26. return [$sender->getName()];
  27. }
  28. }
  29. // Player
  30. if(count($online) > 1){
  31. // Checking the closest player
  32. foreach($online as $p){
  33. if($p->getLevel()->getName() == $sender->getLevel()->getName() &&
  34. (!isset($selectedP) || $p->distanceSquared($sender) < $selectorP->distanceSquared($sender))){
  35. $selectedP = $p;
  36. }
  37. }
  38. return [$selectorP->getName()];
  39. } else {
  40. // Otherwise, just return sender's name because there's no other player.
  41. return [$sender->getName()];
  42. }
  43. }
  44. }