dongya9904 2015-03-31 20:37
浏览 39
已采纳

我的PHP数组问题

This will be a pretty strange question, but bear with me.

I'm coding a browser based game, and each player has an amount of guards, each with 100 health. Every time they are shot, the guards lose health. If all the guards are dead, the player takes the health instead.

The shot damage always overlaps as well, so if player has 3 guards, and the top guard has 60 health, a shot of 100 will kill guard 3 and leave guard 2 with 60 health.

i use a php array to sort this, and it works, except when it comes down to the players health. It doesn't calculate correctly, eg all a players guards are dead and the player has 60 health left. He is shot for 100, but instead of dying the health loops round so he has some other number health instead of -40.

$p_bg = array(); // players guard count
$p_bg[0] = $rs[bgs_hp2]; // only the top guard hp is saved (bgs_hp2)
$p_hp = $rs[hp2]; // players health
$dmg = 80 // shot damage

$x = 0;
while($x < $rs[BGs2]) { $p_bg[$x] = 100; $x++; } 

// As long as there's still damage to take and bgs to take it:
while($dmg && !empty($p_bg)) {
   $soak = min($p_bg[0], $dmg); // not more than the first bg can take
   $p_bg[0] -= $soak; // remove hps from the first bg
   $dmg -= $soak; // deduct from the amount of damage to tage

   if ($p_bg[0] == 0) {
      // bodyguard dead, remove him from the array
      array_shift($p_bg);
      }
   }

// If there's any damage left over, it goes to hp
$p_hp = $p_hp - $dmg;
  • 写回答

1条回答 默认 最新

  • dqnk57224 2015-03-31 21:07
    关注

    Without knowing the contents of $rs or knowing what the constants bgs_hp2, hp2, and BGs2 are, it's hard to say, but it seems like the problem lies around this combination of lines:

    $p_bg = array(); // Create an empty array
    $p_bg[0] = $rs[bgs_hp2]; // Populate the first index, possibly null?
    $x = 0;
    while($x < $rs[BGs2]) { $p_bg[$x] = 100; $x++; }
    

    I'd suspect BGs2 is the bodyguard count for the player? It seems that you're setting the top bodyguard's health to 100 each time this code is hit. Maybe it would be more clear if it was rearranged as follows:

    $p_bg = array($rs[bgs_hp2]);
    for ($x = 0; $x < $rs[BGs2]; $x++) { $p_bg[] = 100; }
    

    Other than that, log out your variables (using print_r($var) or var_dump($var) as necessary) to see the actual data you're executing on. Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c