게임을 만들고 싶습니다. 게임 시작시 플레이어는 괴물을 뽑습니다.쉽게 유지 관리 할 수있는 확률 알고리즘을 작성하는 방법은 무엇입니까?
상당히 괴롭히기 쉽습니다.
// 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();
}
}
문제는 내가 게임에 새로운 몬스터를 추가 할 때, 나는 경우 - 다른을 편집해야한다는 것입니다. 또는 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'의 임의 위치에서 문자 선택. 이러한 문자열은 변경하기 쉽습니다. –