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