Update src/battle.php

Групповые бои. #3
This commit is contained in:
Ivor Barhansky 2024-06-21 12:35:43 +00:00
parent 085663e22e
commit d8fd1d0e76

View File

@ -6,7 +6,9 @@ if (!file_exists($currentBattle)) {
'fighters' => [],
'moves' => [],
'last_fighter' => null,
'battle_end' => false
'battle_end' => false,
'winner' => null,
'game_mode' => null,
]));
}
@ -17,6 +19,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
if ($action === 'join') {
$gameMode = $_POST['gameMode'];
$team = $_POST['team'];
$fighterExists = false;
foreach ($battleState['fighters'] as $fighter) {
if ($username === $fighter['name']) {
@ -24,11 +28,18 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
break;
}
}
if (!$fighterExists) {
// Устанавливаем режим игры только при входе первого игрока
if (empty($battleState['fighters'])) {
$battleState['game_mode'] = $gameMode; //Ошибки нет, данные пишутся в json по окончанию.
}
$battleState['fighters'][] = [
'name' => $username,
'hp' => 100,
'attack' => 10,
'team' => ($gameMode === 'team' ? $team : null),
];
}
@ -62,14 +73,26 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$battleState['fighters'][$targetIndex]['hp'] = 0;
}
$aliveFighters = array_filter($battleState['fighters'], function ($fighter){
return $fighter['hp'] > 0;
});
$aliveTeams = [];
$aliveFighters = [];
if (count($aliveFighters) === 1) {
$battleState['battle_end'] = true;
$battleState['winner'] = reset($aliveFighters)['name'];
foreach ($battleState['fighters'] as $fighter) {
if ($fighter['hp'] > 0) {
if ($fighter['team']) {
$aliveTeams[$fighter['team']] = true;
}
$aliveFighters[] = $fighter;
}
}
if ($battleState['game_mode'] === 'team' && count($aliveTeams) === 1) {
$battleState['battle_end'] = true;
$battleState['winner'] = ['team' => array_keys($aliveTeams)[0]];
} elseif ($battleState['game_mode'] === 'solo' && count($aliveFighters) === 1) {
$battleState['battle_end'] = true;
$battleState['winner'] = ['name' => $aliveFighters[0]['name']];
}
}
} else {
echo json_encode(['error' => 'Not your turn!']);
@ -86,3 +109,5 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo json_encode($battleState);
}