Supposto Voglio creare un gioco. All'inizio del gioco, il giocatore sceglierà un mostro.Come scrivere un algoritmo di probabilità che può essere mantenuto facilmente?
È facile scegliere il mostro in modo equo.
// get all monsters with equal chance
public Monster getMonsterFair(){
Monster[] monsters = {new GoldMonster(), new SilverMonster(), new BronzeMonster()};
int winIndex = random.nextInt(monsters.length);
return monsters[winIndex];
}
e prende il mostro ingiustamente.
// get monsters with unequal chance
public Monster getMonsterUnFair(){
double r = Math.random();
// about 10% to win the gold one
if (r < 0.1){
return new GoldMonster();
}
// about 30% to winthe silver one
else if (r < 0.1 + 0.2){
return new SilverMonster();
}
// about 70% to win the bronze one
else {
return new BronzeMonster();
}
}
Il problema è che, quando aggiungo un nuovo mostro al gioco, devo modificare il if-else. Oppure cambio la possibilità di vincere GoldMonster a 0.2, Devo cambiare tutti 0.1 in 0.2 . È brutto e non è facile da gestire.
// get monsters with unequal change & special monster
public Monster getMonsterSpecial(){
double r = Math.random();
// about 10% to win the gold one
if (r < 0.1){
return new GoldMonster();
}
// about 30% to win the silver one
else if (r < 0.1 + 0.2){
return new SilverMonster();
}
// about 50% to win the special one
else if (r < 0.1 + 0.2 + 0.2){
return new SpecialMonster();
}
// about 50% to win the bronze one
else {
return new BronzeMonster();
}
}
Come può questo algoritmo probabilità può essere riscritta in modo che i codici possono essere mantenuti facilmente quando viene aggiunto un nuovo mostro e le probabilità di vincita mostri vengono regolati?
Seleziona il carattere dalla posizione casuale della stringa 'GSSBBBBBBB'. Tale stringa è facile da cambiare. –