/** * This handles the AJAX requests to update a game * * @return JsonModel */ public function updateAction() { $container = new Container('game'); // if there is no game running, return a 404 error if (!(isset($container->gameId) && null != $container->gameId)) { // no game stored in Session return $this->getResponse()->setStatusCode(404); } $gameRepo = $this->getObjectManager()->getRepository(Game::class); $user = $this->getUser(); $game = $gameRepo->findOneBy(['id' => $container->gameId, 'user' => $user->getId()]); if (!$game instanceof Game) { return $this->getResponse()->setStatusCode(404); } $correctGuesses = 0; $guessesAndPositions = $game->getGuessesAndPositions(); foreach ($guessesAndPositions as $guess) { $correctGuesses += count($guess['positions']); } $gameWon = $correctGuesses >= $game->getWordLength(); $config = $this->serviceLocator->get('Config'); $invalidLetter = false; // if this game is won, do not update it if (!$gameWon) { $request = $this->getRequest(); if ($request->isPost()) { $data = $request->getPost(); // validate the guess and add it to the game if (isset($data['letter'])) { $letter = Word::getStringUpper((string) $data['letter']); if (in_array($letter, $config['game']['allowedLetters'])) { if (mb_strlen($letter, 'utf-8') == 1) { $game->addGuessedLetter($letter); } } else { $invalidLetter = true; } } } } $allowedLetters = $config['game']['allowedLetters']; $correctGuesses = 0; $guessesAndPositions = $game->getGuessesAndPositions(); foreach ($guessesAndPositions as $guess) { $correctGuesses += count($guess['positions']); } // check if the game was won, and update it if so $gameWon = $correctGuesses >= $game->getWordLength(); if ($gameWon) { $container = new Container('game'); $container->gameId = null; $game->setWon(true); $game->setFinishedAt(new DateTime()); } $wrongGuesses = $game->getWrongGuessesAmount(); $leftGuesses = $config['game']['gameOverAfter'] - $wrongGuesses; // check if the game was lost and update it if so $gameLost = $leftGuesses <= 0; if ($gameLost) { $container = new Container('game'); $container->gameId = null; $game->setWon(false); $game->setFinishedAt(new DateTime()); // reveal the word $guessesAndPositions = $game->getLettersAndPositon(); } $this->getObjectManager()->persist($game); $this->getObjectManager()->flush(); $variables = ['letterCount' => $game->getWordLength(), 'guessedLetters' => $guessesAndPositions, 'allowedLetters' => $allowedLetters, 'gameWon' => $gameWon, 'leftGuesses' => $leftGuesses, 'gameLost' => $gameLost, 'invalidLetter' => $invalidLetter]; return new JsonModel($variables); }
static function getEditForm(Word $word) { $form = new WordForm(); $form->setData(['word' => $word->getWord()]); return $form; }