在php中执行此操作的最佳方式

时间:2018-04-22 13:28:43

标签: php

我正在开发一款游戏,我想要一个这样的功能,如果我这样做会有100条if语句,有没有更好的方法呢?

$bulletzz = 10000;
$sum = $bulletzz /10;

if($healthh <=1){
$bulletzz = $sum *0.1;
/// reducing the damage the bullets do if they have 1 health etc
}elseif($healthh <=2){
$bulletzz = $sum *0.2;
/// reducing the damage the bullets do if they have 2 health etc
}elseif($healthh <=3){
$bulletzz = $sum *0.3;
/// reducing the damage the bullets do if they have 3 health etc
}elseif($healthh <=4){
$bulletzz = $sum *0.4;
/// reducing the damage the bullets do if they have 4 health etc
}elseif($healthh <=5){
$bulletzz = $sum *0.5;
/// reducing the damage the bullets do if they have 5 health etc
}

1 个答案:

答案 0 :(得分:3)

如果唯一改变的是应用于$sum的乘数,这应该有效:

$sum = $bulletzz / 10;
$bulletzz = $sum * (ceil($healthh) / 10);

这是因为根据您给出的示例,乘数总是比$healthh的向上舍入值小10倍。要将数字舍入到下一个整数,请使用ceil()

此外,根据&#34; 100声明......&#34;短语,我认为$healthh的上限必须在0到100的范围内。如果是这种情况,请先添加一个附加条款,以确保$healthh始终强制在0到100之间:

$healthh = max(0, min($healthh, 100));
$sum = $bulletzz / 10;
$bulletzz = $sum * (ceil($healthh) / 10);