Update src/battle.php

This commit is contained in:
Ivor Barhansky 2024-06-21 11:20:43 +00:00
parent 8427292d07
commit af6859ccd8

View File

@ -33,43 +33,51 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
} elseif ($action === 'move' && !$battleState['battle_end']) {
if ($battleState['last_fighter'] !== $username) {
$move = $_POST['move'];
$target = $_POST['target'];
$battleState['moves'][] = ['fighter' => $username, 'move' => $move, 'target' => $target];
$battleState['last_fighter'] = $username;
$attackerIndex = -1;
$targetIndex = -1;
foreach ($battleState['fighters'] as $index => $fighter) {
if ($fighter['name'] === $username) {
$attackerIndex = $index;
}
if ($fighter['name'] === $target) {
$targetIndex = $index;
}
$attackerIndex = -1;
foreach ($battleState['fighters'] as $index => $fighter) {
if ($fighter['name'] === $username) {
$attackerIndex = $index;
break;
}
}
if ($attackerIndex !== -1 && $targetIndex !== -1) {
$battleState['fighters'][$targetIndex]['hp'] -= $battleState['fighters'][$attackerIndex]['attack'];
if ($battleState['fighters'][$targetIndex]['hp'] <= 0) {
$battleState['fighters'][$targetIndex]['hp'] = 0;
if ($attackerIndex !== -1 && $battleState['fighters'][$attackerIndex]['hp'] > 0) {
if ($battleState['last_fighter'] !== $username) {
$move = $_POST['move'];
$target = $_POST['target'];
$battleState['moves'][] = ['fighter' => $username, 'move' => $move, 'target' => $target];
$battleState['last_fighter'] = $username;
$targetIndex = -1;
foreach ($battleState['fighters'] as $index => $fighter) {
if ($fighter['name'] === $target) {
$targetIndex = $index;
break;
}
}
$aliveFighters = array_filter($battleState['fighters'], function ($fighter){
return $fighter['hp'] > 0;
});
if ($targetIndex !== -1) {
$battleState['fighters'][$targetIndex]['hp'] -= $battleState['fighters'][$attackerIndex]['attack'];
if ($battleState['fighters'][$targetIndex]['hp'] <= 0) {
$battleState['fighters'][$targetIndex]['hp'] = 0;
}
if (count($aliveFighters) === 1) {
$battleState['battle_end'] = true;
$battleState['winner'] = reset($aliveFighters)['name'];
$aliveFighters = array_filter($battleState['fighters'], function ($fighter){
return $fighter['hp'] > 0;
});
if (count($aliveFighters) === 1) {
$battleState['battle_end'] = true;
$battleState['winner'] = reset($aliveFighters)['name'];
}
}
} else {
echo json_encode(['error' => 'Not your turn!']);
exit;
}
} else {
echo json_encode(['error' => 'Not your turn!']);
exit;
echo json_encode(['error' => 'You are dead!']);
exit();
}
}