如何使用java编程算概率_java – 如何编写一个可以轻松维护的概率算法?

假设我想创造一个游戏.在游戏开始时,玩家将挑选一个怪物.

公平地挑选怪物很容易.

// 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();

}

}

如何重构这种概率算法,以便在添加新怪物并调整获胜怪物的机会时可以轻松维护代码?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值