Comus Party 1.0.0
Application web de mini-jeux en ligne
Chargement...
Recherche...
Aucune correspondance
ControllerGame.class.php
Aller à la documentation de ce fichier.
1<?php
9
10namespace ComusParty\Controllers;
11
12use ComusParty\App\EloCalculator;
13use ComusParty\App\Exceptions\GameSettingsException;
14use ComusParty\App\Exceptions\GameUnavailableException;
15use ComusParty\App\Exceptions\MalformedRequestException;
16use ComusParty\App\Exceptions\NotFoundException;
17use ComusParty\App\Exceptions\UnauthorizedAccessException;
18use ComusParty\App\MessageHandler;
19use ComusParty\App\Validator;
20use ComusParty\Models\GameDAO;
21use ComusParty\Models\GameRecord;
22use ComusParty\Models\GameRecordDAO;
23use ComusParty\Models\GameRecordState;
24use ComusParty\Models\GameState;
25use ComusParty\Models\PenaltyDAO;
26use ComusParty\Models\PlayerDAO;
27use DateMalformedStringException;
28use DateTime;
29use Error;
30use Exception;
31use Random\RandomException;
32use Twig\Environment;
33use Twig\Error\LoaderError;
34use Twig\Error\RuntimeError;
35use Twig\Error\SyntaxError;
36use Twig\Loader\FilesystemLoader;
37
43{
49 public function __construct(FilesystemLoader $loader, Environment $twig)
50 {
51 parent::__construct($loader, $twig);
52 }
53
61 public function showHomePage()
62 {
63 $playerManager = new PlayerDAO($this->getPdo());
64 $player = $playerManager->findByUuid($_SESSION['uuid']);
65 $_SESSION["elo"] = $player->getElo();
66 $_SESSION["xp"] = $player->getXp();
67 $_SESSION["comusCoin"] = $player->getComusCoin();
68 $_SESSION["username"] = $player->getUsername();
69 $this->getTwig()->addGlobal('auth', [
70 'pfpPath' => $_SESSION['pfpPath'] ?? null,
71 'loggedIn' => isset($_SESSION['uuid']),
72 'loggedUuid' => $_SESSION['uuid'] ?? null,
73 'loggedUsername' => $_SESSION['username'] ?? null,
74 'loggedComusCoin' => $_SESSION['comusCoin'] ?? null,
75 'loggedElo' => $_SESSION['elo'] ?? null,
76 'loggedXp' => $_SESSION['xp'] ?? null,
77 'role' => $_SESSION['role'] ?? null,
78 'firstName' => $_SESSION['firstName'] ?? null,
79 'lastName' => $_SESSION['lastName'] ?? null,
80 ]);
81 $gameManager = new GameDAO($this->getPdo());
82 $games = $gameManager->findAllWithTags();
83 $games = array_filter($games, fn($game) => $game->getState() == GameState::AVAILABLE);
84 $template = $this->getTwig()->load('player/home.twig');
85 echo $template->render(array(
86 "games" => $games
87 ));
88 }
89
101 public function initGame(string $code, ?array $settings): void
102 {
103 try {
104 $gameRecord = (new GameRecordDAO($this->getPdo()))->findByCode($code);
105
106 if ($gameRecord == null) {
107 throw new NotFoundException("La partie n'existe pas");
108 }
109
110 if ($gameRecord->getState() != GameRecordState::WAITING) {
111 throw new MalformedRequestException("La partie a déjà commencé ou est terminée");
112 }
113
114 if ($gameRecord->getHostedBy()->getUuid() != $_SESSION['uuid']) {
115 throw new UnauthorizedAccessException("Vous n'êtes pas l'hôte de la partie");
116 }
117
118 $game = $gameRecord->getGame();
119
120 if ($game->getState() != GameState::AVAILABLE) {
121 throw new GameUnavailableException("Le jeu n'est pas disponible");
122 }
123
124 $gameSettings = $this->getGameSettings($game->getId());
125 if (sizeof($gameSettings) == 0) {
126 throw new GameUnavailableException("Les paramètres du jeu ne sont pas disponibles");
127 }
128
129 $nbPlayers = sizeof($gameRecord->getPlayers());
130 if ($nbPlayers < $gameSettings["settings"]["minPlayers"] || $nbPlayers > $gameSettings["settings"]["maxPlayers"]) {
131 throw new GameSettingsException("Le nombre de joueurs est de " . $nbPlayers . " alors que le jeu nécessite entre " . $gameSettings["settings"]["minPlayers"] . " et " . $gameSettings["settings"]["maxPlayers"] . " joueurs");
132 }
133
134 if (in_array("MODIFIED_SETTING_DATA", $gameSettings["neededParametersFromComus"])) {
135 if (sizeof($settings) != sizeof($gameSettings["modifiableSettings"])) {
136 throw new GameSettingsException("Les paramètres du jeu ne sont pas valides");
137 }
138
139 $rules = [];
140 foreach ($settings as $key => $value) {
141 if (!array_key_exists($key, $gameSettings["modifiableSettings"])) {
142 throw new GameSettingsException("Les paramètres du jeu ne sont pas valides");
143 }
144
145 $neededSetting = $gameSettings["modifiableSettings"][$key];
146
147 if ($neededSetting["type"] == "select" && !in_array($value, array_map(fn($option) => $option["value"], $neededSetting["options"]))) {
148 throw new GameSettingsException("Le paramètre $key doit être une des valeurs suivantes : " . implode(", ", $neededSetting["values"]));
149 } elseif ($neededSetting["type"] == "select") {
150 continue;
151 }
152
153 if ($neededSetting["type"] == "checkbox" && !is_bool($value)) {
154 throw new GameSettingsException("Le paramètre $key doit être un booléen");
155 } elseif ($neededSetting["type"] == "checkbox") {
156 continue;
157 }
158
159 $rules[$key] = [
160 "required" => true,
161 "type" => $neededSetting["type"] == "number" ? "numeric" : "string",
162 ...(array_key_exists("min", $neededSetting) ? ["min-value" => $neededSetting["min"]] : []),
163 ...(array_key_exists("max", $neededSetting) ? ["max-value" => $neededSetting["max"]] : []),
164 ...(array_key_exists("pattern", $neededSetting) ? ["format" => $neededSetting["pattern"]] : [])
165 ];
166 }
167 $validator = new Validator($rules);
168
169 if (!$validator->validate($settings)) {
170 throw new GameSettingsException("Les paramètres du jeu ne sont pas valides.\r\n" . implode("\r\n", array_map(fn(string $key, array $value) => "[$key] " . implode(", ", $value), array_keys($validator->getErrors()), $validator->getErrors())));
171 }
172 } else {
173 $settings = [];
174 }
175
176 $baseUrl = $this->getGameUrl($game->getId());
177
178 $players = $gameRecord->getPlayers();
179 foreach ($players as &$player) {
180 $player["token"] = bin2hex(random_bytes(8));
181 }
182 $gameRecord->setPlayers($players);
183 (new GameRecordDAO($this->getPdo()))->updatePlayers($gameRecord->getCode(), $gameRecord->getPlayers());
184
185 $token = $gameRecord->generateToken();
186
187 $data = [
188 "token" => $token,
189 "code" => $gameRecord->getCode(),
190 ];
191
192 if (in_array("MODIFIED_SETTING_DATA", $gameSettings["neededParametersFromComus"])) {
193 $data["settings"] = $settings;
194 }
195
196 if (in_array("PLAYER_UUID", $gameSettings["neededParametersFromComus"])) {
197 $data["players"] = array_map(function ($player) use ($gameSettings) {
198 return [
199 'uuid' => $player["player"]->getUuid(),
200 ...(in_array("PLAYER_NAME", $gameSettings["neededParametersFromComus"]) ? ['username' => $player["player"]->getUsername()] : []),
201 ...(in_array('PLAYER_STYLE', $gameSettings["neededParametersFromComus"]) ? ['style' => [
202 "profilePicture" => $player["player"]->getActivePfp(),
203 "banner" => $player["player"]->getActiveBanner(),
204 ]] : []),
205 'token' => $player["token"]
206 ];
207 }, $gameRecord->getPlayers());
208 }
209
210 $ch = curl_init($baseUrl . "/" . $gameRecord->getCode() . "/init");
211 curl_setopt($ch, CURLOPT_POST, true);
212 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Envoyer le JSON
213 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Obtenir la réponse
214 curl_setopt($ch, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
215 curl_setopt($ch, CURLOPT_HTTPHEADER, [
216 "Content-Type: application/json", // Indiquer que les données sont au format JSON
217 ]);
218
219 // Exécuter la requête
220 $response = curl_exec($ch);
221
222 // Vérifier les erreurs
223 if (curl_errno($ch)) {
224 MessageHandler::sendJsonCustomException(500, curl_error($ch));
225 } else {
226 if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
227 MessageHandler::sendJsonCustomException(curl_getinfo($ch, CURLINFO_HTTP_CODE), "Erreur lors de l'initialisation du jeu");
228 }
229
230 $response = json_decode($response, true);
231 if (!$response["success"]) {
232 MessageHandler::sendJsonCustomException(
233 array_key_exists("code", $response) ? $response["code"] : 500,
234 "Erreur lors de l'initialisation du jeu." . (array_key_exists("message", $response) ? " " . $response["message"] : "")
235 );
236 }
237 }
238
239 // Fermer la connexion cURL
240 curl_close($ch);
241
242 $gameRecord->setState(GameRecordState::STARTED);
243 $gameRecord->setUpdatedAt(new DateTime());
244 (new GameRecordDAO($this->getPdo()))->update($gameRecord);
245
246 echo MessageHandler::sendJsonMessage("La partie a bien été initialisée", [
247 "game" => [
248 "code" => $code,
249 "gameId" => $game->getId(),
250 ],
251 ]);
252 exit;
253 } catch (Exception|Error $e) {
254 MessageHandler::sendJsonException($e);
255 }
256 }
257
265 private function getGameSettings(int $id): array
266 {
267 $gameFolder = $this->getGameFolder($id);
268 $settingsFile = "$gameFolder/settings.json";
269 if (!file_exists($settingsFile)) {
270 throw new GameUnavailableException("Le fichier $settingsFile n'existe pas. Impossible de récupérer les informations du jeu.");
271 }
272
273 return json_decode(file_get_contents($settingsFile), true);
274 }
275
282 private function getGameFolder(int $id): string
283 {
284 return realpath(__DIR__ . "/../..") . "/games/game$id";
285 }
286
287 private function getGameUrl(int $id): string
288 {
289 $gameSettings = $this->getGameSettings($id);
290 if ($gameSettings["settings"]["serveByComus"]) {
291 return "https://games.comus-party.com/game" . $id;
292 } else {
293 return $gameSettings["settings"]["serverAddress"] . ":" . $gameSettings["settings"]["serverPort"];
294 }
295 }
296
302 public function getGameInformations(?int $id)
303 {
304 $gameManager = new GameDAO($this->getPdo());
305 $game = $gameManager->findWithDetailsById($id);
306 echo MessageHandler::sendJsonMessage("Informations du jeu récupérées", [
307 "game" => [
308 "id" => $game->getId(),
309 "name" => $game->getName(),
310 "img" => $game->getPathImg(),
311 "description" => $game->getDescription(),
312 "tags" => $game->getTags(),
313 ],
314 ]);
315 exit;
316 }
317
328 public function showGame(string $code): void
329 {
330 $gameRecord = (new GameRecordDAO($this->getPdo()))->findByCode($code);
331 if ($gameRecord == null || $gameRecord->getGame()->getState() != GameState::AVAILABLE) {
332 throw new NotFoundException("La partie n'existe pas");
333 }
334
335 if (is_null($gameRecord->getPlayers())) {
336 (new GameRecordDAO($this->getPdo()))->delete($gameRecord->getCode());
337 throw new NotFoundException("La partie n'existe pas");
338 }
339
340 if ($gameRecord->getState() == GameRecordState::WAITING) {
341 $this->showGameSettings($gameRecord);
342 } else if ($gameRecord->getState() == GameRecordState::STARTED) {
343 $this->showInGame($gameRecord);
344 } else {
345 throw new Exception("Cette partie est terminée", 404);
346 }
347
348 exit;
349 }
350
361 private function showGameSettings(GameRecord $gameRecord): void
362 {
363 if (!in_array((new PlayerDAO($this->getPdo()))->findByUuid($_SESSION['uuid']), array_map(fn($player) => $player['player'], $gameRecord->getPlayers()))) {
364 $this->joinGameWithCode('GET', $gameRecord->getCode());
365 $gameRecord = (new GameRecordDAO($this->getPdo()))->findByCode($gameRecord->getCode());
366 }
367
368 $gameSettings = $this->getGameSettings($gameRecord->getGame()->getId());
369 if (in_array("MODIFIED_SETTING_DATA", $gameSettings["neededParametersFromComus"])) {
370 $settings = $this->getGameModifiableSettings($gameRecord->getGame()->getId());
371 } else {
372 $settings = [];
373 }
374
375 $template = $this->getTwig()->load('player/game-settings.twig');
376 echo $template->render([
377 "code" => $gameRecord->getCode(),
378 "isHost" => $gameRecord->getHostedBy()->getUuid() == $_SESSION['uuid'],
379 "players" => array_map(fn($player) => $player['player'], $gameRecord->getPlayers()),
380 "game" => $gameRecord->getGame(),
381 "chat" => $gameSettings["settings"]["allowChat"],
382 "gameFileInfos" => $gameSettings["game"],
383 "settings" => $settings,
384 "isPrivate" => $gameRecord->isPrivate(),
385 ]);
386 }
387
395 public function joinGameWithCode(string $method, string $code): void
396 {
397 if ($method == 'POST') {
398 try {
399 echo $this->joinGame($code, $_SESSION['uuid']);
400 } catch (Exception $e) {
401 MessageHandler::sendJsonException($e);
402 }
403 } elseif ($method == 'GET') {
404 $this->joinGame($code, $_SESSION['uuid']);
405 }
406 }
407
417 private function joinGame(string $code, ?string $playerUuid = null): string
418 {
419 $gameRecordManager = new GameRecordDAO($this->getPdo());
420 $gameRecord = $gameRecordManager->findByCode($code);
421
422 if ($gameRecord == null) {
423 throw new NotFoundException("La partie n'existe pas");
424 }
425
426 if ($this->getGameSettings($gameRecord->getGame()->getId())['settings']['maxPlayers'] <= sizeof($gameRecord->getPlayers())) {
427 throw new GameUnavailableException("La partie est pleine");
428 }
429
430 $player = (new PlayerDAO($this->getPdo()))->findByUuid($playerUuid);
431
432 // TODO: Fonctionnement pour un joueur non connecté a insérer ici
433
434 if ($gameRecord->getState() != GameRecordState::WAITING) {
435 throw new GameUnavailableException("La partie a déjà commencé");
436 }
437
438 if (!in_array($playerUuid, array_map(fn($player) => $player['player']->getUuid(), $gameRecord->getPlayers()))) {
439 $gameRecordManager->addPlayer($gameRecord, $player);
440 }
441
442 return json_encode([
443 "success" => true,
444 "game" => [
445 "code" => $code,
446 "gameId" => $gameRecord->getGame()->getId(),
447 ],
448 ]);
449 }
450
456 private function getGameModifiableSettings(int $id): array
457 {
458 $allSettings = $this->getGameSettings($id);
459 return $allSettings["modifiableSettings"];
460 }
461
471 private function showInGame(GameRecord $gameRecord): void
472 {
473 $players = $gameRecord->getPlayers();
474 if (!in_array($_SESSION['uuid'], array_map(fn($player) => $player["player"]->getUuid(), $players))) {
475 throw new UnauthorizedAccessException("Vous n'êtes pas dans la partie");
476 }
477
478 $baseUrl = $this->getGameUrl($gameRecord->getGame()->getId());
479 $token = null;
480 foreach ($players as $player) {
481 if ($player["player"]->getUuid() == $_SESSION['uuid']) {
482 $token = $player["token"];
483 break;
484 }
485 }
486 $template = $this->getTwig()->load('player/in-game.twig');
487 echo $template->render([
488 "code" => $gameRecord->getCode(),
489 "isHost" => $gameRecord->getHostedBy()->getUuid() == $_SESSION['uuid'],
490 "players" => $gameRecord->getPlayers(),
491 "game" => $gameRecord->getGame(),
492 "chat" => $this->getGameSettings($gameRecord->getGame()->getId())["settings"]["allowChat"],
493 "iframe" => $baseUrl . "/" . $gameRecord->getCode() . "/" . $token
494 ]);
495 }
496
503 public function changeVisibility(string $code, bool $isPrivate): void
504 {
505 try {
506 $gameRecordManager = new GameRecordDAO($this->getPdo());
507 $gameRecord = $gameRecordManager->findByCode($code);
508
509 if ($gameRecord == null) {
510 throw new NotFoundException("La partie n'existe pas");
511 }
512
513 if ($gameRecord->getHostedBy()->getUuid() != $_SESSION['uuid']) {
514 throw new UnauthorizedAccessException("Vous n'êtes pas l'hôte de la partie");
515 }
516
517 $gameRecord->setPrivate($isPrivate);
518 $gameRecordManager->update($gameRecord);
519
520 echo MessageHandler::sendJsonMessage("La visibilité de la partie a bien été modifiée");
521 exit;
522 } catch (Exception|Error $e) {
523 MessageHandler::sendJsonException($e);
524 }
525 }
526
533 public function joinGameFromSearch(int $gameId): void
534 {
535 try {
536 $game = (new GameDAO($this->getPdo()))->findById($gameId);
537
538 if ($game->getState() != GameState::AVAILABLE) {
539 throw new GameUnavailableException("Le jeu n'est pas disponible");
540 }
541
542 $gameRecordManager = new GameRecordDAO($this->getPdo());
543 $gameRecords = $gameRecordManager->findByGameIdAndState($gameId, GameRecordState::WAITING);
544
545 $eloForGame = [];
546 foreach ($gameRecords as $gameRecord) {
547 if ($gameRecord->getState() == GameRecordState::WAITING && !$gameRecord->isPrivate()) {
548 $players = $gameRecord->getPlayers();
549
550 $totalElo = 0;
551 $nbPlayers = 0;
552
553 if (is_null($players)) {
554 continue;
555 }
556
557 foreach ($players as $player) {
558 $totalElo += $player['player']->getElo();
559 $nbPlayers++;
560 }
561
562 $eloForGame[$gameRecord->getCode()] = $totalElo / $nbPlayers;
563 }
564 }
565
566 if (sizeof($eloForGame) == 0) {
567 throw new GameUnavailableException("Aucune partie n'est disponible");
568 }
569
570 $playerElo = (new PlayerDAO($this->getPdo()))->findByUuid($_SESSION['uuid'])->getElo();
571 $bestGame = null;
572
573 foreach ($eloForGame as $gameCode => $gameElo) {
574 if ($bestGame == null || abs($gameElo - $playerElo) < abs($eloForGame[$bestGame] - $playerElo)) {
575 $bestGame = $gameCode;
576 }
577 }
578
579 echo $this->joinGame($bestGame, $_SESSION['uuid']);
580 exit;
581 } catch (Exception $e) {
582 MessageHandler::sendJsonException($e);
583 }
584 }
585
594 public function quitGame(string $code, string $playerUuid): void
595 {
596 $gameRecordManager = new GameRecordDAO($this->getPdo());
597 $gameRecord = $gameRecordManager->findByCode($code);
598
599 if ($gameRecord == null) {
600 throw new NotFoundException("La partie n'existe pas");
601 }
602
603 $gameRecordManager->removePlayer($code, $playerUuid);
604
605 if ($gameRecord->getHostedBy()->getUuid() == $playerUuid) {
606 if (sizeof($gameRecord->getPlayers()) > 1) {
607 $gameRecord->setHostedBy($gameRecord->getPlayers()[0]["player"]);
608 $gameRecordManager->update($gameRecord);
609 } else {
610 $gameRecordManager->delete($code);
611 }
612 }
613
614 echo MessageHandler::sendJsonMessage("Vous avez bien quitté la partie");
615 exit;
616 }
617
626 public function createGame(int $gameId): void
627 {
628 $game = (new GameDAO($this->getPdo()))->findById($gameId);
629
630 if ($game->getState() != GameState::AVAILABLE) {
631 throw new GameUnavailableException("Le jeu n'est pas disponible");
632 }
633
634 $host = (new PlayerDAO($this->getPdo()))->findByUuid($_SESSION['uuid']);
635 $generatedCode = bin2hex(random_bytes(8));
636
637 $gameRecord = new GameRecord(
638 $generatedCode,
639 $game,
640 $host,
641 null,
642 GameRecordState::WAITING,
643 true,
644 null,
645 new DateTime(),
646 new DateTime(),
647 null
648 );
649
650 $gameRecordManager = new GameRecordDAO($this->getPdo());
651 $gameRecordManager->insert($gameRecord);
652 $gameRecordManager->addPlayer($gameRecord, $host);
653
654 echo MessageHandler::sendJsonMessage("La partie a bien été créée", [
655 "game" => [
656 "code" => $generatedCode,
657 "gameId" => $gameId,
658 ],
659 ]);
660 exit;
661 }
662
670 public function endGame(string $code, string $token, ?array $results = null): void
671 {
672 try {
673 $gameRecordManager = new GameRecordDAO($this->getPdo());
674 $playerManager = new PlayerDAO($this->getPdo());
675 $gameRecord = $gameRecordManager->findByCode($code);
676
677 if ($gameRecord == null) {
678 throw new NotFoundException("La partie n'existe pas");
679 }
680
681 if ($gameRecord->getState() != GameRecordState::STARTED) {
682 throw new MalformedRequestException("La partie n'a pas commencé ou est déjà terminée");
683 }
684
685 if ($gameRecord->getToken() != hash("sha256", $token)) {
686 throw new UnauthorizedAccessException("Impossible d'authentifier le serveur de jeu");
687 }
688
689 if (!empty($results)) {
690 $actualPlayerTokenInRecord = [];
691 foreach ($gameRecord->getPlayers() as $player) {
692 $actualPlayerTokenInRecord[$player["player"]->getUuid()] = $player["token"];
693 }
694
695 $gameSettings = $this->getGameSettings($gameRecord->getGame()->getId());
696
697 foreach ($results as $playerUuid => $playerData) {
698 if (!isset($actualPlayerTokenInRecord[$playerUuid]) || $actualPlayerTokenInRecord[$playerUuid] !== $playerData["token"]) {
699 throw new MalformedRequestException("Le joueur $playerUuid n'est pas dans la partie ou le token est invalide");
700 }
701 }
702
703 $allWinner = [];
704 $allLooser = [];
705 $allPlayers = [];
706 foreach ($results as $playerUuid => $playerData) {
707 if (in_array("SCORES", $gameSettings["returnParametersToComus"])) {
708 // TODO: Traiter le score des joueurs
709 }
710
711 if (in_array("WINNERS", $gameSettings["returnParametersToComus"])) {
712 if (!isset($playerData["winner"])) {
713 throw new MalformedRequestException("L'attribut \"winner\" n'est pas présent");
714 }
715
716 // TODO: Fix array_filter($gameRecord->getPlayers(), fn($player) => $player["player"]->getUuid() == $playerUuid)[0]["player"]
717 $player = $playerManager->findByUuid($playerUuid);
718 if ($playerData["winner"]) {
719 $allWinner[] = $player;
720 $gameRecordManager->addWinner($code, $playerUuid);
721 } else {
722 $allLooser[] = $player;
723 }
724 $allPlayers[] = $player;
725 }
726 }
727
728 if (!$gameRecord->isPrivate() && in_array("WINNERS", $gameSettings["returnParametersToComus"])) {
729 $this->calculateAndUpdateElo($allPlayers, $allWinner, $allLooser);
730 }
731 }
732
733 $gameRecord->setState(GameRecordState::FINISHED);
734 $gameRecord->setFinishedAt(new DateTime());
735 $gameRecordManager->update($gameRecord);
736
737 echo MessageHandler::sendJsonMessage("La partie a bien été terminée");
738 exit;
739 } catch (Exception|Error $e) {
740 MessageHandler::sendJsonException($e);
741 }
742 }
743
751 private function calculateAndUpdateElo(array $allPlayers, array $winners, array $looser): void
752 {
753 $averageEloLooser = $this->averageElo($looser);
754 $averageEloWinner = $this->averageElo($winners);
755
756 $playerManager = new PlayerDAO($this->getPdo());
757 foreach ($allPlayers as $player) {
758 $elo = $player->getElo();
759 if (sizeof($winners) == 0) {
760 $newElo = EloCalculator::calculateNewElo($elo, $averageEloLooser, 0.5);
761 } else if (in_array($player, $winners)) {
762 $newElo = EloCalculator::calculateNewElo($elo, $averageEloLooser, 1);
763 } else {
764 $newElo = EloCalculator::calculateNewElo($elo, $averageEloWinner, 0);
765 }
766 if ($newElo < 0)
767 $newElo = 0;
768 $player->setElo(round($newElo));
769 $playerManager->update($player);
770 }
771 }
772
777 private function averageElo(array $players): float
778 {
779 $averageElo = 0;
780 foreach ($players as $player) {
781 $averageElo += $player->getElo();
782 }
783 return $averageElo / sizeof($players);
784 }
785
792 public function isPlayerMuted(string $playerUsername): void
793 {
794 $playerManager = new PlayerDAO($this->getPdo());
795 $player = $playerManager->findByUsername($playerUsername);
796
797 $penaltyManager = new PenaltyDAO($this->getPdo());
798 $penalty = $penaltyManager->findLastMutedByPlayerUuid($player->getUuid());
799
800
801 $response = [
802 'muted' => false
803 ];
804
805 if (isset($penalty)) {
806 $endDate = $penalty->getCreatedAt()->modify("+" . $penalty->getDuration() . "hour");
807 if ($endDate > new DateTime()) {
808 $response['muted'] = true;
809 echo MessageHandler::sendJsonMessage("Le joueur est encore mute", $response);
810 exit;
811 }
812 }
813
814 echo MessageHandler::sendJsonMessage("Le joueur n'est pas mute", $response);
815 }
816}
static calculateNewElo(int $eloPlayer, float $averageElo, float $result)
Calcule le nouvel Elo du joueur en fonction de son Elo actuel, de l'Elo moyen des joueurs de la parti...
Classe Validator.
Definition Validator.php:17
showHomePage()
Affiche la page d'accueil avec la liste des jeux.
joinGameWithCode(string $method, string $code)
Rejoint une partie avec un code (Méthode GET ou POST autorisée)
initGame(string $code, ?array $settings)
Permet d'initialiser le jeu après validation des paramètres et que les joueurs soient prêts.
showGameSettings(GameRecord $gameRecord)
Affiche la page des paramètres de la partie.
getGameSettings(int $id)
Récupère les paramètres du jeu dont l'ID est passé en paramètre.
endGame(string $code, string $token, ?array $results=null)
Termine une partie et met à jour les scores et les gagnants.
showInGame(GameRecord $gameRecord)
Affiche la page de la partie en cours.
showGame(string $code)
Affiche la page de la partie dont le code est passé en paramètre.
joinGameFromSearch(int $gameId)
Rejoint une partie suite à une recherche de partie.
__construct(FilesystemLoader $loader, Environment $twig)
Constructeur de la classe ControllerGame.
createGame(int $gameId)
Crée une partie en base de données pour un jeu donné
isPlayerMuted(string $playerUsername)
Vérifie si un joueur est mute.
getGameInformations(?int $id)
Récupère les informations d'un jeu et le retourne au format JSON.
joinGame(string $code, ?string $playerUuid=null)
Rejoint une partie avec un code.
changeVisibility(string $code, bool $isPrivate)
Permet de changer la visibilité d'une partie.
getGameModifiableSettings(int $id)
Récupère les paramètres modifiables du jeu dont l'ID est passé en paramètre.
calculateAndUpdateElo(array $allPlayers, array $winners, array $looser)
Calcule et met à jour les scores Elo des joueurs.
quitGame(string $code, string $playerUuid)
Quitte une partie.
getGameFolder(int $id)
Récupère le dossier du jeu dont l'ID est passé en paramètre.
getTwig()
Retourne l'attribut twig, correspondant à l'environnement de Twig.
getPdo()
Retourne l'attribut PDO, correspondant à la connexion à la base de données.
isPrivate()
Getter de l'attribut isPrivate.
getGame()
Getter de l'attribut game.
getPlayers()
Getter de l'attribut players.
getCode()
Getter de l'attribut uuid.
getHostedBy()
Getter de l'attribut hostedBy.