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