简体   繁体   English

选择while循环生成的随机数组

[英]Select random array generated from while loop

im learning PHP because i made only designs and templates, and i came to an big problem, at least for me. 我正在学习PHP,因为我只制作了设计和模板,而且我遇到了一个大问题,至少对我而言。 I am making simple "army battle script" where each player has some troops with attack, defense, hp stats, and they battle against each other. 我正在制作一个简单的“军队战斗剧本”,每个玩家都有一些部队有攻击,防御,hp统计,并且他们互相争斗。 Ive made attack player vs player but i am struggling about many entity fight and how to code it. 我已经制造了攻击玩家与玩家,但我正在努力解决许多实体战斗以及如何编码。 First im calling all my units sended to attack, run it trought the loop and get in array every row/unit Then i made that with enemy units, and in the end, i have a simple simulation script that makes the fight. 首先我呼吁所有我的单位被攻击,运行它进行循环并获得阵列每一行/单位然后我用敌人单位做到了,最后,我有一个简单的模拟脚本,使战斗。 But the fight isnt working. 但战斗不起作用。 It doesnt select random unit from the array, it doesnt switch between attacker x defender turns and whats the worse, it only runs with one unit, when that units dies, the script ends and thats it... Can you guys please give me some answer, or way to handle this? 它不会从阵列中选择随机单位,它不会在攻击者x防御者转弯之间切换,最糟糕的是,它只运行一个单位,当单位死亡时,脚本结束并且就是它...你们可以请给我一些回答,或处理这个问题的方法? I will be so thankfull because i am solving this for few days and i have no clue. 我会非常感激,因为我解决了这几天,我不知道。 Thanks. 谢谢。 (i know that the code is ugly, but its just concept...) (我知道代码很难看,但它只是概念...)

//EDIT Ok, i turned on the error reports and change a bit the simulation code, but the results are bad. //编辑好了,我打开了错误报告并更改了模拟代码,但结果很糟糕。 I get error Fatal error: Maximum execution time of 30 seconds exceeded in or Warning: Division by zero in php in line 我得到错误致命错误:超过30秒的最大执行时间或警告:在行中的除以零

  $hit = ($attacker['attack']/$defender['defense']) + rand(1, 2);

Heres the full code, ive tried rand(0,count($unit_attacker_def)-1); 下面是完整的代码,我试过rand(0,count($ unit_attacker_def)-1); but i think its without changes. 但我认为它没有变化。 Also i added selecting new random array with unit, if there is 0 health and unset. 此外,我添加了选择新的随机数组与单位,如果有0健康和未设置。 And its still running trought one unit, not all in attacker array, and all, or left units in defender array. 并且它仍在运行一个单位,而不是所有攻击者阵列,以及所有或左侧单位的后卫阵列。 I somehow came to phase where the script calls the next unit, but it havent any variables in it loaded. 我不知何故来到了脚本调用下一个单元的阶段,但它没有加载任何变量。

    case 'battle_wizard_execute';
                    ?>
                    <table> 
                    <tr><td><h3>Utok</h3></td></tr>
                    <?

                   $query_street = mysql_query("SELECT * FROM game_army_attacks WHERE attack_id = '".$_GET['id']."' ");
                   $row_street = mysql_fetch_assoc($query_street);

                   $query_loc_info = mysql_query("SELECT * FROM game_location_street WHERE street_id = '".$row_street['attack_attacker']."' ");
                   $row_loc_info = mysql_fetch_assoc($query_loc_info);

                   $tilee_info = mysql_num_rows($query_street);
                   if ($tilee_info > 0){ 

   $query_units_info = mysql_query("SELECT * FROM game_army_units_attacking WHERE army_attack = '".$_GET['id']."' ");
   while (($unitsinfo = mysql_fetch_assoc($query_units_info)) != NULL) {
   $query_unit_info = mysql_query("SELECT * FROM game_army_class WHERE army_class_id = '".$unitsinfo['army_class_id']."' ");
   $unit = mysql_fetch_assoc($query_unit_info);
   $unit_attacker = array();

   $unit_attacker[] = array(
        'name' => $unit['army_class_name'],
        'power' => $unitsinfo['army_power'],
        'attack' => $unitsinfo['army_att'],
        'defense' => $unitsinfo['army_def']
    );

   ///// Kolko jednotiek máš tolko krat sa vypise 
   $x = 1;    
   while($x <= $unitsinfo['army_population']) {

   foreach($unit_attacker as $index => $record){    

   ///// Tato cast pusti kod pre kazdu jednu jednotku ktora je v poli
   echo "<tr><td>Jednotka: {$record['name']} ID: {$record['power']} ParentID: {$record['attack']} Title: {$record['defense']}</td></tr>";
   $x++;
} 
}
}   
}  
                 ?>
                    </table>
                    <table> 
                    <tr><td><h3>Utok protivnik</h3></td></tr>
                    <?
   $query_street_def = mysql_query("SELECT * FROM game_army_units WHERE army_street = '".$row_street['attack_defender']."' ");
   $tilee_info_def = mysql_num_rows($query_street_def);
   if ($tilee_info_def > 0){ 

   $query_units_info_def = mysql_query("SELECT * FROM game_army_units WHERE army_street = '".$row_street['attack_defender']."' ");
   while (($unitsinfo_def = mysql_fetch_assoc($query_units_info_def)) != NULL) {
   $query_unit_info_def = mysql_query("SELECT * FROM game_army_class WHERE army_class_id = '".$unitsinfo_def['army_class_id']."' ");
   $unit_def = mysql_fetch_assoc($query_unit_info_def);
   $unit_attacker_def = array();

   $unit_attacker_def[] = array(
        'name' => $unit_def['army_class_name'],
        'power' => $unitsinfo_def['army_power'],
        'attack' => $unitsinfo_def['army_att'],
        'defense' => $unitsinfo_def['army_def']
    );

   ///// Kolko jednotiek máš tolko krat sa vypise 
   $y = 1;    
   while($y <= $unitsinfo_def['army_population']) {

   foreach($unit_attacker_def as $index => $record_def){    

   ///// Tato cast pusti kod pre kazdu jednu jednotku ktora je v poli
   echo "<tr><td>Jednotka: {$record_def['name']} ID: {$record_def['power']} ParentID: {$record_def['attack']} Title: {$record_def['defense']}</td></tr>";
   $y++;
} 
}
}    
} 

Simulation: 模拟:

 $count = 0;    
      while ((count($unit_attacker_def) > 0) && (count($unit_attacker) > 0)){
      $count++;
      $attacker_key = rand(0,count($unit_attacker_def)-1);
      $attacker     =& $unit_attacker[$attacker_key];
      $defender_key = rand(0,count($unit_defender)-1);
      $defender     =& $unit_attacker_def[$defender_key];
           while (($defender['power'] >= 0) && ($defender['power'] >= 0)){
      $hit = ($attacker['attack']/$defender['defense']) + rand(1, 2);
      echo "<tr><td>{$count}.xx {$attacker_key} xJednotka {$defender['name']} ({$defender['power']} hp) bola zranená a dostala {$hit} zranenia jednotkou {$attacker['name']} ({$attacker['power']} hp)</td></tr>";
      $defender['power'] = $defender['power'] - $hit;
      $attacker['power'] = $attacker['power'] - $hit;

      if ($defender['power'] <= 0) {
        echo "<tr>Jednotka {$defender['name']} umrela, jednotka {$attacker['name']} vyhrala!</tr>";
        unset($defender[$defender_key]);
        $defender_key = rand(0,count($unit_defender)-1);
        $defender =& $unit_attacker_def[$defender_key];

      }
        if ($attacker['power'] <= 0) {
        echo "<tr>Jednotka {$attacker['name']} umrela, jednotka {$defender['name']} vyhrala!</tr>";
        unset($attacker[$attacker_key]);
        $attacker_key = rand(0,count($unit_attacker_def)-1);
        $attacker =& $unit_attacker[$attacker_key];
      }
      }
    }
     ?>
     </table>
     <? 
             break;

First of all, make sure you have turned on error reporting: 首先,确保您已启用错误报告:

<?php
// Turn off error reporting
error_reporting(0);

// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Report all errors
error_reporting(E_ALL);

// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

With simple debugging you will find out where is an error. 通过简单的调试,您将找到错误的位置。 Just var_dump() every important variable and check its state. 只需var_dump()每个重要变量并检查其状态。 Nobody can debug for you because we don't know what is the data in your mysql table. 没有人可以为您调试,因为我们不知道您的mysql表中的数据是什么。

Try to use mysqli_* functions, because mysql are deprecated. 尝试使用mysqli_ *函数,因为不推荐使用mysql。

Try to use classes to describe everything in your game and make it more readable and maintainable. 尝试使用类来描述游戏中的所有内容,使其更具可读性和可维护性。 For example: 例如:

    <?php

    abstract class Unit{


        protected $hp;
        protected $damage;
        protected $defense;

        // Force Extending class to define this method
        abstract protected function applyDamage($damage);

    }

    class GroundUnit extends Unit{

        //GroundUnit inherits everything from Unit

        //define methods specific for GroundUnits


    }

    class FlyingUnit extends Unit{
        //FlyingUnit inherits everything from Unit

         //define methods specific for GroundUnits

}

When you find where is an error, and if you are still stuck, update your question with relevant data. 当您发现错误的位置,并且如果您仍然卡住时,请使用相关数据更新您的问题。

Note that your code is vulnerable to SQL injection 请注意,您的代码容易受到SQL注入攻击

$query_street = mysql_query("SELECT * FROM game_army_attacks WHERE attack_id = '".$_GET['id']."' ");//don't put $_GET['id'] directly into query because that is security hole

Simple steps(related to your example) to improve your protection from sql injection would be : 简单的步骤(与您的示例相关),以提高您的sql注入保护将是:

//assume that $_GET['id'] should hold an integer value

$id = isset($_GET['id']? trim($_GET['id']) ? 0);
$id = (int)$id;

Now let's pretend that there is a $_GET['some_key'] also and it should hold string value. 现在让我们假装还有一个$ _GET ['some_key']并且它应该保存字符串值。 Now checks would be little different: 现在检查会有所不同:

$some_string_value =  isset($_GET['some_key']? trim($_GET['some_key']) ? '');
$some_string_value = trim($some_string_value);//triming whitespace
$some_string_value = mysql_real_escape_string($some_string_value);//escaping troublesome quotes(')

Also you can use prepared statements which is in my opinion a preferred way. 您也可以使用我认为是首选方式的预准备语句

Well you use array_rand() it selects one element from the array and when u use $array[$key] where $key = 1 because of array to var conversion it returns second element of your array atackers and second element of defenders. 那么你使用array_rand()它从数组中选择一个元素,当你使用$array[$key] ,其中$key = 1因为数组到var的转换,它返回数组atackers的第二个元素和防御者的第二个元素。 Use rand(0,count($unit_attacker)-1) to generate random key. 使用rand(0,count($unit_attacker)-1)生成随机密钥。 But it still will be bugy because you can generate the same key )). 但它仍然会很烦人,因为你可以生成相同的密钥))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM