Test Failed
Push — trunk ( 132e87...b3f953 )
by SuperNova.WS
11:54
created

coe_o_missile_calculate()   C

Complexity

Conditions 11
Paths 13

Size

Total Lines 89
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 57
nc 13
nop 0
dl 0
loc 89
rs 6.7915
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// Copyright (c) 2009-2012 by Gorlum for http://supernova.ws
3
// Date 2009-08-08
4
// Open Source
5
// V1
6
//
7
use DBAL\db_mysql;
8
use DBAL\OldDbChangeSet;
9
use Planet\DBStaticPlanet;
10
11
function COE_missileAttack($defenceTech, $attackerTech, $MIPs, $structures, $targetedStructure = '0') {
12
  // Here we select which part of defense should take damage: structure or shield
13
  // $damageTo = P_SHIELD;
14
  // $damageTo = P_STRUCTURE;
15
  $damageTo = P_DEFENSE;
16
17
  $mip_data  = get_unit_param(UNIT_DEF_MISSILE_INTERPLANET);
18
  $MIPDamage = floor(mrc_modify_value($attackerTech, false, TECH_WEAPON, $MIPs * $mip_data[P_ATTACK] * mt_rand(80, 120) / 100));
19
  foreach ($structures as $key => $structure) {
20
    $unit_info                     = get_unit_param($key);
21
    $amplify                       = isset($mip_data[P_AMPLIFY][$key]) ? $mip_data[P_AMPLIFY][$key] : 1;
22
    $structures[$key][P_SHIELD]    = floor(mrc_modify_value($defenceTech, false, TECH_SHIELD, $unit_info[P_SHIELD]) / $amplify);
23
    $structures[$key][P_STRUCTURE] = floor(mrc_modify_value($defenceTech, false, TECH_ARMOR, $unit_info[P_ARMOR]) / $amplify);
24
    $structures[$key][P_DEFENSE]   = floor((
25
        mrc_modify_value($defenceTech, false, TECH_ARMOR, $unit_info[P_ARMOR]) +
26
        mrc_modify_value($defenceTech, false, TECH_SHIELD, $unit_info[P_SHIELD])
27
      ) / $amplify * mt_rand(80, 120) / 100);
28
  }
29
30
  $startStructs = $structures;
31
32
  if ($targetedStructure) {
33
    //attacking only selected structure
34
    $damageDone                        = $structures[$targetedStructure][$damageTo];
35
    $structsDestroyed                  = min(floor($MIPDamage / $damageDone), $structures[$targetedStructure][0]);
36
    $structures[$targetedStructure][0] -= $structsDestroyed;
37
    $MIPDamage                         -= $structsDestroyed * $damageDone;
38
  } else {
39
    // REALLY random attack
40
    $can_be_damaged = sn_get_groups('defense_active');
41
//debug($structures);
42
//debug($can_be_damaged);
43
    do {
44
      // finding is there any structure that can be damaged with leftovers of $MIPDamage
45
      foreach ($can_be_damaged as $key => $unit_id) {
46
//debug($structures[$unit_id][0]);
47
//debug($structures[$unit_id][$damageTo], $MIPDamage);
48
        if ($structures[$unit_id][0] <= 0 || $structures[$unit_id][$damageTo] > $MIPDamage) {
49
          unset($can_be_damaged[$key]);
50
        }
51
      }
52
      if (empty($can_be_damaged)) {
53
        break;
54
      }
55
      sort($can_be_damaged);
56
//debug($can_be_damaged, 'can be damaged');
57
      $random_defense = mt_rand(0, count($can_be_damaged) - 1);
58
//debug($can_be_damaged[$random_defense], 'Target');
59
      $current_target = &$structures[$can_be_damaged[$random_defense]];
60
//debug($current_target[0], 'Amount was');
61
      $can_be_destroyed = min($current_target[0], floor($MIPDamage / $current_target[$damageTo]));
62
//debug($MIPDamage, 'MIPDamage');
63
//debug($can_be_destroyed, 'Can be destroyed');
64
      $destroyed         = mt_rand(1, $can_be_destroyed);
65
      $MIPDamage         -= $current_target[$damageTo] * $destroyed;
66
      $current_target[0] -= $destroyed;
67
//debug($destroyed, 'Actually destroyed');
68
69
//print('<hr>');
70
    } while ($MIPDamage > 0 && !empty($can_be_damaged));
71
//debug($MIPDamage, 'MIPDamage left');
72
  }
73
//debug($structures);//die();
74
  // 1/2 of metal and 1/4 of crystal of destroyed structures returns to planet
75
  $metal   = 0;
76
  $crystal = 0;
77
  foreach ($structures as $key => $structure) {
78
    $unit_info = get_unit_param($key);
79
    $destroyed = $startStructs[$key][0] - $structure[0];
80
    $metal     += $destroyed * $unit_info[P_COST][RES_METAL] / 2;
81
    $crystal   += $destroyed * $unit_info[P_COST][RES_CRYSTAL] / 4;
82
  }
83
84
  $return['structures'] = $structures;     // Structures left after attack
0 ignored issues
show
Comprehensibility Best Practice introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.
Loading history...
85
  $return['metal']      = floor($metal);   // Metal scraps
86
  $return['crystal']    = floor($crystal); // Crystal scraps
87
88
  return $return;
89
}
90
91
// Copyright (c) 2009-2010 by Gorlum for http://supernova.ws
92
// Date 2009-08-08
93
// Open Source
94
95
/**
96
 * Copyright (c) 2009-2010 by Gorlum for http://supernova.ws
97
 *       OpenSource as long as you don't remove this Copyright
98
 * V3 2009-11-13
99
 * V2 2009-10-10
100
 */
101
102
function coe_o_missile_calculate() {
103
//  db_mysql::db_transaction_check(true);
104
105
  global $lang;
106
107
  $iraks = doquery("SELECT * FROM {{iraks}} WHERE `fleet_end_time` <= " . SN_TIME_NOW . " FOR UPDATE;");
0 ignored issues
show
Deprecated Code introduced by
The function doquery() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

107
  $iraks = /** @scrutinizer ignore-deprecated */ doquery("SELECT * FROM {{iraks}} WHERE `fleet_end_time` <= " . SN_TIME_NOW . " FOR UPDATE;");
Loading history...
108
109
  while ($fleetRow = db_fetch($iraks)) {
0 ignored issues
show
Deprecated Code introduced by
The function db_fetch() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

109
  while ($fleetRow = /** @scrutinizer ignore-deprecated */ db_fetch($iraks)) {
Loading history...
110
    $sourcePlanet = DBStaticPlanet::db_planet_by_vector($fleetRow, 'fleet_start_');
111
    $target_planet_row = DBStaticPlanet::db_planet_by_gspt(
112
      $fleetRow['fleet_end_galaxy'],
113
      $fleetRow['fleet_end_system'],
114
      $fleetRow['fleet_end_planet'],
115
      PT_PLANET
116
    );
117
    $targetUser = db_user_by_id($target_planet_row['id_owner'], true);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

117
    $targetUser = /** @scrutinizer ignore-deprecated */ db_user_by_id($target_planet_row['id_owner'], true);
Loading history...
118
    $rowAttacker = db_user_by_id($fleetRow['fleet_owner'], true);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

118
    $rowAttacker = /** @scrutinizer ignore-deprecated */ db_user_by_id($fleetRow['fleet_owner'], true);
Loading history...
119
120
    db_mysql::db_transaction_start();
121
    set_time_limit(15);
122
    SN::$gc->db->lockRecords([
123
      'users'   => [$targetUser['id'], $rowAttacker['id'],],
124
      'planets' => [$target_planet_row['id'], $sourcePlanet['id'],],
125
      'iraks'   => [$fleetRow['id'],],
126
    ]);
127
    $fleetRow = doquery("SELECT * FROM `{{iraks}}` WHERE `id` = {$fleetRow['id']} FOR UPDATE;", '', true);
0 ignored issues
show
Deprecated Code introduced by
The function doquery() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

127
    $fleetRow = /** @scrutinizer ignore-deprecated */ doquery("SELECT * FROM `{{iraks}}` WHERE `id` = {$fleetRow['id']} FOR UPDATE;", '', true);
Loading history...
128
    if (empty($fleetRow)) {
129
      db_mysql::db_transaction_rollback();
130
      continue;
131
    }
132
133
    $db_changeset = array();
134
135
    $target_planet_row = sys_o_get_updated($targetUser['id'], $target_planet_row['id'], SN_TIME_NOW);
136
    $target_planet_row = $target_planet_row['planet'];
137
138
139
    if ($target_planet_row['id']) {
140
      $planetDefense = array();
141
      foreach (sn_get_groups('defense_active') as $unit_id) {
142
        $planetDefense[$unit_id] = array(mrc_get_level($targetUser, $target_planet_row, $unit_id, true, true));
143
      }
144
145
      $message      = '';
146
      $interceptors = mrc_get_level($targetUser, $target_planet_row, UNIT_DEF_MISSILE_INTERCEPTOR, true, true); //$target_planet_row[$interceptor_db_name]; // Number of interceptors
147
      $missiles     = $fleetRow['fleet_amount']; // Number of MIP
148
      if ($interceptors >= $missiles) {
149
        $message                = $lang['mip_all_destroyed'];
150
        $db_changeset['unit'][] = OldDbChangeSet::db_changeset_prepare_unit(UNIT_DEF_MISSILE_INTERCEPTOR, -$missiles, $targetUser, $target_planet_row['id']);
151
      } else {
152
        if ($interceptors) {
153
          $message                = sprintf($lang['mip_destroyed'], $interceptors);
154
          $db_changeset['unit'][] = OldDbChangeSet::db_changeset_prepare_unit(UNIT_DEF_MISSILE_INTERCEPTOR, -$interceptors, $targetUser, $target_planet_row['id']);
155
        }
156
157
        $attackResult = COE_missileAttack($targetUser, $rowAttacker, $missiles - $interceptors, $planetDefense, $fleetRow['primaer']);
158
159
        foreach ($attackResult['structures'] as $key => $structure) {
160
          $destroyed = $planetDefense[$key][0] - $structure[0];
161
          if ($destroyed) {
162
            $db_changeset['unit'][] = OldDbChangeSet::db_changeset_prepare_unit($key, -$destroyed, $targetUser, $target_planet_row['id']);
163
164
            $message .= "&nbsp;&nbsp;{$lang['tech'][$key]} - {$destroyed} {$lang['quantity']}<br>";
165
          }
166
        }
167
168
        if (!empty($message)) {
169
          $message = $lang['mip_defense_destroyed'] . $message . "{$lang['mip_recycled']}{$lang['Metal']}: {$attackResult['metal']}, {$lang['Crystal']}: {$attackResult['crystal']}<br>";
170
171
          DBStaticPlanet::db_planet_set_by_id($target_planet_row['id'], "`metal` = `metal` + {$attackResult['metal']}, `crystal` = `crystal` + {$attackResult['crystal']}");
172
        }
173
      }
174
      OldDbChangeSet::db_changeset_apply($db_changeset);
175
176
      $fleetRow['fleet_start_type'] = PT_PLANET;
177
178
      $message_vorlage = sprintf($lang['mip_body_attack'], $fleetRow['fleet_amount'],
179
        addslashes($sourcePlanet['name']), $fleetRow['fleet_start_galaxy'], $fleetRow['fleet_start_system'], $fleetRow['fleet_start_planet'],
180
        addslashes($target_planet_row['name']), $fleetRow['fleet_end_galaxy'], $fleetRow['fleet_end_system'], $fleetRow['fleet_end_planet']);
181
182
      empty($message) ? $message = $lang['mip_no_defense'] : false;
183
184
      msg_send_simple_message($fleetRow['fleet_owner'], '', SN_TIME_NOW, MSG_TYPE_SPY, $lang['mip_sender_amd'], $lang['mip_subject_amd'], $message_vorlage . $message);
185
      msg_send_simple_message($fleetRow['fleet_target_owner'], '', SN_TIME_NOW, MSG_TYPE_SPY, $lang['mip_sender_amd'], $lang['mip_subject_amd'], $message_vorlage . $message);
186
    }
187
188
    doquery("DELETE FROM {{iraks}} WHERE id = '{$fleetRow['id']}';");
0 ignored issues
show
Deprecated Code introduced by
The function doquery() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

188
    /** @scrutinizer ignore-deprecated */ doquery("DELETE FROM {{iraks}} WHERE id = '{$fleetRow['id']}';");
Loading history...
189
190
    db_mysql::db_transaction_commit();
191
  }
192
193
}
194