Jump to content
MakeWebGames

Error


Samurai Legend
 Share

Recommended Posts

Error - 

Fatal error: Uncaught TypeError: Unsupported operand types: string + int in /Users/shahed/Projects/samuraiconflict/attack.php:98 Stack trace: #0 /Users/shahed/.composer/vendor/laravel/valet/server.php(235): require() #1 {main} thrown in /Users/shahed/Projects/samuraiconflict/attack.php on line 98

 

 Line -       $ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;

 

Tried searching for the fix but I couldn't seem to get anywhere, please help!

Link to comment
Share on other sites

Post or send me your attack.php Just because the line says its line 98 doesn't always mean its that line that is the cause ??

However 

 

$ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;

depending on whats above that line you could change to

 

 

if ( !$_GET['nextstep'] ) {
        $ns = 1;
     } else {
        $ns = $_GET['nextstep'] + 2;
     }

or

 

 

if(!$_GET['nextstep']) { $ns=1; } else { $ns=$_GET['nextstep']+2; }

 

But im just shooting in the dark here without seeing whats above or below

Edited by Uridium
fat fingers
Link to comment
Share on other sites

Posted (edited)

Still the same error, I have posted my full attack script

Quote
<?php
define('PAGE_HEADER', 'Attacking');
$atkpage = 1;
require('globals.php');
$rounds = 25;

?><h3><u>Attacking</u></h3><?php

$_GET['ID'] = (isset($_GET['ID']) 
			&& is_numeric($_GET['ID'])) 
			? abs(intval($_GET['ID'])) : '';

$prohibited = array(1); //Add player IDs to this array that you don't want to get attacks.

if(in_array($_GET['ID'], $prohibited)) {
    ?>You cannot attack this player.<a href = 'viewuser.php?u=<?php echo $_GET['ID']; ?>'>&gt; Go Back</a><a href = 'index.php'>&gt; Go Home</a><?php
    exit($h->endpage());
}
if(!$_GET['ID']) {
	cancelAttack('Invalid ID.');
}
if($_GET['ID'] == $userid) {
	cancelAttack('You can\'t attack yourself.');
}	
if($ir['hp'] <= 1) {
	cancelAttack('You\'re unconcious therefore you can\'t attack.');
}
if(isset($_SESSION['attacklost']) && $_SESSION['attacklost'] == 1) {
	$_SESSION['attacklost'] = 0;
	cancelAttack('Only the losers of all their EXP attack when they\'ve already lost.');
}
$youdata   = $ir;
$odata_sql = <<<SQL
	SELECT `u`.`userid`, `hp`, `hospital`, `prison`, `equip_armor`, `username`,
	`equip_primary`, `equip_secondary`, `clan`, `location`, `maxhp`,
	`guard`, `agility`, `strength`, `gender`, `display_pic`, `attacks_won`
	FROM `users` AS `u`
	INNER JOIN `userstats` AS `us` ON `u`.`userid` = `us`.`userid`
	WHERE `u`.`userid` = {$_GET['ID']}
	LIMIT 1
SQL;
$q = $db->query($odata_sql);
if($db->num_rows($q) == 0) {
	cancelAttack('That user does not exist.');
}
$odata = $db->fetch_row($q);
$db->free_result($q);
$myabbr = ($ir['gender'] == 'Male') ? 'his' : 'her';
$oabbr  = ($odata['gender'] == 'Male') ? 'his' : 'her';
if($ir['attacking'] && $ir['attacking'] != $_GET['ID']) {
	$_SESSION['attacklost'] = 0;
	cancelAttack('Something went wrong.');
}
if($odata['hp'] == 1) {
	cancelAttack('This player is unconscious.');
}
if($odata['hospital']) {
	cancelAttack('This player is in hospital.');
}
if($ir['hospital']) {
	cancelAttack('While in hospital you can\'t attack.');
}
if($odata['prison']) {
	cancelAttack('This player is in prison.');
}
if($ir['prison']) {
	cancelAttack('While in prison you can\'t attack.');
}
if($odata['hp'] < 5) {
	cancelAttack('You can only attack those who have health.');
} else if($ir['clan'] == $odata['clan'] && $ir['clan'] > 0) {
	cancelAttack("You are in the same clan as {$odata['username']}!");
} else if($youdata['energy'] < $youdata['maxenergy'] / 2) {
	cancelAttack('You can only attack someone when you have 50% energy.');
} else if($youdata['location'] != $odata['location']) {
	cancelAttack('You can only attack someone in the same location!');
}
$userdp = ($ir['display_pic']) 
? '<img src = "' . $ir['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />';

$odp = ($odata['display_pic']) 
? '<img src = "' . $odata['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />';

?><hr width = '100%'>
<table width = '100%' cellpadding = '1' cellspacing = '1' class = 'table'>
<tr>
	<th width = '33%'><?php echo $ir['username']; ?></th>
	<th width = '33%'>VS</th>
	<th width = '33%'><?php echo username($odata['userid']); ?></th>
</tr>
<tr>
	<th width = '33%'><?php echo $userdp; ?><br/>Attacks Won: <?php echo $ir['attacks_won']; ?></th>
	<th width = '33%'><?php
$mw = $db->query("SELECT `itmid`,`itmname` FROM  `items`  WHERE `itmid` IN({$ir['equip_primary']}, {$ir['equip_secondary']})");
	?>Attack with:<br /><?php
if($db->num_rows($mw) > 0) {
	while($r = $db->fetch_row($mw)) {
		$ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;
		if($r['itmid'] == $ir['equip_primary']) {
			?><b>Primary Weapon:</b><?php
			?><a href='attack.php?nextstep=$ns&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php
		}
		if($r['itmid'] == $ir['equip_secondary']) {
			?><b>Secondary Weapon:</b><?php
			?><a href='attack.php?nextstep=$ns&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php
		}
	}
} else {
	?>You have nothing to fight with.<?php
}
$db->free_result($mw);
$vars['hpperc']  = round($youdata['hp'] / $youdata['maxhp'] * 100);
$vars['hpopp']   = 100 - $vars['hpperc'];
$vars2['hpperc'] = round($odata['hp'] / $odata['maxhp'] * 100);
$vars2['hpopp']  = 100 - $vars2['hpperc'];

?></th>
	<th width = '33%'><?php echo $odp; ?><br/>Attacks Won: <?php echo $odata['attacks_won']; ?></th>
</tr>

<tr>
	<th width = '33%'>
		<img src = 'images/greenbar.gif' width = '<?php echo $vars['hpperc']; ?>'	 height = '10'>
		<img src= 'images/greybar.gif' width = '<?php echo $vars['hpopp']; ?>' height = '10'></th>
		<th>&nbsp;</th>
	<th width = '33%'>
		<img src = 'images/greenbar.gif' width = '<?php echo $vars2['hpperc']; ?>' height = '10'>
		<img src = 'images/greybar.gif' width = '<?php echo $vars2['hpopp']; ?>' height = '10'></th>
</tr>
<tr>
<td colspan = '3' align = 'center'>
<?php

$_GET['wepid'] = (isset($_GET['wepid']) && is_numeric($_GET['wepid'])) ? abs(intval($_GET['wepid'])) : '';
if($_GET['wepid']) {
	$_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : 1;
	if($_SESSION['attacking'] == 0 && $ir['attacking'] == 0) {
		if($youdata['energy'] >= $youdata['maxenergy'] / 2) {
			$youdata['energy'] -= floor($youdata['maxenergy'] / 2);
			$cost = floor($youdata['maxenergy'] / 2);
			$db->query("UPDATE `users` SET `energy` = `energy` - {$cost} " . "WHERE `userid` = {$userid}");
			$_SESSION['attacklog'] = '';
			$_SESSION['attackdmg'] = 0;
		} else {
			cancelAttack("You can only attack someone when you have 50% energy.");
	}
}
	$_SESSION['attacking'] = 1;
	$ir['attacking']       = $odata['userid'];
	$db->query("UPDATE `users` SET `attacking` = {$ir['attacking']} WHERE `userid` = {$userid}");
	$_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : '';
	if($_GET['wepid'] != $ir['equip_primary'] && $_GET['wepid'] != $ir['equip_secondary']) {
		$db->query("UPDATE `users` SET `exp` = 0 WHERE `userid` = {$userid}");
		cancelAttack("Stop trying to abuse a game bug.");
	}
	$qo = $db->query("SELECT `itmname`, `weapon` FROM `items` WHERE `itmid` = {$_GET['wepid']} LIMIT 1");
	if($db->num_rows($qo) == 0) {
		cancelAttack("That weapon doesn not exist.");
	}
	$r1 = $db->fetch_row($qo);
	$db->free_result($qo);
	$mydamage = (int) (($r1['weapon'] * $youdata['strength'] / ($odata['guard'] / 1.5)) * (rand(8000, 12000) / 10000));
	$hitratio = max(10, min(60 * $ir['agility'] / $odata['agility'], 95));
	if(rand(1, 100) <= $hitratio) {
		if($odata['equip_armor'] > 0) {
			$q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$odata['equip_armor']} LIMIT 1");
			if($db->num_rows($q3) > 0)
				$mydamage -= $db->fetch_single($q3);
			$db->free_result($q3);
		}
		if($mydamage < -100000)
			$mydamage = abs($mydamage);
		else if($mydamage < 1)
			$mydamage = 1;
		$crit = rand(1, 40);
		if($crit == 17)
			$mydamage *= rand(20, 40) / 10;
		else if($crit == 25 OR $crit == 8)
			$mydamage /= (rand(20, 40) / 10);
		$mydamage = round($mydamage);
		$odata['hp'] -= $mydamage;
		if($odata['hp'] == 1) {
			$odata['hp'] = 0;
			$mydamage += 1;
		}
		$db->query("UPDATE `users` SET `hp` = `hp` - $mydamage WHERE `userid` = {$_GET['ID']}");
		echo "<font color = 'red'>{$_GET['nextstep']}. Using your {$r1['itmname']} you hit {$odata['username']} doing $mydamage damage ({$odata['hp']})</font><br />\n";
		$_SESSION['attackdmg'] += $mydamage;
		$_SESSION['attacklog'] .= "<font color = 'red'>{$_GET['nextstep']}. Using {$myabbr} {$r1['itmname']} {$ir['username']} hit {$odata['username']} doing $mydamage damage ({$odata['hp']})</font><br />\n";
	} else {
		echo "<font color=red>{$_GET['nextstep']}. You tried to hit {$odata['username']} but missed ({$odata['hp']})</font><br />\n";
		$_SESSION['attacklog'] .= "<font color = 'red'>{$_GET['nextstep']}. {$ir['username']} tried to hit {$odata['username']} but missed ({$odata['hp']})</font><br />\n";
	}
	if($odata['hp'] <= 0) {
		$odata['hp']           = 0;
		$_SESSION['attackwon'] = $_GET['ID'];
		$db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = {$_GET['ID']}");
		$db->query("UPDATE `users` SET `LWID` = {$_GET['ID']} WHERE `userid` = {$ir['userid']}");
		echo "<br />
<b>What do you want to do with {$odata['username']} now?</b><br />
<form action='attackwon.php?ID={$_GET['ID']}' method='post'><input type='submit' value='Mug Them' /></form>
<form action='attackbeat.php?ID={$_GET['ID']}' method='post'><input type='submit' value='Hospitalize Them' /></form>
<form action='attacktake.php?ID={$_GET['ID']}' method='post'><input type='submit' value='Leave Them' /></form>";
	} else {
		$eq = $db->query("SELECT `itmname`,`weapon` FROM  `items` WHERE `itmid` IN({$odata['equip_primary']}, {$odata['equip_secondary']})");
		if($db->num_rows($eq) == 0) {
			$wep = "Fists";
			$dam = (int) ((((int) ($odata['strength'] / $ir['guard'] / 100)) + 1) * (rand(8000, 12000) / 10000));
		} else {
			$cnt = 0;
			while($r = $db->fetch_row($eq)) {
				$enweps[] = $r;
				++$cnt;
			}
			$db->free_result($eq);
			$weptouse = rand(0, $cnt - 1);
			$wep      = $enweps[$weptouse]['itmname'];
			$dam      = (int) (($enweps[$weptouse]['weapon'] * $odata['strength'] / ($youdata['guard'] / 1.5)) * (rand(8000, 12000) / 10000));
		}
		$hitratio = max(10, min(60 * $odata['agility'] / $ir['agility'], 95));
		if(rand(1, 100) <= $hitratio) {
			if($ir['equip_armor'] > 0) {
				$q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$ir['equip_armor']} LIMIT 1");
				if($db->num_rows($q3) > 0)
					$dam -= $db->fetch_single($q3);
				$db->free_result($q3);
			}
			if($dam < -100000)
				$dam = abs($dam);
			else if($dam < 1)
				$dam = 1;
			$crit = rand(1, 40);
			if($crit == 17)
				$dam *= rand(20, 40) / 10;
			else if($crit == 25 OR $crit == 8)
				$dam /= (rand(20, 40) / 10);
			$dam = round($dam);
			$youdata['hp'] -= $dam;
			if($youdata['hp'] == 1) {
				$dam += 1;
				$youdata['hp'] = 0;
			}
			$db->query("UPDATE `users` SET `hp` = `hp` - $dam WHERE `userid` = $userid");
			$ns = $_GET['nextstep'] + 1;
			echo "<font color = 'blue'>{$ns}. Using $oabbr $wep {$odata['username']} hit you doing $dam damage ({$youdata['hp']})</font><br />\n";
			$_SESSION['attacklog'] .= "<font color = 'blue'>{$ns}. Using $oabbr $wep {$odata['username']} hit {$ir['username']} doing $dam damage ({$youdata['hp']})</font><br />\n";
		} else {
			$ns = $_GET['nextstep'] + 1;
			echo "<font color = 'red'>{$ns}. {$odata['username']} tried to hit you but missed ({$youdata['hp']})</font><br />\n";
			$_SESSION['attacklog'] .= "<font color = 'blue'>{$ns}. {$odata['username']} tried to hit {$ir['username']} but missed ({$youdata['hp']})</font><br />\n";
		}
		if($youdata['hp'] <= 0) {
			$youdata['hp']          = 0;
			$_SESSION['attacklost'] = 1;
			$db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = $userid");
			echo "<form action='attacklost.php?ID={$_GET['ID']}' method='post'><input type='submit' value='Continue' />";
		}
	}
}	
echo '</td></tr></table>';
$h->endpage();

 

 

@Uridium - Thank you for helping me out

10 hours ago, Uridium said:

Post or send me your attack.php Just because the line says its line 98 doesn't always mean its that line that is the cause ??

However 

 

$ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;

$ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;

depending on whats above that line you could change to

 

 

if ( !$_GET['nextstep'] ) {         $ns = 1;      } else {         $ns = $_GET['nextstep'] + 2;      }

if ( !$_GET['nextstep'] ) {
        $ns = 1;
     } else {
        $ns = $_GET['nextstep'] + 2;
     }

or

 

 

if(!$_GET['nextstep']) { $ns=1; } else { $ns=$_GET['nextstep']+2; }

if(!$_GET['nextstep']) { $ns=1; } else { $ns=$_GET['nextstep']+2; }

 

But im just shooting in the dark here without seeing whats above or below

 

Edited by Samurai Legend
Link to comment
Share on other sites

it says the error within  Unsupported operand types: string + int

you need to make sure you are not mixing types and also wrap your operators correctly as could play a part in your errors.

this part is clearly the error, you could try using abs and intval to correct this.

$_GET['nextstep'] + 2
Edited by URBANZ
Link to comment
Share on other sites

Posted (edited)

Hello, I have fixed the issue. I forgot to echo out two statements on the links when attacking which was causing the error. However, now I am receiving the error only when the attacker is weaker than the person they are attacking. Can someone help me out on this as I have no clue on why it is throwing the error. 

Fatal error: Uncaught DivisionByZeroError: Division by zero in /attack.php:237 Stack trace: #0 /.composer/vendor/laravel/valet/server.php(235): require() #1 {main} thrown in /attack.php on line 237

 

Line 235 - 237

            $dam = 
            		(int) (($enweps[$weptouse]['weapon'] * $odata['strength'] 
            				/ ($youdata['guard'] / 1.5)) 
            				* (rand(8000, 12000) / 10000));
<?php
define('PAGE_HEADER', 'Attacking');
$atkpage = 1;
require('globals.php');
$rounds = 250;

?><h3><u>Attacking</u></h3><?php

$_GET['ID'] = (isset($_GET['ID']) 
			&& is_numeric($_GET['ID'])) 
			? abs(intval($_GET['ID'])) : '';

$_GET['nextstep'] = (isset($_GET['nextstep']) 
            && is_numeric($_GET['nextstep'])) 
            ? abs(intval($_GET['nextstep'])) : '0';

$prohibited = array(1); //Add player IDs to this array that you don't want to get attacks.

if(in_array($_GET['ID'], $prohibited)) {
    ?>You cannot attack this player.<br/>
    <a href = 'viewuser.php?u=<?php echo $_GET['ID']; ?>'>&gt; Go Back</a><br/>
    <a href = 'index.php'>&gt; Go Home</a><?php
    exit($h->endpage());
}
if(!$_GET['ID']) {
	cancelAttack('Invalid ID.');
}
if($_GET['ID'] == $userid) {
	cancelAttack('You can\'t attack yourself.');
}	
if($ir['hp'] <= 1) {
	cancelAttack('You\'re unconcious therefore you can\'t attack.');
}
if(isset($_SESSION['attacklost']) && $_SESSION['attacklost'] == 1) {
	$_SESSION['attacklost'] = 0;
	cancelAttack('Only the losers of all their EXP attack when they\'ve already lost.');
}
$youdata   = $ir;
$odata_sql = <<<SQL
	SELECT `u`.`userid`, `hp`, `hospital`, `prison`, `equip_armor`, `username`,
	`equip_primary`, `equip_secondary`, `clan`, `location`, `maxhp`,
	`guard`, `agility`, `strength`, `gender`, `display_pic`, `attacks_won`
	FROM `users` AS `u`
	INNER JOIN `userstats` AS `us` ON `u`.`userid` = `us`.`userid`
	WHERE `u`.`userid` = {$_GET['ID']}
	LIMIT 1
SQL;
$q = $db->query($odata_sql);
if($db->num_rows($q) == 0) {
	cancelAttack('That user does not exist.');
}
$odata = $db->fetch_row($q);
$db->free_result($q);
$myabbr = ($ir['gender'] == 'Male') ? 'his' : 'her';
$oabbr  = ($odata['gender'] == 'Male') ? 'his' : 'her';
if($ir['attacking'] && $ir['attacking'] != $_GET['ID']) {
	$_SESSION['attacklost'] = 0;
	cancelAttack('Something went wrong.');
}
if($odata['hp'] == 1) {
	cancelAttack('This player is unconscious.');
}
if($odata['hospital']) {
	cancelAttack('This player is in hospital.');
}
if($ir['hospital']) {
	cancelAttack('While in hospital you can\'t attack.');
}
if($odata['prison']) {
	cancelAttack('This player is in prison.');
}
if($ir['prison']) {
	cancelAttack('While in prison you can\'t attack.');
}
if($odata['hp'] < 5) {
	cancelAttack('You can only attack those who have health.');
} else if($ir['clan'] == $odata['clan'] && $ir['clan'] > 0) {
	cancelAttack("You are in the same clan as {$odata['username']}!");
} else if($youdata['energy'] < $youdata['maxenergy'] / 2) {
	cancelAttack('You can only attack someone when you have 50% energy.');
} else if($youdata['location'] != $odata['location']) {
	cancelAttack('You can only attack someone in the same location!');
}
if($_GET['nextstep'] > $rounds) {
	cancelAttack('You both have become tired and called it a draw. You have been sent home.');
}


$userdp = ($ir['display_pic']) 
? '<img src = "' . $ir['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />';

$odp = ($odata['display_pic']) 
? '<img src = "' . $odata['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />';

?><hr width = '100%'>
<table width = '100%' cellpadding = '1' cellspacing = '1' class = 'table'>
<tr>
	<th width = '33%'><?php echo $ir['username']; ?></th>
	<th width = '33%'>VS</th>
	<th width = '33%'><?php echo username($odata['userid']); ?></th>
</tr>
<tr>
	<th width = '33%'><?php echo $userdp; ?><br/>Attacks Won: <?php echo $ir['attacks_won']; ?></th>
	<th width = '33%'><?php
$mw = $db->query("SELECT `itmid`,`itmname` FROM  `items`  WHERE `itmid` IN({$ir['equip_primary']}, {$ir['equip_secondary']})");
	?>Attack with:<br /><?php
if($db->num_rows($mw) > 0) {
	while($r = $db->fetch_row($mw)) {
		$ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;
		if($r['itmid'] == $ir['equip_primary']) {
			?><b>Primary Weapon:</b><?php
			?><a href='attack.php?nextstep=<?php echo $ns; ?>&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php
		}
		if($r['itmid'] == $ir['equip_secondary']) {
			?><b>Secondary Weapon:</b><?php
			?><a href='attack.php?nextstep=<?php echo $ns; ?>&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php
		}
	}
} else {
	?>You have nothing to fight with.<?php
}
$db->free_result($mw);
$vars['hpperc']  = round($youdata['hp'] / $youdata['maxhp'] * 100);
$vars['hpopp']   = 100 - $vars['hpperc'];
$vars2['hpperc'] = round($odata['hp'] / $odata['maxhp'] * 100);
$vars2['hpopp']  = 100 - $vars2['hpperc'];

?></th>
	<th width = '33%'><?php echo $odp; ?><br/>Attacks Won: <?php echo $odata['attacks_won']; ?></th>
</tr>

<tr>
	<th width = '33%'>
		<img src = 'images/greenbar.gif' width = '<?php echo $vars['hpperc']; ?>'	 height = '10'>
		<img src= 'images/greybar.gif' width = '<?php echo $vars['hpopp']; ?>' height = '10'></th>
		<th>&nbsp;</th>
	<th width = '33%'>
		<img src = 'images/greenbar.gif' width = '<?php echo $vars2['hpperc']; ?>' height = '10'>
		<img src = 'images/greybar.gif' width = '<?php echo $vars2['hpopp']; ?>' height = '10'></th>
</tr>
<tr>
<td colspan = '3' align = 'center'>
<?php

$_GET['wepid'] = (isset($_GET['wepid']) && is_numeric($_GET['wepid'])) ? abs(intval($_GET['wepid'])) : '';
if($_GET['wepid']) {
	$_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : 1;
	if($_SESSION['attacking'] == 0 && $ir['attacking'] == 0) {
		if($youdata['energy'] >= $youdata['maxenergy'] / 2) {
			$youdata['energy'] -= floor($youdata['maxenergy'] / 2);
			$cost = floor($youdata['maxenergy'] / 2);
			$db->query("UPDATE `users` SET `energy` = `energy` - {$cost} " . "WHERE `userid` = {$userid}");
			$_SESSION['attacklog'] = '';
			$_SESSION['attackdmg'] = 0;
		} else {
			cancelAttack("You can only attack someone when you have 50% energy.");
	}
}
	$_SESSION['attacking'] = 1;
	$ir['attacking']       = $odata['userid'];
	$db->query("UPDATE `users` SET `attacking` = {$ir['attacking']} WHERE `userid` = {$userid}");
	$_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : '';
	if($_GET['wepid'] != $ir['equip_primary'] && $_GET['wepid'] != $ir['equip_secondary']) {
		$db->query("UPDATE `users` SET `exp` = 0 WHERE `userid` = {$userid}");
		cancelAttack("Stop trying to abuse a game bug.");
	}
	$qo = $db->query("SELECT `itmname`, `weapon` FROM `items` WHERE `itmid` = {$_GET['wepid']} LIMIT 1");
	if($db->num_rows($qo) == 0) {
		cancelAttack("That weapon doesn not exist.");
	}
	$r1 = $db->fetch_row($qo);
	$db->free_result($qo);
	$mydamage = (int) (($r1['weapon'] * $youdata['strength'] / ($odata['guard'] / 1.5)) * (rand(8000, 12000) / 10000));
	$hitratio = max(10, min(60 * $ir['agility'] / $odata['agility'], 95));
	if(rand(1, 100) <= $hitratio) {
		if($odata['equip_armor'] > 0) {
			$q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$odata['equip_armor']} LIMIT 1");
			if($db->num_rows($q3) > 0)
				$mydamage -= $db->fetch_single($q3);
			$db->free_result($q3);
		}
		if($mydamage < -100000)
			$mydamage = abs($mydamage);
		else if($mydamage < 1)
			$mydamage = 1;
		$crit = rand(1, 40);
		if($crit == 17)
			$mydamage *= rand(20, 40) / 10;
		else if($crit == 25 OR $crit == 8)
			$mydamage /= (rand(20, 40) / 10);
		$mydamage = round($mydamage);
		$odata['hp'] -= $mydamage;
		if($odata['hp'] == 1) {
			$odata['hp'] = 0;
			$mydamage += 1;
		}
		$db->query("UPDATE `users` SET `hp` = `hp` - $mydamage WHERE `userid` = {$_GET['ID']}");
		?>

		<span style='color: red;'><?php echo $_GET['nextstep']; ?>. Using your <?php echo $r1['itmname']; ?> you hit <?php echo $odata['username']; ?> doing <?php echo $mydamage; ?> damage (<?php echo $odata['hp']; ?>)</span><br /><?php
		$_SESSION['attackdmg'] += $mydamage;
		$_SESSION['attacklog'] .= "<span style='color: red;'>{$_GET['nextstep']}. Using {$myabbr} {$r1['itmname']} {$ir['username']} hit {$odata['username']} doing $mydamage damage ({$odata['hp']})</span><br />";




	} else {
		?><span style='color: red;'><?php echo $_GET['nextstep']; ?>. You tried to hit <?php echo $odata['username']; ?> but missed (<?php echo $odata['hp']; ?>)</span><br /><?php
		$_SESSION['attacklog'] .= "<span style='color: red;'>{$_GET['nextstep']}. {$ir['username']} tried to hit {$odata['username']} but missed ({$odata['hp']})</span><br />";
	}
	if($odata['hp'] <= 0) {
		$odata['hp']           = 0;
		$_SESSION['attackwon'] = $_GET['ID'];
		$db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = {$_GET['ID']}");
		$db->query("UPDATE `users` SET `LWID` = {$_GET['ID']} WHERE `userid` = {$ir['userid']}");
		?><br />
<b>What do you want to do with <?php echo $odata['username']; ?> now?</b><br />
<form action='attackwon.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Mug Them' /></form>
<form action='attackbeat.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Hospitalize Them' /></form>
<form action='attacktake.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Leave Them' /></form><?php
	} else {
		$eq = $db->query("SELECT `itmname`,`weapon` FROM  `items` WHERE `itmid` IN({$odata['equip_primary']}, {$odata['equip_secondary']})");
		if($db->num_rows($eq) == 0) {
			$wep = "Fists";
			$dam = (int) ((((int) ($odata['strength'] / $ir['guard'] / 100)) + 1) * (rand(8000, 12000) / 10000));
		} else {
			$cnt = 0;
			while($r = $db->fetch_row($eq)) {
				$enweps[] = $r;
				++$cnt;
			}
			$db->free_result($eq);
            $weptouse = rand(0, $cnt - 1);
            $wep = $enweps[$weptouse]['itmname'];
            $dam = 
            		(int) (($enweps[$weptouse]['weapon'] * $odata['strength'] 
            				/ ($youdata['guard'] / 1.5)) 
            				* (rand(8000, 12000) / 10000));
		}
		$hitratio = max(10, min(60 * $odata['agility'] / $ir['agility'], 95));
		if(rand(1, 100) <= $hitratio) {
			if($ir['equip_armor'] > 0) {
				$q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$ir['equip_armor']} LIMIT 1");
				if($db->num_rows($q3) > 0)
					$dam -= $db->fetch_single($q3);
				$db->free_result($q3);
			}
			if($dam < -100000)
				$dam = abs($dam);
			else if($dam < 1)
				$dam = 1;
			$crit = rand(1, 40);
			if($crit == 17)
				$dam *= rand(20, 40) / 10;
			else if($crit == 25 OR $crit == 8)
				$dam /= (rand(20, 40) / 10);
			$dam = round($dam);
			$youdata['hp'] -= $dam;
			if($youdata['hp'] == 1) {
				$dam += 1;
				$youdata['hp'] = 0;
			}
			$db->query("UPDATE `users` SET `hp` = `hp` - $dam WHERE `userid` = $userid");
			$ns = $_GET['nextstep'] + 1;
			?><span style='color: blue;'><?php echo $ns; ?>. Using <?php echo $oabbr; ?> <?php echo $wep; ?> <?php echo $odata['username']; ?> hit you doing <?php echo $dam; ?> damage (<?php echo $youdata['hp']; ?>)</span><br /><?php

			$_SESSION['attacklog'] .= "<span style='color: blue;'>{$ns}. Using $oabbr $wep {$odata['username']} hit {$ir['username']} doing $dam damage ({$youdata['hp']})</span><br />";
		} else {
			$ns = $_GET['nextstep'] + 1;
			?><span style='color: blue;'><?php echo $ns; ?>. <?php echo $odata['username']; ?> tried to hit you but missed (<?php echo $youdata['hp']; ?>)</span><br /><?php
			$_SESSION['attacklog'] .= "<span style='color: blue;'>{$ns}. {$odata['username']} tried to hit {$ir['username']} but missed ({$youdata['hp']})</span><br />";
		}
		if($youdata['hp'] <= 0) {
			$youdata['hp']          = 0;
			$_SESSION['attacklost'] = 1;
			$db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = $userid");
			?><form action='attacklost.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Continue' /><?php
		}
	}
}	
?></td></tr></table><?php
$h->endpage();

 

Edited by Samurai Legend
Link to comment
Share on other sites

Check that the result of the guard / 1.5 is above 0 before using it as part of the equation

<?php
// Check that the user's guard is above 0 and get the guard division result, otherwise it's 0
$guardResult = $youdata['guard'] > 0 ? $youdata['guard'] / 1.5 : 0;
// Begin the damage calculation
$dam = $enweps[$weptouse]['weapon'] * $odata['strength'];
// If we've got something to divide by ..
if ($guardResult > 0) {
    // .. divide it
    $dam /= $guardResult;
}
// Add the randomisation back in
$dam *= rand(8000, 12000) / 10000;
// And cast it to an integer
$dam = (int)$dam;


/**
 * Original line for reference
 * $dam = (int) (($enweps[$weptouse]['weapon'] * $odata['strength'] / ($youdata['guard'] / 1.5)) * (rand(8000, 12000) / 10000));
 */

 

  • Like 1
Link to comment
Share on other sites

  • 5 months later...
On 3/3/2022 at 8:04 AM, Samurai Legend said:

Hello, I have fixed the issue. I forgot to echo out two statements on the links when attacking which was causing the error. However, now I am receiving the error only when the attacker is weaker than the person they are attacking. Can someone help me out on this as I have no clue on why it is throwing the error. 

Fatal error: Uncaught DivisionByZeroError: Division by zero in /attack.php:237 Stack trace: #0 /.composer/vendor/laravel/valet/server.php(235): require() #1 {main} thrown in /attack.php on line 237

Fatal error: Uncaught DivisionByZeroError: Division by zero in /attack.php:237 Stack trace: #0 /.composer/vendor/laravel/valet/server.php(235): require() #1 {main} thrown in /attack.php on line 237

 

Line 235 - 237

$dam = (int) (($enweps[$weptouse]['weapon'] * $odata['strength'] / ($youdata['guard'] / 1.5)) * (rand(8000, 12000) / 10000));

            $dam = 
            		(int) (($enweps[$weptouse]['weapon'] * $odata['strength'] 
            				/ ($youdata['guard'] / 1.5)) 
            				* (rand(8000, 12000) / 10000));

<?php define('PAGE_HEADER', 'Attacking'); $atkpage = 1; require('globals.php'); $rounds = 250; ?><h3><u>Attacking</u></h3><?php $_GET['ID'] = (isset($_GET['ID']) && is_numeric($_GET['ID'])) ? abs(intval($_GET['ID'])) : ''; $_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : '0'; $prohibited = array(1); //Add player IDs to this array that you don't want to get attacks. if(in_array($_GET['ID'], $prohibited)) { ?>You cannot attack this player.<br/> <a href = 'viewuser.php?u=<?php echo $_GET['ID']; ?>'>&gt; Go Back</a><br/> <a href = 'index.php'>&gt; Go Home</a><?php exit($h->endpage()); } if(!$_GET['ID']) { cancelAttack('Invalid ID.'); } if($_GET['ID'] == $userid) { cancelAttack('You can\'t attack yourself.'); } if($ir['hp'] <= 1) { cancelAttack('You\'re unconcious therefore you can\'t attack.'); } if(isset($_SESSION['attacklost']) && $_SESSION['attacklost'] == 1) { $_SESSION['attacklost'] = 0; cancelAttack('Only the losers of all their EXP attack when they\'ve already lost.'); } $youdata = $ir; $odata_sql = <<<SQL SELECT `u`.`userid`, `hp`, `hospital`, `prison`, `equip_armor`, `username`, `equip_primary`, `equip_secondary`, `clan`, `location`, `maxhp`, `guard`, `agility`, `strength`, `gender`, `display_pic`, `attacks_won` FROM `users` AS `u` INNER JOIN `userstats` AS `us` ON `u`.`userid` = `us`.`userid` WHERE `u`.`userid` = {$_GET['ID']} LIMIT 1 SQL; $q = $db->query($odata_sql); if($db->num_rows($q) == 0) { cancelAttack('That user does not exist.'); } $odata = $db->fetch_row($q); $db->free_result($q); $myabbr = ($ir['gender'] == 'Male') ? 'his' : 'her'; $oabbr = ($odata['gender'] == 'Male') ? 'his' : 'her'; if($ir['attacking'] && $ir['attacking'] != $_GET['ID']) { $_SESSION['attacklost'] = 0; cancelAttack('Something went wrong.'); } if($odata['hp'] == 1) { cancelAttack('This player is unconscious.'); } if($odata['hospital']) { cancelAttack('This player is in hospital.'); } if($ir['hospital']) { cancelAttack('While in hospital you can\'t attack.'); } if($odata['prison']) { cancelAttack('This player is in prison.'); } if($ir['prison']) { cancelAttack('While in prison you can\'t attack.'); } if($odata['hp'] < 5) { cancelAttack('You can only attack those who have health.'); } else if($ir['clan'] == $odata['clan'] && $ir['clan'] > 0) { cancelAttack("You are in the same clan as {$odata['username']}!"); } else if($youdata['energy'] < $youdata['maxenergy'] / 2) { cancelAttack('You can only attack someone when you have 50% energy.'); } else if($youdata['location'] != $odata['location']) { cancelAttack('You can only attack someone in the same location!'); } if($_GET['nextstep'] > $rounds) { cancelAttack('You both have become tired and called it a draw. You have been sent home.'); } $userdp = ($ir['display_pic']) ? '<img src = "' . $ir['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />'; $odp = ($odata['display_pic']) ? '<img src = "' . $odata['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />'; ?><hr width = '100%'> <table width = '100%' cellpadding = '1' cellspacing = '1' class = 'table'> <tr> <th width = '33%'><?php echo $ir['username']; ?></th> <th width = '33%'>VS</th> <th width = '33%'><?php echo username($odata['userid']); ?></th> </tr> <tr> <th width = '33%'><?php echo $userdp; ?><br/>Attacks Won: <?php echo $ir['attacks_won']; ?></th> <th width = '33%'><?php $mw = $db->query("SELECT `itmid`,`itmname` FROM `items` WHERE `itmid` IN({$ir['equip_primary']}, {$ir['equip_secondary']})"); ?>Attack with:<br /><?php if($db->num_rows($mw) > 0) { while($r = $db->fetch_row($mw)) { $ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2; if($r['itmid'] == $ir['equip_primary']) { ?><b>Primary Weapon:</b><?php ?><a href='attack.php?nextstep=<?php echo $ns; ?>&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php } if($r['itmid'] == $ir['equip_secondary']) { ?><b>Secondary Weapon:</b><?php ?><a href='attack.php?nextstep=<?php echo $ns; ?>&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php } } } else { ?>You have nothing to fight with.<?php } $db->free_result($mw); $vars['hpperc'] = round($youdata['hp'] / $youdata['maxhp'] * 100); $vars['hpopp'] = 100 - $vars['hpperc']; $vars2['hpperc'] = round($odata['hp'] / $odata['maxhp'] * 100); $vars2['hpopp'] = 100 - $vars2['hpperc']; ?></th> <th width = '33%'><?php echo $odp; ?><br/>Attacks Won: <?php echo $odata['attacks_won']; ?></th> </tr> <tr> <th width = '33%'> <img src = 'images/greenbar.gif' width = '<?php echo $vars['hpperc']; ?>' height = '10'> <img src= 'images/greybar.gif' width = '<?php echo $vars['hpopp']; ?>' height = '10'></th> <th>&nbsp;</th> <th width = '33%'> <img src = 'images/greenbar.gif' width = '<?php echo $vars2['hpperc']; ?>' height = '10'> <img src = 'images/greybar.gif' width = '<?php echo $vars2['hpopp']; ?>' height = '10'></th> </tr> <tr> <td colspan = '3' align = 'center'> <?php $_GET['wepid'] = (isset($_GET['wepid']) && is_numeric($_GET['wepid'])) ? abs(intval($_GET['wepid'])) : ''; if($_GET['wepid']) { $_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : 1; if($_SESSION['attacking'] == 0 && $ir['attacking'] == 0) { if($youdata['energy'] >= $youdata['maxenergy'] / 2) { $youdata['energy'] -= floor($youdata['maxenergy'] / 2); $cost = floor($youdata['maxenergy'] / 2); $db->query("UPDATE `users` SET `energy` = `energy` - {$cost} " . "WHERE `userid` = {$userid}"); $_SESSION['attacklog'] = ''; $_SESSION['attackdmg'] = 0; } else { cancelAttack("You can only attack someone when you have 50% energy."); } } $_SESSION['attacking'] = 1; $ir['attacking'] = $odata['userid']; $db->query("UPDATE `users` SET `attacking` = {$ir['attacking']} WHERE `userid` = {$userid}"); $_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : ''; if($_GET['wepid'] != $ir['equip_primary'] && $_GET['wepid'] != $ir['equip_secondary']) { $db->query("UPDATE `users` SET `exp` = 0 WHERE `userid` = {$userid}"); cancelAttack("Stop trying to abuse a game bug."); } $qo = $db->query("SELECT `itmname`, `weapon` FROM `items` WHERE `itmid` = {$_GET['wepid']} LIMIT 1"); if($db->num_rows($qo) == 0) { cancelAttack("That weapon doesn not exist."); } $r1 = $db->fetch_row($qo); $db->free_result($qo); $mydamage = (int) (($r1['weapon'] * $youdata['strength'] / ($odata['guard'] / 1.5)) * (rand(8000, 12000) / 10000)); $hitratio = max(10, min(60 * $ir['agility'] / $odata['agility'], 95)); if(rand(1, 100) <= $hitratio) { if($odata['equip_armor'] > 0) { $q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$odata['equip_armor']} LIMIT 1"); if($db->num_rows($q3) > 0) $mydamage -= $db->fetch_single($q3); $db->free_result($q3); } if($mydamage < -100000) $mydamage = abs($mydamage); else if($mydamage < 1) $mydamage = 1; $crit = rand(1, 40); if($crit == 17) $mydamage *= rand(20, 40) / 10; else if($crit == 25 OR $crit == 8) $mydamage /= (rand(20, 40) / 10); $mydamage = round($mydamage); $odata['hp'] -= $mydamage; if($odata['hp'] == 1) { $odata['hp'] = 0; $mydamage += 1; } $db->query("UPDATE `users` SET `hp` = `hp` - $mydamage WHERE `userid` = {$_GET['ID']}"); ?> <span style='color: red;'><?php echo $_GET['nextstep']; ?>. Using your <?php echo $r1['itmname']; ?> you hit <?php echo $odata['username']; ?> doing <?php echo $mydamage; ?> damage (<?php echo $odata['hp']; ?>)</span><br /><?php $_SESSION['attackdmg'] += $mydamage; $_SESSION['attacklog'] .= "<span style='color: red;'>{$_GET['nextstep']}. Using {$myabbr} {$r1['itmname']} {$ir['username']} hit {$odata['username']} doing $mydamage damage ({$odata['hp']})</span><br />"; } else { ?><span style='color: red;'><?php echo $_GET['nextstep']; ?>. You tried to hit <?php echo $odata['username']; ?> but missed (<?php echo $odata['hp']; ?>)</span><br /><?php $_SESSION['attacklog'] .= "<span style='color: red;'>{$_GET['nextstep']}. {$ir['username']} tried to hit {$odata['username']} but missed ({$odata['hp']})</span><br />"; } if($odata['hp'] <= 0) { $odata['hp'] = 0; $_SESSION['attackwon'] = $_GET['ID']; $db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = {$_GET['ID']}"); $db->query("UPDATE `users` SET `LWID` = {$_GET['ID']} WHERE `userid` = {$ir['userid']}"); ?><br /> <b>What do you want to do with <?php echo $odata['username']; ?> now?</b><br /> <form action='attackwon.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Mug Them' /></form> <form action='attackbeat.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Hospitalize Them' /></form> <form action='attacktake.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Leave Them' /></form><?php } else { $eq = $db->query("SELECT `itmname`,`weapon` FROM `items` WHERE `itmid` IN({$odata['equip_primary']}, {$odata['equip_secondary']})"); if($db->num_rows($eq) == 0) { $wep = "Fists"; $dam = (int) ((((int) ($odata['strength'] / $ir['guard'] / 100)) + 1) * (rand(8000, 12000) / 10000)); } else { $cnt = 0; while($r = $db->fetch_row($eq)) { $enweps[] = $r; ++$cnt; } $db->free_result($eq); $weptouse = rand(0, $cnt - 1); $wep = $enweps[$weptouse]['itmname']; $dam = (int) (($enweps[$weptouse]['weapon'] * $odata['strength'] / ($youdata['guard'] / 1.5)) * (rand(8000, 12000) / 10000)); } $hitratio = max(10, min(60 * $odata['agility'] / $ir['agility'], 95)); if(rand(1, 100) <= $hitratio) { if($ir['equip_armor'] > 0) { $q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$ir['equip_armor']} LIMIT 1"); if($db->num_rows($q3) > 0) $dam -= $db->fetch_single($q3); $db->free_result($q3); } if($dam < -100000) $dam = abs($dam); else if($dam < 1) $dam = 1; $crit = rand(1, 40); if($crit == 17) $dam *= rand(20, 40) / 10; else if($crit == 25 OR $crit == 8) $dam /= (rand(20, 40) / 10); $dam = round($dam); $youdata['hp'] -= $dam; if($youdata['hp'] == 1) { $dam += 1; $youdata['hp'] = 0; } $db->query("UPDATE `users` SET `hp` = `hp` - $dam WHERE `userid` = $userid"); $ns = $_GET['nextstep'] + 1; ?><span style='color: blue;'><?php echo $ns; ?>. Using <?php echo $oabbr; ?> <?php echo $wep; ?> <?php echo $odata['username']; ?> hit you doing <?php echo $dam; ?> damage (<?php echo $youdata['hp']; ?>)</span><br /><?php $_SESSION['attacklog'] .= "<span style='color: blue;'>{$ns}. Using $oabbr $wep {$odata['username']} hit {$ir['username']} doing $dam damage ({$youdata['hp']})</span><br />"; } else { $ns = $_GET['nextstep'] + 1; ?><span style='color: blue;'><?php echo $ns; ?>. <?php echo $odata['username']; ?> tried to hit you but missed (<?php echo $youdata['hp']; ?>)</span><br /><?php $_SESSION['attacklog'] .= "<span style='color: blue;'>{$ns}. {$odata['username']} tried to hit {$ir['username']} but missed ({$youdata['hp']})</span><br />"; } if($youdata['hp'] <= 0) { $youdata['hp'] = 0; $_SESSION['attacklost'] = 1; $db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = $userid"); ?><form action='attacklost.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Continue' /><?php } } } ?></td></tr></table><?php $h->endpage();

<?php
define('PAGE_HEADER', 'Attacking');
$atkpage = 1;
require('globals.php');
$rounds = 250;

?><h3><u>Attacking</u></h3><?php

$_GET['ID'] = (isset($_GET['ID']) 
			&& is_numeric($_GET['ID'])) 
			? abs(intval($_GET['ID'])) : '';

$_GET['nextstep'] = (isset($_GET['nextstep']) 
            && is_numeric($_GET['nextstep'])) 
            ? abs(intval($_GET['nextstep'])) : '0';

$prohibited = array(1); //Add player IDs to this array that you don't want to get attacks.

if(in_array($_GET['ID'], $prohibited)) {
    ?>You cannot attack this player.<br/>
    <a href = 'viewuser.php?u=<?php echo $_GET['ID']; ?>'>&gt; Go Back</a><br/>
    <a href = 'index.php'>&gt; Go Home</a><?php
    exit($h->endpage());
}
if(!$_GET['ID']) {
	cancelAttack('Invalid ID.');
}
if($_GET['ID'] == $userid) {
	cancelAttack('You can\'t attack yourself.');
}	
if($ir['hp'] <= 1) {
	cancelAttack('You\'re unconcious therefore you can\'t attack.');
}
if(isset($_SESSION['attacklost']) && $_SESSION['attacklost'] == 1) {
	$_SESSION['attacklost'] = 0;
	cancelAttack('Only the losers of all their EXP attack when they\'ve already lost.');
}
$youdata   = $ir;
$odata_sql = <<<SQL
	SELECT `u`.`userid`, `hp`, `hospital`, `prison`, `equip_armor`, `username`,
	`equip_primary`, `equip_secondary`, `clan`, `location`, `maxhp`,
	`guard`, `agility`, `strength`, `gender`, `display_pic`, `attacks_won`
	FROM `users` AS `u`
	INNER JOIN `userstats` AS `us` ON `u`.`userid` = `us`.`userid`
	WHERE `u`.`userid` = {$_GET['ID']}
	LIMIT 1
SQL;
$q = $db->query($odata_sql);
if($db->num_rows($q) == 0) {
	cancelAttack('That user does not exist.');
}
$odata = $db->fetch_row($q);
$db->free_result($q);
$myabbr = ($ir['gender'] == 'Male') ? 'his' : 'her';
$oabbr  = ($odata['gender'] == 'Male') ? 'his' : 'her';
if($ir['attacking'] && $ir['attacking'] != $_GET['ID']) {
	$_SESSION['attacklost'] = 0;
	cancelAttack('Something went wrong.');
}
if($odata['hp'] == 1) {
	cancelAttack('This player is unconscious.');
}
if($odata['hospital']) {
	cancelAttack('This player is in hospital.');
}
if($ir['hospital']) {
	cancelAttack('While in hospital you can\'t attack.');
}
if($odata['prison']) {
	cancelAttack('This player is in prison.');
}
if($ir['prison']) {
	cancelAttack('While in prison you can\'t attack.');
}
if($odata['hp'] < 5) {
	cancelAttack('You can only attack those who have health.');
} else if($ir['clan'] == $odata['clan'] && $ir['clan'] > 0) {
	cancelAttack("You are in the same clan as {$odata['username']}!");
} else if($youdata['energy'] < $youdata['maxenergy'] / 2) {
	cancelAttack('You can only attack someone when you have 50% energy.');
} else if($youdata['location'] != $odata['location']) {
	cancelAttack('You can only attack someone in the same location!');
}
if($_GET['nextstep'] > $rounds) {
	cancelAttack('You both have become tired and called it a draw. You have been sent home.');
}


$userdp = ($ir['display_pic']) 
? '<img src = "' . $ir['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />';

$odp = ($odata['display_pic']) 
? '<img src = "' . $odata['display_pic'] . '" width = "150px" height = "150px" alt = "User Display Pic" title = "User Display Pic" />' : '<img src = "images/default_dp.png" width = "150px" height = "150px" alt = "No Avatar" title = "No Avatar" />';

?><hr width = '100%'>
<table width = '100%' cellpadding = '1' cellspacing = '1' class = 'table'>
<tr>
	<th width = '33%'><?php echo $ir['username']; ?></th>
	<th width = '33%'>VS</th>
	<th width = '33%'><?php echo username($odata['userid']); ?></th>
</tr>
<tr>
	<th width = '33%'><?php echo $userdp; ?><br/>Attacks Won: <?php echo $ir['attacks_won']; ?></th>
	<th width = '33%'><?php
$mw = $db->query("SELECT `itmid`,`itmname` FROM  `items`  WHERE `itmid` IN({$ir['equip_primary']}, {$ir['equip_secondary']})");
	?>Attack with:<br /><?php
if($db->num_rows($mw) > 0) {
	while($r = $db->fetch_row($mw)) {
		$ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;
		if($r['itmid'] == $ir['equip_primary']) {
			?><b>Primary Weapon:</b><?php
			?><a href='attack.php?nextstep=<?php echo $ns; ?>&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php
		}
		if($r['itmid'] == $ir['equip_secondary']) {
			?><b>Secondary Weapon:</b><?php
			?><a href='attack.php?nextstep=<?php echo $ns; ?>&amp;ID=<?php echo $_GET['ID']; ?>&amp;wepid=<?php echo $r['itmid']; ?>'> <?php echo $r['itmname']; ?></a><br /><?php
		}
	}
} else {
	?>You have nothing to fight with.<?php
}
$db->free_result($mw);
$vars['hpperc']  = round($youdata['hp'] / $youdata['maxhp'] * 100);
$vars['hpopp']   = 100 - $vars['hpperc'];
$vars2['hpperc'] = round($odata['hp'] / $odata['maxhp'] * 100);
$vars2['hpopp']  = 100 - $vars2['hpperc'];

?></th>
	<th width = '33%'><?php echo $odp; ?><br/>Attacks Won: <?php echo $odata['attacks_won']; ?></th>
</tr>

<tr>
	<th width = '33%'>
		<img src = 'images/greenbar.gif' width = '<?php echo $vars['hpperc']; ?>'	 height = '10'>
		<img src= 'images/greybar.gif' width = '<?php echo $vars['hpopp']; ?>' height = '10'></th>
		<th>&nbsp;</th>
	<th width = '33%'>
		<img src = 'images/greenbar.gif' width = '<?php echo $vars2['hpperc']; ?>' height = '10'>
		<img src = 'images/greybar.gif' width = '<?php echo $vars2['hpopp']; ?>' height = '10'></th>
</tr>
<tr>
<td colspan = '3' align = 'center'>
<?php

$_GET['wepid'] = (isset($_GET['wepid']) && is_numeric($_GET['wepid'])) ? abs(intval($_GET['wepid'])) : '';
if($_GET['wepid']) {
	$_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : 1;
	if($_SESSION['attacking'] == 0 && $ir['attacking'] == 0) {
		if($youdata['energy'] >= $youdata['maxenergy'] / 2) {
			$youdata['energy'] -= floor($youdata['maxenergy'] / 2);
			$cost = floor($youdata['maxenergy'] / 2);
			$db->query("UPDATE `users` SET `energy` = `energy` - {$cost} " . "WHERE `userid` = {$userid}");
			$_SESSION['attacklog'] = '';
			$_SESSION['attackdmg'] = 0;
		} else {
			cancelAttack("You can only attack someone when you have 50% energy.");
	}
}
	$_SESSION['attacking'] = 1;
	$ir['attacking']       = $odata['userid'];
	$db->query("UPDATE `users` SET `attacking` = {$ir['attacking']} WHERE `userid` = {$userid}");
	$_GET['nextstep'] = (isset($_GET['nextstep']) && is_numeric($_GET['nextstep'])) ? abs(intval($_GET['nextstep'])) : '';
	if($_GET['wepid'] != $ir['equip_primary'] && $_GET['wepid'] != $ir['equip_secondary']) {
		$db->query("UPDATE `users` SET `exp` = 0 WHERE `userid` = {$userid}");
		cancelAttack("Stop trying to abuse a game bug.");
	}
	$qo = $db->query("SELECT `itmname`, `weapon` FROM `items` WHERE `itmid` = {$_GET['wepid']} LIMIT 1");
	if($db->num_rows($qo) == 0) {
		cancelAttack("That weapon doesn not exist.");
	}
	$r1 = $db->fetch_row($qo);
	$db->free_result($qo);
	$mydamage = (int) (($r1['weapon'] * $youdata['strength'] / ($odata['guard'] / 1.5)) * (rand(8000, 12000) / 10000));
	$hitratio = max(10, min(60 * $ir['agility'] / $odata['agility'], 95));
	if(rand(1, 100) <= $hitratio) {
		if($odata['equip_armor'] > 0) {
			$q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$odata['equip_armor']} LIMIT 1");
			if($db->num_rows($q3) > 0)
				$mydamage -= $db->fetch_single($q3);
			$db->free_result($q3);
		}
		if($mydamage < -100000)
			$mydamage = abs($mydamage);
		else if($mydamage < 1)
			$mydamage = 1;
		$crit = rand(1, 40);
		if($crit == 17)
			$mydamage *= rand(20, 40) / 10;
		else if($crit == 25 OR $crit == 8)
			$mydamage /= (rand(20, 40) / 10);
		$mydamage = round($mydamage);
		$odata['hp'] -= $mydamage;
		if($odata['hp'] == 1) {
			$odata['hp'] = 0;
			$mydamage += 1;
		}
		$db->query("UPDATE `users` SET `hp` = `hp` - $mydamage WHERE `userid` = {$_GET['ID']}");
		?>

		<span style='color: red;'><?php echo $_GET['nextstep']; ?>. Using your <?php echo $r1['itmname']; ?> you hit <?php echo $odata['username']; ?> doing <?php echo $mydamage; ?> damage (<?php echo $odata['hp']; ?>)</span><br /><?php
		$_SESSION['attackdmg'] += $mydamage;
		$_SESSION['attacklog'] .= "<span style='color: red;'>{$_GET['nextstep']}. Using {$myabbr} {$r1['itmname']} {$ir['username']} hit {$odata['username']} doing $mydamage damage ({$odata['hp']})</span><br />";




	} else {
		?><span style='color: red;'><?php echo $_GET['nextstep']; ?>. You tried to hit <?php echo $odata['username']; ?> but missed (<?php echo $odata['hp']; ?>)</span><br /><?php
		$_SESSION['attacklog'] .= "<span style='color: red;'>{$_GET['nextstep']}. {$ir['username']} tried to hit {$odata['username']} but missed ({$odata['hp']})</span><br />";
	}
	if($odata['hp'] <= 0) {
		$odata['hp']           = 0;
		$_SESSION['attackwon'] = $_GET['ID'];
		$db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = {$_GET['ID']}");
		$db->query("UPDATE `users` SET `LWID` = {$_GET['ID']} WHERE `userid` = {$ir['userid']}");
		?><br />
<b>What do you want to do with <?php echo $odata['username']; ?> now?</b><br />
<form action='attackwon.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Mug Them' /></form>
<form action='attackbeat.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Hospitalize Them' /></form>
<form action='attacktake.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Leave Them' /></form><?php
	} else {
		$eq = $db->query("SELECT `itmname`,`weapon` FROM  `items` WHERE `itmid` IN({$odata['equip_primary']}, {$odata['equip_secondary']})");
		if($db->num_rows($eq) == 0) {
			$wep = "Fists";
			$dam = (int) ((((int) ($odata['strength'] / $ir['guard'] / 100)) + 1) * (rand(8000, 12000) / 10000));
		} else {
			$cnt = 0;
			while($r = $db->fetch_row($eq)) {
				$enweps[] = $r;
				++$cnt;
			}
			$db->free_result($eq);
            $weptouse = rand(0, $cnt - 1);
            $wep = $enweps[$weptouse]['itmname'];
            $dam = 
            		(int) (($enweps[$weptouse]['weapon'] * $odata['strength'] 
            				/ ($youdata['guard'] / 1.5)) 
            				* (rand(8000, 12000) / 10000));
		}
		$hitratio = max(10, min(60 * $odata['agility'] / $ir['agility'], 95));
		if(rand(1, 100) <= $hitratio) {
			if($ir['equip_armor'] > 0) {
				$q3 = $db->query("SELECT `armor` FROM `items` WHERE `itmid` = {$ir['equip_armor']} LIMIT 1");
				if($db->num_rows($q3) > 0)
					$dam -= $db->fetch_single($q3);
				$db->free_result($q3);
			}
			if($dam < -100000)
				$dam = abs($dam);
			else if($dam < 1)
				$dam = 1;
			$crit = rand(1, 40);
			if($crit == 17)
				$dam *= rand(20, 40) / 10;
			else if($crit == 25 OR $crit == 8)
				$dam /= (rand(20, 40) / 10);
			$dam = round($dam);
			$youdata['hp'] -= $dam;
			if($youdata['hp'] == 1) {
				$dam += 1;
				$youdata['hp'] = 0;
			}
			$db->query("UPDATE `users` SET `hp` = `hp` - $dam WHERE `userid` = $userid");
			$ns = $_GET['nextstep'] + 1;
			?><span style='color: blue;'><?php echo $ns; ?>. Using <?php echo $oabbr; ?> <?php echo $wep; ?> <?php echo $odata['username']; ?> hit you doing <?php echo $dam; ?> damage (<?php echo $youdata['hp']; ?>)</span><br /><?php

			$_SESSION['attacklog'] .= "<span style='color: blue;'>{$ns}. Using $oabbr $wep {$odata['username']} hit {$ir['username']} doing $dam damage ({$youdata['hp']})</span><br />";
		} else {
			$ns = $_GET['nextstep'] + 1;
			?><span style='color: blue;'><?php echo $ns; ?>. <?php echo $odata['username']; ?> tried to hit you but missed (<?php echo $youdata['hp']; ?>)</span><br /><?php
			$_SESSION['attacklog'] .= "<span style='color: blue;'>{$ns}. {$odata['username']} tried to hit {$ir['username']} but missed ({$youdata['hp']})</span><br />";
		}
		if($youdata['hp'] <= 0) {
			$youdata['hp']          = 0;
			$_SESSION['attacklost'] = 1;
			$db->query("UPDATE `users` SET `hp` = 0 WHERE `userid` = $userid");
			?><form action='attacklost.php?ID=<?php echo $_GET['ID']; ?>' method='post'><input type='submit' value='Continue' /><?php
		}
	}
}	
?></td></tr></table><?php
$h->endpage();

 

very bad code

<?php
 
namespace App\Http\Controllers;
 
use App\Models\{ AttackLog, User, Item, UserDetail,  UserSlot, UserStats, WeaponAttribute};
use Carbon\Carbon;
use Illuminate\Http\Request;
 
class AttacksController extends Controller
{
 
    /**
     * The attributes that are assignable.
     *
     * @var
     */
    protected  $attacker,
               $defender,
               $userDetails,
               $userStats,
               $weaponAttributes,
               $userSlots,
               $attackLog,
               $items,
               $hitresult,
               $carbon;
 
    /**
     * Instantiate a new AttacksController instance.
     */
    public function __construct(){
        $this->middleware(function ($request, $next) {
            $this->attacker = auth()->user();
        return $next($request);
        });
 
        $this->userDetails = new UserDetail();
        $this->userStats = new UserStats();
        $this->items = new Item();
        $this->weaponAttributes = new WeaponAttribute();
        $this->userSlots = new UserSlot();
        $this->attackLog = new AttackLog();
        $this->items = new Item();
        $this->carbon = new Carbon();
    }
 
    /**
     * invoke for attack
     * @param  Request $request, User $defender
     * @return \Illuminate\Http\Response player.attack with $array
     */
     public function __invoke(Request $request, User $defender) {
        $this->defender = $defender;
        return view('player.attack', [
             'attacker' => $this->attacker,
             'defender' => $this->defender,
             'defenderEquipped' => $this->equippedWeapons($this->defender->id),
             'attackerEquipped' => $this->equippedWeapons($this->attacker->id)
        ]);
     }
 
    /**
     * both player preparation for an Attack
     * @param  Request $request
     * @return \Illuminate\Http\Response $array
     */
    public function preparationForAttack($request) {
        $this->canAttack();
        $nextTurnAssignment = $this->turn();
        // dd($nextTurnAssignment);
        if((int)$nextTurnAssignment === 1)
        {
            $this->consumeEnergy($this->attacker->id);
        }
 
        $turnOwner = $this->doTurn($nextTurnAssignment);
        $selectedAttackerWeapon = $this->selectedWeaponName($this->attacker->id, $request->weaponId );
        $defenderWeaponId = $this->equippedWeapons($this->defender->id);
        $selectedDefenderWeapon = $this->selectedWeaponName($this->defender->id, $defenderWeaponId['primaryWeaponId']);
        $selectedAttackerWeaponAttributes = $this->equippedWeaponAttributes($request->weaponId);
        $selectedDefenderWeaponAttributes = $this->equippedWeaponAttributes($defenderWeaponId['primaryWeaponId']);
        $attackerStats = $this->getFightStats($this->attacker->id);
        $defenderStats = $this->getFightStats($this->defender->id);
        return [
            'turnNumber' => $nextTurnAssignment,
            'turnOwner' => $turnOwner,
            'attackerStats' => $attackerStats,
            'defenderStats' => $defenderStats,
            'selectedAttackerWeapon' => $selectedAttackerWeapon,
            'selectedDefenderWeapon' =>   $selectedDefenderWeapon,
            'selectedAttackerWeaponAttributes' => $selectedAttackerWeaponAttributes,
            'selectedDefenderWeaponAttributes' => $selectedDefenderWeaponAttributes
        ];
    }
 
    /**
     * attack preformance responsible
     * @param  Request $request, User $defender
     * @return \Illuminate\Http\Response $method
     */
    public function attack(Request $request, User $defender) {
        $this->defender = $defender;
        $preparedForAttack = $this->preparationForAttack($request);
        $singleHitResult = $this->attackPerform($preparedForAttack);
        $this->hitresult .= $singleHitResult;
    return $singleHitResult;
    }
 
    /**
     * generate attack step event
     * @param  $preparedForAttack, $damage
     * @return \Illuminate\Http\Response string
     */
    public function generateAttackStepEvent($preparedForAttack, $damage = 'missed') {
        $weaponName =  ($preparedForAttack['turnNumber'] % 2) ? $preparedForAttack['selectedDefenderWeapon'] : $preparedForAttack['selectedAttackerWeapon'];
        return [
            'turnNumber' => $preparedForAttack['turnNumber'],
            'message' => $preparedForAttack['turnNumber'] . " " . $preparedForAttack['turnOwner'] . " " . $weaponName . " " . $damage . " " . date('Y-m-d H:i:s')
        ] ;
    }
 
    /**
     * consume the energy for attack
     * @param  $userId
     * @return \Illuminate\Http\Response string
     */
    public function consumeEnergy($userId) {
        $consumeEnergyValue  = (int) ($this->userStats->getMaxEnergy($userId) / 3);
        $this->userStats->decrementEnergy($userId, $consumeEnergyValue);
    }
 
    /**
     * add attack log in storage                                                    \
     * @param
     * @return \Illuminate\Http\Response boolean
     */
    public function attackLog($hitResult) {
        return $this->attackLog->addLog($hitResult);
    }
 
    /**
     * cheack the eligibility for attack of both player
     * @param
     * @return \Illuminate\Http\Response throw expection
     */
    public function canAttack() {
        // dd($this->defender);
        $haveEnergy = (int) $this->userStats->getEnergy($this->defender->id) < (int) ($this->userStats->getMaxEnergy($this->defender->id)/2);
        $notSameLocation = $this->userDetails->getLocation($this->defender->id) !== $this->userDetails->getLocation($this->attacker->id);
        $defenderHospitalized = $this->userDetails->getHospitalTime($this->defender->id);
        $defenderJailed = $this->userDetails->getJailTime($this->defender->id);
        $selfAttack = $this->defender->id === $this->attacker->id;
 
        if ($selfAttack) {
            abort(403, "You can't attack yourself.");
        }elseif($haveEnergy) {
            abort(403, "You don't have enough energy.");
        } elseif ($notSameLocation) {
            abort(403, "Player isn't on same location.");
        } elseif ($defenderHospitalized) {
            abort(403, "Player already is hospitalized.");
        } elseif ($defenderJailed) {
            abort(403, "Player already is Jailed.");
        }
    }
 
    /**
     * turn creator for attack
     * @param
     * @return \Illuminate\Http\Response session
     */
    public function turn() {
        $turn = session('oldTurnNumber', 0);
        $countturn = $turn+1;
        session()->put('oldTurnNumber', $countturn);
    return $countturn;
    }
 
    /**
     * assign the turn to players for attack
     * @param $nextTurnAssignment
     * @return \Illuminate\Http\Response string
     */
    public function doTurn($nextTurnAssignment) {
 
        if($nextTurnAssignment%2 == 0)
        {
            return $this->defender->name;
        }
 
    return $this->attacker->name;
    }
 
    /**
     * attack performer
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response string or JSON
     */
    public function attackPerform($preparedForAttack){
        $userId = ($preparedForAttack['turnNumber'] % 2) ? $this->defender->id : $this->attacker->id;
 
        if($this->isChanceSuccess($preparedForAttack))
        {
            $damageCalculation = $this->damageCalculation($preparedForAttack);
            $this->doHPDown($userId, $damageCalculation);
            $isrHpDown = $this->isHP($userId);
 
            if($isrHpDown <= 0)
            {
                $attacker = ['attackerId' => $this->attacker->id];
                $defender = ['defenderId' => $this->defender->id];
                $userData = ($userId === $this->attacker->id)? $attacker: $defender;
            return response()->json([$userData]);
            }
 
        return $this->generateAttackStepEvent($preparedForAttack, $damageCalculation)['message'];
        }
 
    return $this->generateAttackStepEvent($preparedForAttack)['message'];
    }
 
    /**
     * defender hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function hospitalize($userId) {
        $number = mt_rand(1,5);
        $duration = $this->carbon->now()->addHours($number);
        session()->forget('oldTurnNumber');
    return $this->userDetails->addHospitalTime($userId, $duration);
    }
 
    /**
     * defender hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function settlement($userId)
    {
        $number = mt_rand(1, 5);
        $duration = $this->carbon->now()->addHours($number);
        $this->hitresult['message'] .= "You successfully done settlement";
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult);
    }
 
    /**
     * runway in between the attack
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function runaway($userId)
    {
        $number = mt_rand(1, 5);
        $message = "You successfully managed runaway";
 
        if($number === 3)
        {
            $duration = $this->carbon->now()->addHours($number);
            $this->userDetails->addHospitalTime($userId, $duration);
            $message = "You failed to manage the runaway";
        }
 
        $this->hitresult['message'] .= $message;
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult);
    }
 
    /**
     * defender  hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function leave($userId) {
        $number = mt_rand(20,30);
        $duration = $this->carbon->now()->addMinutes($number);
        $this->userDetails->addHospitalTime($userId, $duration);
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult['message']);
    }
 
    /**
     * defender  hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function mug($userId) {
        $number = mt_rand(20, 25);
        $duration = $this->carbon->now()->addMinutes($number);
        $this->userDetails->addHospitalTime($userId, $duration);
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult['message']);
    }
 
    /**
     * attacker hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function lost($userId) {
        $number = mt_rand(10, 20);
        $duration = $this->carbon->now()->addMinutes($number);
        $this->userDetails->addHospitalTime($userId, $duration);
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult['message']);
    }
 
    /**
     * equipped weapons of both players for attack
     * @param $userId
     * @return \Illuminate\Http\Response array
     */
    public function equippedWeapons($userId) {
        $weapons = $this->userSlots->getUserWeaponsById($userId);
        $primaryWeaponName = $this->items->getWeaponNameById($weapons->primary_slot);
        $secondaryWeaponName = $this->items->getWeaponNameById($weapons->secondary_slot);
        return [
            'primaryWeaponId' => $weapons->primary_slot,
            'primaryWeaponName' => $primaryWeaponName,
            'secondaryWeaponId' => $weapons->secondary_slot,
            'secondaryWeaponName' => $secondaryWeaponName
        ];
    }
 
    /**
     * hitting chance of attacker
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response boolean
     */
    public function isChanceSuccess($preparedForAttack) {
        $genrateRandom = mt_rand(1, 100);
        $hitRatio = (int) $this->hitRatio($preparedForAttack);
    return $genrateRandom <= (int) $hitRatio;
    }
 
    /**
     * decrement the HP of loser of hit in attack
     * @param $userId, $damageCalculation
     * @return \Illuminate\Http\Response boolean
     */
    public function doHPDown($userId, $damageCalculation) {
        return $this->userStats->decrementHP($userId, $damageCalculation);
    }
 
    /**
     * select weapon for attack by both player for attack
     * @param $userId, $weaponId
     * @return \Illuminate\Http\Response boolean or throw expection
     */
    public function selectedWeaponName($userId, $weaponId) {
        $weapons = $this->equippedWeapons($userId);
        $correctWeaponSelected = (int) $weapons['primaryWeaponId']  === (int) $weaponId || (int) $weapons['secondaryWeaponId']  === (int) $weaponId;
 
        if($correctWeaponSelected){
            return $this->items->getWeaponNameById($weaponId);
        }
 
    abort(403, "This weapon isn't selectable");
    }
 
    /**
     * as per weapon selection get attributes of weapon
     * @param $itemId
     * @return \Illuminate\Http\Response array
     */
    public function equippedWeaponAttributes($itemId) {
        $weaponAtrributeId = $this->items->getItemAttributeById($itemId);
    return $this->weaponAttributes->getattributesById($weaponAtrributeId);
    }
 
    /**
     * calculation of damage
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response int
     */
    public function damageCalculation($preparedForAttack) {
 
        if ($preparedForAttack['turnNumber'] % 2)
        {
            return (int) ($preparedForAttack['selectedDefenderWeaponAttributes']['damage'] * $preparedForAttack['defenderStats']['strength'] /
                $preparedForAttack['attackerStats']['defense']) * (rand(8000, 12000) / 10000);
        }
 
    return (int) ($preparedForAttack['selectedAttackerWeaponAttributes']['damage'] * $preparedForAttack['attackerStats']['strength'] /
        $preparedForAttack['defenderStats']['defense']) * (rand(8000, 12000) / 10000);
    }
 
    /**
     * calculation of hitratio
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response float
     */
    public function hitRatio($preparedForAttack) {
        return min(50 * $preparedForAttack['attackerStats']['agility'] / $preparedForAttack['defenderStats']['agility'] , 95);
    }
 
    /**
     * calculation of cirital hit
     * @param $hitRatio
     * @return \Illuminate\Http\Response float
     */
    public function ciritalHit($hitRatio) {
        return ($hitRatio + $this->attacker->level / 2) / 10;
    }
 
    /**
     * for get the players fighting stats
     * @param $userId
     * @return \Illuminate\Http\Response array
     */
    public function getFightStats($userId) {
        $strength = $this->userStats->getStrength($userId);
        $agility = $this->userStats->getAgility($userId);
        $defense = $this->userStats->getDefense($userId);
        $hp = $this->userStats->getHp($userId);
    return ['strength' => $strength, 'agility' => $agility, 'defense' => $defense, 'HP' => $hp];
    }
 
    /**
     * check the hp of player
     * @param $userId
     * @return \Illuminate\Http\Response string
     */
    public function isHP($userId) {
        return $this->userStats->getHp($userId);
    }
}
Link to comment
Share on other sites

On 8/30/2022 at 6:20 PM, smith said:

very bad code

<?php
 
namespace App\Http\Controllers;
 
use App\Models\{ AttackLog, User, Item, UserDetail,  UserSlot, UserStats, WeaponAttribute};
use Carbon\Carbon;
use Illuminate\Http\Request;
 
class AttacksController extends Controller
{
 
    /**
     * The attributes that are assignable.
     *
     * @var
     */
    protected  $attacker,
               $defender,
               $userDetails,
               $userStats,
               $weaponAttributes,
               $userSlots,
               $attackLog,
               $items,
               $hitresult,
               $carbon;
 
    /**
     * Instantiate a new AttacksController instance.
     */
    public function __construct(){
        $this->middleware(function ($request, $next) {
            $this->attacker = auth()->user();
        return $next($request);
        });
 
        $this->userDetails = new UserDetail();
        $this->userStats = new UserStats();
        $this->items = new Item();
        $this->weaponAttributes = new WeaponAttribute();
        $this->userSlots = new UserSlot();
        $this->attackLog = new AttackLog();
        $this->items = new Item();
        $this->carbon = new Carbon();
    }
 
    /**
     * invoke for attack
     * @param  Request $request, User $defender
     * @return \Illuminate\Http\Response player.attack with $array
     */
     public function __invoke(Request $request, User $defender) {
        $this->defender = $defender;
        return view('player.attack', [
             'attacker' => $this->attacker,
             'defender' => $this->defender,
             'defenderEquipped' => $this->equippedWeapons($this->defender->id),
             'attackerEquipped' => $this->equippedWeapons($this->attacker->id)
        ]);
     }
 
    /**
     * both player preparation for an Attack
     * @param  Request $request
     * @return \Illuminate\Http\Response $array
     */
    public function preparationForAttack($request) {
        $this->canAttack();
        $nextTurnAssignment = $this->turn();
        // dd($nextTurnAssignment);
        if((int)$nextTurnAssignment === 1)
        {
            $this->consumeEnergy($this->attacker->id);
        }
 
        $turnOwner = $this->doTurn($nextTurnAssignment);
        $selectedAttackerWeapon = $this->selectedWeaponName($this->attacker->id, $request->weaponId );
        $defenderWeaponId = $this->equippedWeapons($this->defender->id);
        $selectedDefenderWeapon = $this->selectedWeaponName($this->defender->id, $defenderWeaponId['primaryWeaponId']);
        $selectedAttackerWeaponAttributes = $this->equippedWeaponAttributes($request->weaponId);
        $selectedDefenderWeaponAttributes = $this->equippedWeaponAttributes($defenderWeaponId['primaryWeaponId']);
        $attackerStats = $this->getFightStats($this->attacker->id);
        $defenderStats = $this->getFightStats($this->defender->id);
        return [
            'turnNumber' => $nextTurnAssignment,
            'turnOwner' => $turnOwner,
            'attackerStats' => $attackerStats,
            'defenderStats' => $defenderStats,
            'selectedAttackerWeapon' => $selectedAttackerWeapon,
            'selectedDefenderWeapon' =>   $selectedDefenderWeapon,
            'selectedAttackerWeaponAttributes' => $selectedAttackerWeaponAttributes,
            'selectedDefenderWeaponAttributes' => $selectedDefenderWeaponAttributes
        ];
    }
 
    /**
     * attack preformance responsible
     * @param  Request $request, User $defender
     * @return \Illuminate\Http\Response $method
     */
    public function attack(Request $request, User $defender) {
        $this->defender = $defender;
        $preparedForAttack = $this->preparationForAttack($request);
        $singleHitResult = $this->attackPerform($preparedForAttack);
        $this->hitresult .= $singleHitResult;
    return $singleHitResult;
    }
 
    /**
     * generate attack step event
     * @param  $preparedForAttack, $damage
     * @return \Illuminate\Http\Response string
     */
    public function generateAttackStepEvent($preparedForAttack, $damage = 'missed') {
        $weaponName =  ($preparedForAttack['turnNumber'] % 2) ? $preparedForAttack['selectedDefenderWeapon'] : $preparedForAttack['selectedAttackerWeapon'];
        return [
            'turnNumber' => $preparedForAttack['turnNumber'],
            'message' => $preparedForAttack['turnNumber'] . " " . $preparedForAttack['turnOwner'] . " " . $weaponName . " " . $damage . " " . date('Y-m-d H:i:s')
        ] ;
    }
 
    /**
     * consume the energy for attack
     * @param  $userId
     * @return \Illuminate\Http\Response string
     */
    public function consumeEnergy($userId) {
        $consumeEnergyValue  = (int) ($this->userStats->getMaxEnergy($userId) / 3);
        $this->userStats->decrementEnergy($userId, $consumeEnergyValue);
    }
 
    /**
     * add attack log in storage                                                    \
     * @param
     * @return \Illuminate\Http\Response boolean
     */
    public function attackLog($hitResult) {
        return $this->attackLog->addLog($hitResult);
    }
 
    /**
     * cheack the eligibility for attack of both player
     * @param
     * @return \Illuminate\Http\Response throw expection
     */
    public function canAttack() {
        // dd($this->defender);
        $haveEnergy = (int) $this->userStats->getEnergy($this->defender->id) < (int) ($this->userStats->getMaxEnergy($this->defender->id)/2);
        $notSameLocation = $this->userDetails->getLocation($this->defender->id) !== $this->userDetails->getLocation($this->attacker->id);
        $defenderHospitalized = $this->userDetails->getHospitalTime($this->defender->id);
        $defenderJailed = $this->userDetails->getJailTime($this->defender->id);
        $selfAttack = $this->defender->id === $this->attacker->id;
 
        if ($selfAttack) {
            abort(403, "You can't attack yourself.");
        }elseif($haveEnergy) {
            abort(403, "You don't have enough energy.");
        } elseif ($notSameLocation) {
            abort(403, "Player isn't on same location.");
        } elseif ($defenderHospitalized) {
            abort(403, "Player already is hospitalized.");
        } elseif ($defenderJailed) {
            abort(403, "Player already is Jailed.");
        }
    }
 
    /**
     * turn creator for attack
     * @param
     * @return \Illuminate\Http\Response session
     */
    public function turn() {
        $turn = session('oldTurnNumber', 0);
        $countturn = $turn+1;
        session()->put('oldTurnNumber', $countturn);
    return $countturn;
    }
 
    /**
     * assign the turn to players for attack
     * @param $nextTurnAssignment
     * @return \Illuminate\Http\Response string
     */
    public function doTurn($nextTurnAssignment) {
 
        if($nextTurnAssignment%2 == 0)
        {
            return $this->defender->name;
        }
 
    return $this->attacker->name;
    }
 
    /**
     * attack performer
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response string or JSON
     */
    public function attackPerform($preparedForAttack){
        $userId = ($preparedForAttack['turnNumber'] % 2) ? $this->defender->id : $this->attacker->id;
 
        if($this->isChanceSuccess($preparedForAttack))
        {
            $damageCalculation = $this->damageCalculation($preparedForAttack);
            $this->doHPDown($userId, $damageCalculation);
            $isrHpDown = $this->isHP($userId);
 
            if($isrHpDown <= 0)
            {
                $attacker = ['attackerId' => $this->attacker->id];
                $defender = ['defenderId' => $this->defender->id];
                $userData = ($userId === $this->attacker->id)? $attacker: $defender;
            return response()->json([$userData]);
            }
 
        return $this->generateAttackStepEvent($preparedForAttack, $damageCalculation)['message'];
        }
 
    return $this->generateAttackStepEvent($preparedForAttack)['message'];
    }
 
    /**
     * defender hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function hospitalize($userId) {
        $number = mt_rand(1,5);
        $duration = $this->carbon->now()->addHours($number);
        session()->forget('oldTurnNumber');
    return $this->userDetails->addHospitalTime($userId, $duration);
    }
 
    /**
     * defender hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function settlement($userId)
    {
        $number = mt_rand(1, 5);
        $duration = $this->carbon->now()->addHours($number);
        $this->hitresult['message'] .= "You successfully done settlement";
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult);
    }
 
    /**
     * runway in between the attack
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function runaway($userId)
    {
        $number = mt_rand(1, 5);
        $message = "You successfully managed runaway";
 
        if($number === 3)
        {
            $duration = $this->carbon->now()->addHours($number);
            $this->userDetails->addHospitalTime($userId, $duration);
            $message = "You failed to manage the runaway";
        }
 
        $this->hitresult['message'] .= $message;
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult);
    }
 
    /**
     * defender  hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function leave($userId) {
        $number = mt_rand(20,30);
        $duration = $this->carbon->now()->addMinutes($number);
        $this->userDetails->addHospitalTime($userId, $duration);
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult['message']);
    }
 
    /**
     * defender  hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function mug($userId) {
        $number = mt_rand(20, 25);
        $duration = $this->carbon->now()->addMinutes($number);
        $this->userDetails->addHospitalTime($userId, $duration);
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult['message']);
    }
 
    /**
     * attacker hospitalize
     * @param $userId
     * @return \Illuminate\Http\Response boolean
     */
    public function lost($userId) {
        $number = mt_rand(10, 20);
        $duration = $this->carbon->now()->addMinutes($number);
        $this->userDetails->addHospitalTime($userId, $duration);
        session()->forget('oldTurnNumber');
    return $this->attackLog($this->hitresult['message']);
    }
 
    /**
     * equipped weapons of both players for attack
     * @param $userId
     * @return \Illuminate\Http\Response array
     */
    public function equippedWeapons($userId) {
        $weapons = $this->userSlots->getUserWeaponsById($userId);
        $primaryWeaponName = $this->items->getWeaponNameById($weapons->primary_slot);
        $secondaryWeaponName = $this->items->getWeaponNameById($weapons->secondary_slot);
        return [
            'primaryWeaponId' => $weapons->primary_slot,
            'primaryWeaponName' => $primaryWeaponName,
            'secondaryWeaponId' => $weapons->secondary_slot,
            'secondaryWeaponName' => $secondaryWeaponName
        ];
    }
 
    /**
     * hitting chance of attacker
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response boolean
     */
    public function isChanceSuccess($preparedForAttack) {
        $genrateRandom = mt_rand(1, 100);
        $hitRatio = (int) $this->hitRatio($preparedForAttack);
    return $genrateRandom <= (int) $hitRatio;
    }
 
    /**
     * decrement the HP of loser of hit in attack
     * @param $userId, $damageCalculation
     * @return \Illuminate\Http\Response boolean
     */
    public function doHPDown($userId, $damageCalculation) {
        return $this->userStats->decrementHP($userId, $damageCalculation);
    }
 
    /**
     * select weapon for attack by both player for attack
     * @param $userId, $weaponId
     * @return \Illuminate\Http\Response boolean or throw expection
     */
    public function selectedWeaponName($userId, $weaponId) {
        $weapons = $this->equippedWeapons($userId);
        $correctWeaponSelected = (int) $weapons['primaryWeaponId']  === (int) $weaponId || (int) $weapons['secondaryWeaponId']  === (int) $weaponId;
 
        if($correctWeaponSelected){
            return $this->items->getWeaponNameById($weaponId);
        }
 
    abort(403, "This weapon isn't selectable");
    }
 
    /**
     * as per weapon selection get attributes of weapon
     * @param $itemId
     * @return \Illuminate\Http\Response array
     */
    public function equippedWeaponAttributes($itemId) {
        $weaponAtrributeId = $this->items->getItemAttributeById($itemId);
    return $this->weaponAttributes->getattributesById($weaponAtrributeId);
    }
 
    /**
     * calculation of damage
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response int
     */
    public function damageCalculation($preparedForAttack) {
 
        if ($preparedForAttack['turnNumber'] % 2)
        {
            return (int) ($preparedForAttack['selectedDefenderWeaponAttributes']['damage'] * $preparedForAttack['defenderStats']['strength'] /
                $preparedForAttack['attackerStats']['defense']) * (rand(8000, 12000) / 10000);
        }
 
    return (int) ($preparedForAttack['selectedAttackerWeaponAttributes']['damage'] * $preparedForAttack['attackerStats']['strength'] /
        $preparedForAttack['defenderStats']['defense']) * (rand(8000, 12000) / 10000);
    }
 
    /**
     * calculation of hitratio
     * @param $preparedForAttack
     * @return \Illuminate\Http\Response float
     */
    public function hitRatio($preparedForAttack) {
        return min(50 * $preparedForAttack['attackerStats']['agility'] / $preparedForAttack['defenderStats']['agility'] , 95);
    }
 
    /**
     * calculation of cirital hit
     * @param $hitRatio
     * @return \Illuminate\Http\Response float
     */
    public function ciritalHit($hitRatio) {
        return ($hitRatio + $this->attacker->level / 2) / 10;
    }
 
    /**
     * for get the players fighting stats
     * @param $userId
     * @return \Illuminate\Http\Response array
     */
    public function getFightStats($userId) {
        $strength = $this->userStats->getStrength($userId);
        $agility = $this->userStats->getAgility($userId);
        $defense = $this->userStats->getDefense($userId);
        $hp = $this->userStats->getHp($userId);
    return ['strength' => $strength, 'agility' => $agility, 'defense' => $defense, 'HP' => $hp];
    }
 
    /**
     * check the hp of player
     * @param $userId
     * @return \Illuminate\Http\Response string
     */
    public function isHP($userId) {
        return $this->userStats->getHp($userId);
    }
}

Your Laravel-based code won't translate into a mccodes game. Nice code though.

Link to comment
Share on other sites

10 hours ago, sniko said:

Your Laravel-based code won't translate into a mccodes game. Nice code though.

Is it really though? Why instantiate a class, to then not include the functions and call them outside of the class. Class in the same file as random functions too, is poor design.

Code is sloppy, not to mention the fact it’s completely irrelevant to the entire post.

Not PSR compliant either. Slightly better than mccodes 😛

Edited by SRB
  • Like 1
Link to comment
Share on other sites

On 9/3/2022 at 6:56 AM, SRB said:

Is it really though? Why instantiate a class, to then not include the functions and call them outside of the class. Class in the same file as random functions too, is poor design.

Code is sloppy, not to mention the fact it’s completely irrelevant to the entire post.

Not PSR compliant either. Slightly better than mccodes 😛

just my point is only all engines are badly coded i am coding Engine in Reactjs (Frontend) + Laravel (Backend) + MUI (Styling)

 

above post code is not improved code 

soon i am with new Engine 

On 3/1/2022 at 3:45 AM, Samurai Legend said:

Error - 

Fatal error: Uncaught TypeError: Unsupported operand types: string + int in /Users/shahed/Projects/samuraiconflict/attack.php:98 Stack trace: #0 /Users/shahed/.composer/vendor/laravel/valet/server.php(235): require() #1 {main} thrown in /Users/shahed/Projects/samuraiconflict/attack.php on line 98

 

 Line -       $ns = !isset($_GET['nextstep']) ? 1 : $_GET['nextstep'] + 2;

 

Tried searching for the fix but I couldn't seem to get anywhere, please help!

outdated way

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...