增加机会

时间:2015-06-20 13:04:47

标签: java random arraylist

我有6个玩家,每个玩家都有一个名为Karma的玩家。它可以从-1000到1000.如果玩家有0业力,他们的机会是正常的,很可能是1000。这是我目前挑选特殊玩家的方法。

List<String> players = new ArrayList<String>();
for (Player p : getOnlinePlayers() {
    players.add(p.getName());
}
Player p = getPlayer(players.get(new Random().nextInt(players
        .size())));
while (sherrifs.contains(p.getName())) {
    p = Bukkit.getPlayer(players.get(new Random().nextInt(players
            .size())));
}
special = p;

这目前不包括业力,但我想为每个业力增加玩家1次,但如果所有6名玩家都有1000个业力,那将是非常低效的,这意味着,每个名字输入1000次。由于名称必须至少输入一次,因此这不会对-1000业力起作用。如何根据业力增加和减少选择球员的机会?

2 个答案:

答案 0 :(得分:0)

看看here。它应该足够有用。如果你会做Usman Ismali的方法,我会建议你为每个玩家增加1001业力(仅在选择随机玩家时)。否则,选择-980业力的球员是不可能的。例如:

class Player {
    int prob;
}

class RandomPlayer {
    List<Player> players;

    RandomPlayer(List<Player> players) {
        this.players = players;
    }

    public Player getPlayer() {
        int sum = 0;

        for (Player p : players)
            sum += p.prob + 1001;

        int random = new Random().nextInt(sum);

        int i = 0;
        int sum2 = 0;

        while(sum2 < index) 
             sum2 = sum2 + players.get(i++).prob;

        return players.get(Math.max(0,i-1));
    }
}

答案 1 :(得分:0)

创建一个List<Double>,其中包含通过添加相对机会计算的数字。通过找到玩家的间隔或“分享”来完成选择玩家。

// code for creating the list
private List<Player> players = ...;
private List<Double> chances = new ArrayList<>();
private double acc;

public void createChances(){
    acc = 0.0;
    for( Player player: players ){
        acc += (player.getKarma() + 1001)/2000.0;
        chances.add( acc );
    }
}

// code for using the list
private Random random = new Random();

// pick a player
public Player pick(){
    Player picked;
    double rc = random.nextDouble()*acc;
    for( int ic = 0; ic < chances.size(); ++ic ){
        if( rc < chance.get(ic) ){
            picked = players.get(ic);
            break;
        }
    return picked;
}