假设我想制作一个游戏。在游戏开始时,玩家将选择一个怪物。
公平地选择怪物是很容易的。
// 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];
}
并且不公平地选择了怪物。
// 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();
}
}
问题在于,当我向游戏中添加一个新怪物时,我必须编辑 if-else。或者,如果我将GoldMonster的获胜几率更改为0.2,那么我必须将所有的0.1更改为0.2。这很丑陋,也不易于维护。
// 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();
}
}
如何重构这个概率算法,以便在添加新怪物和调整赢得怪物的几率时代码可以更容易地维护?
GSSBBBBBBB
的随机位置选择一个字符。这种字符串很容易更改。 - Egor Skriptunoff