我想按字母顺序排列所有在线玩家的名字。然后从中随机抽取 1 位玩家
您可以使用
Bukkit.getOnlinePlayers()
获取所有在线玩家。
然后您可以使用
sort()
函数对它们进行排序,然后使用 Random
类从列表中获取休闲玩家。
示例:
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
public class YourPluginClass {
public void selectRandomPlayer() {
// Step 1: Get the online players
Player[] onlinePlayers = Bukkit.getOnlinePlayers().toArray(new Player[0]);
// Step 2: Alphabetize the player names
Arrays.sort(onlinePlayers, Comparator.comparing(Player::getName));
// Step 3: Select a random player
if (onlinePlayers.length > 0) {
Random random = new Random();
int randomIndex = random.nextInt(onlinePlayers.length);
Player randomPlayer = onlinePlayers[randomIndex];
} else {
// No players online
}
}
}