Add pregame lobby with live chat

Players used to get bounced back to the dashboard when a session
wasn't full yet. Now they land on a lobby page showing who has
joined, and can chat with each other while waiting - messages are
broadcast live over the existing Mercure hub, and the session
auto-starts (and the lobby notifies everyone) once it fills up.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Frank
2026-08-10 15:32:23 +02:00
co-authored by Claude Sonnet 5
parent 98cf48b29d
commit 444f54b6c6
7 changed files with 301 additions and 4 deletions
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260810120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add lobby_message table for pre-game lobby chat';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE lobby_message (id INT AUTO_INCREMENT NOT NULL, session_id INT NOT NULL, player_id INT NOT NULL, content VARCHAR(500) NOT NULL, created_at DATETIME NOT NULL, INDEX IDX_LOBBY_MESSAGE_SESSION (session_id), INDEX IDX_LOBBY_MESSAGE_PLAYER (player_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE lobby_message ADD CONSTRAINT FK_LOBBY_MESSAGE_SESSION FOREIGN KEY (session_id) REFERENCES session (id)');
$this->addSql('ALTER TABLE lobby_message ADD CONSTRAINT FK_LOBBY_MESSAGE_PLAYER FOREIGN KEY (player_id) REFERENCES player (id)');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE lobby_message DROP FOREIGN KEY FK_LOBBY_MESSAGE_SESSION');
$this->addSql('ALTER TABLE lobby_message DROP FOREIGN KEY FK_LOBBY_MESSAGE_PLAYER');
$this->addSql('DROP TABLE lobby_message');
}
}
+11 -2
View File
@@ -141,12 +141,21 @@ final class GameController extends AbstractController
return $this->redirectToRoute('game', ['session' => $session->getId()]); return $this->redirectToRoute('game', ['session' => $session->getId()]);
} }
if ($request->isMethod('POST') && $request->request->has('send_message')) {
$dashboardService->postLobbyMessage($session, $user, (string) $request->request->get('content', ''));
return $this->redirectToRoute('game', ['session' => $session->getId()]);
}
// Lazily pick up readiness changes from other players since our last request // Lazily pick up readiness changes from other players since our last request
$dashboardService->checkAllPlayersReady($session); $dashboardService->checkAllPlayersReady($session);
if ($session->getStatus() === SessionStatus::CREATED) { if ($session->getStatus() === SessionStatus::CREATED) {
$this->addFlash('info', 'This session is still waiting for more players to join.'); return $this->render('game/lobby.html.twig', [
return $this->redirectToRoute('game_dashboard'); 'session' => $session,
'messages' => $dashboardService->getLobbyMessages($session),
'player' => $player,
'mercure_public_url' => $this->mercurePublicUrl,
]);
} }
if ($session->getStatus() === SessionStatus::WON) { if ($session->getStatus() === SessionStatus::WON) {
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Game\Entity;
use App\Game\Repository\LobbyMessageRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: LobbyMessageRepository::class)]
#[ORM\Table(name: 'lobby_message')]
class LobbyMessage
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(targetEntity: Session::class)]
#[ORM\JoinColumn(nullable: false)]
private ?Session $session = null;
#[ORM\ManyToOne(targetEntity: Player::class)]
#[ORM\JoinColumn(nullable: false)]
private ?Player $player = null;
#[ORM\Column(length: 500)]
private ?string $content = null;
#[ORM\Column(type: 'datetime')]
private ?\DateTimeInterface $createdAt = null;
public function __construct()
{
$this->createdAt = new \DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getSession(): ?Session
{
return $this->session;
}
public function setSession(?Session $session): static
{
$this->session = $session;
return $this;
}
public function getPlayer(): ?Player
{
return $this->player;
}
public function setPlayer(?Player $player): static
{
$this->player = $player;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): static
{
$this->content = $content;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): static
{
$this->createdAt = $createdAt;
return $this;
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Game\Repository;
use App\Game\Entity\LobbyMessage;
use App\Game\Entity\Session;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<LobbyMessage>
*/
class LobbyMessageRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, LobbyMessage::class);
}
/**
* @return LobbyMessage[]
*/
public function findForSession(Session $session, int $limit = 100): array
{
return $this->createQueryBuilder('m')
->andWhere('m.session = :session')
->setParameter('session', $session)
->orderBy('m.createdAt', 'ASC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
}
+63 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Game\Service; namespace App\Game\Service;
use App\Game\Entity\Game; use App\Game\Entity\Game;
use App\Game\Entity\LobbyMessage;
use App\Game\Entity\Player; use App\Game\Entity\Player;
use App\Game\Entity\Session; use App\Game\Entity\Session;
use App\Game\Entity\SessionSetting; use App\Game\Entity\SessionSetting;
@@ -11,6 +12,7 @@ use App\Game\Enum\GameStatus;
use App\Game\Enum\SessionSettingType; use App\Game\Enum\SessionSettingType;
use App\Game\Enum\SessionStatus; use App\Game\Enum\SessionStatus;
use App\Game\Repository\GameRepository; use App\Game\Repository\GameRepository;
use App\Game\Repository\LobbyMessageRepository;
use App\Game\Repository\SessionRepository; use App\Game\Repository\SessionRepository;
use App\Tech\Entity\User; use App\Tech\Entity\User;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@@ -21,10 +23,12 @@ use Symfony\Component\Mercure\Update;
final class GameDashboardService final class GameDashboardService
{ {
private const READY_TIMEOUT_SECONDS = 60; private const READY_TIMEOUT_SECONDS = 60;
private const LOBBY_MESSAGE_MAX_LENGTH = 500;
public function __construct( public function __construct(
private readonly GameRepository $gameRepository, private readonly GameRepository $gameRepository,
private readonly SessionRepository $sessionRepository, private readonly SessionRepository $sessionRepository,
private readonly LobbyMessageRepository $lobbyMessageRepository,
private readonly EntityManagerInterface $entityManager, private readonly EntityManagerInterface $entityManager,
private readonly HubInterface $hub, private readonly HubInterface $hub,
) { ) {
@@ -122,6 +126,8 @@ final class GameDashboardService
$this->entityManager->flush(); $this->entityManager->flush();
$this->publishLobbyEvent($session, 'player_joined');
if (count($session->getPlayers()) === $session->getGame()->getNumberOfPlayers()) { if (count($session->getPlayers()) === $session->getGame()->getNumberOfPlayers()) {
$this->startSession($session); $this->startSession($session);
} }
@@ -283,9 +289,60 @@ final class GameDashboardService
$this->entityManager->persist($session); $this->entityManager->persist($session);
$this->entityManager->flush(); $this->entityManager->flush();
$this->publishLobbyEvent($session, 'session_started');
return true; return true;
} }
/**
* @return LobbyMessage[]
*/
public function getLobbyMessages(Session $session): array
{
return $this->lobbyMessageRepository->findForSession($session);
}
public function postLobbyMessage(Session $session, User $user, string $content): ?LobbyMessage
{
if ($session->getStatus() !== SessionStatus::CREATED) {
return null;
}
$player = null;
foreach ($session->getPlayers() as $sessionPlayer) {
if ($sessionPlayer->getUser() === $user) {
$player = $sessionPlayer;
break;
}
}
if (!$player) {
return null;
}
$content = trim($content);
if ($content === '') {
return null;
}
$content = mb_substr($content, 0, self::LOBBY_MESSAGE_MAX_LENGTH);
$message = new LobbyMessage();
$message->setSession($session);
$message->setPlayer($player);
$message->setContent($content);
$this->entityManager->persist($message);
$this->entityManager->flush();
$this->publishLobbyEvent($session, 'lobby_message', [
'username' => $user->getUserIdentifier(),
'content' => $content,
'createdAt' => $message->getCreatedAt()->format(DATE_ATOM),
]);
return $message;
}
public function toggleReady(Session $session, User $user): bool public function toggleReady(Session $session, User $user): bool
{ {
if ($session->getStatus() !== SessionStatus::READY) { if ($session->getStatus() !== SessionStatus::READY) {
@@ -393,10 +450,15 @@ final class GameDashboardService
} }
private function publishPlayerReady(Session $session, int $screen, bool $ready): void private function publishPlayerReady(Session $session, int $screen, bool $ready): void
{
$this->publishLobbyEvent($session, 'player_ready', ['player' => $screen, 'ready' => $ready]);
}
private function publishLobbyEvent(Session $session, string $type, array $extra = []): void
{ {
try { try {
$topic = '/game/hub/' . $session->getId(); $topic = '/game/hub/' . $session->getId();
$this->hub->publish(new Update($topic, json_encode(['type' => 'player_ready', 'player' => $screen, 'ready' => $ready]))); $this->hub->publish(new Update($topic, json_encode(array_merge(['type' => $type], $extra))));
} catch (\Exception $e) { } catch (\Exception $e) {
// Mercure might be down, but we don't want to crash the game // Mercure might be down, but we don't want to crash the game
} }
+72
View File
@@ -0,0 +1,72 @@
{% extends 'layout/site.html.twig' %}
{% block title %}Waiting for players - {{ session.game.name }}{% endblock %}
{% block body %}
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary text-white">
<h3 class="card-title mb-0">Waiting for more players to join</h3>
</div>
<div class="card-body">
<h4>{{ session.game.name }}</h4>
<p>Share the invite code with your friends. Feel free to chat below while you wait &mdash; no need to reload the page.</p>
<div class="alert alert-info">
<strong>Players joined:</strong> {{ session.players|length }} / {{ session.game.numberOfPlayers }}
</div>
<ul class="list-group mb-3">
{% for sessionPlayer in session.players %}
<li class="list-group-item">{{ sessionPlayer.user.username }}</li>
{% endfor %}
</ul>
{% if session.players|length >= session.game.numberOfPlayers %}
<form method="post" action="{{ path('game_dashboard') }}" class="mb-3">
<input type="hidden" name="session_id" value="{{ session.id }}">
<button type="submit" name="start_session" class="btn btn-success">Start Session</button>
</form>
{% endif %}
<a href="{{ path('game_dashboard') }}" class="btn btn-outline-secondary btn-sm">Back to Dashboard</a>
</div>
</div>
<div class="card shadow-sm">
<div class="card-header">
<h5 class="mb-0">Lobby chat</h5>
</div>
<div class="card-body">
<div id="lobby-chat-log" class="mb-3 d-flex flex-column gap-2" style="max-height: 320px; overflow-y: auto;">
{% for message in messages %}
<div class="lobby-message">
<strong>{{ message.player.user.username }}</strong>
<span class="text-muted small">{{ message.createdAt|date('H:i') }}</span>
<div>{{ message.content }}</div>
</div>
{% else %}
<p class="text-muted mb-0" id="lobby-chat-empty">No messages yet. Say hi!</p>
{% endfor %}
</div>
{% if player %}
<form method="post" class="d-flex gap-2">
<input type="text" name="content" class="form-control" placeholder="Type a message&hellip;" maxlength="500" required autocomplete="off">
<button type="submit" name="send_message" class="btn btn-primary">Send</button>
</form>
{% else %}
<p class="text-muted mb-0">Only players in this session can chat.</p>
{% endif %}
</div>
</div>
</div>
</div>
<div id="game-lobby-config"
data-mercure-public-url="{{ mercure_public_url|e('html_attr') }}"
data-topic="/game/hub/{{ session.id|e('html_attr') }}"
style="display:none">
</div>
{% endblock %}
+4 -1
View File
@@ -10,6 +10,7 @@ use App\Game\Entity\SessionSetting;
use App\Game\Enum\GameStatus; use App\Game\Enum\GameStatus;
use App\Game\Enum\SessionStatus; use App\Game\Enum\SessionStatus;
use App\Game\Enum\SessionSettingType; use App\Game\Enum\SessionSettingType;
use App\Game\Repository\LobbyMessageRepository;
use App\Game\Service\GameDashboardService; use App\Game\Service\GameDashboardService;
use App\Tech\Entity\User; use App\Tech\Entity\User;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@@ -23,6 +24,7 @@ class GameDashboardServiceTest extends TestCase
private $entityManager; private $entityManager;
private $gameRepository; private $gameRepository;
private $sessionRepository; private $sessionRepository;
private $lobbyMessageRepository;
private $hub; private $hub;
private $service; private $service;
@@ -31,14 +33,15 @@ class GameDashboardServiceTest extends TestCase
$this->entityManager = $this->createMock(EntityManagerInterface::class); $this->entityManager = $this->createMock(EntityManagerInterface::class);
$this->gameRepository = $this->createMock(GameRepository::class); $this->gameRepository = $this->createMock(GameRepository::class);
$this->sessionRepository = $this->createMock(SessionRepository::class); $this->sessionRepository = $this->createMock(SessionRepository::class);
$this->lobbyMessageRepository = $this->createMock(LobbyMessageRepository::class);
$this->hub = $this->createMock(HubInterface::class); $this->hub = $this->createMock(HubInterface::class);
$this->service = new GameDashboardService( $this->service = new GameDashboardService(
$this->gameRepository, $this->gameRepository,
$this->sessionRepository, $this->sessionRepository,
$this->lobbyMessageRepository,
$this->entityManager, $this->entityManager,
$this->hub, $this->hub,
'http://localhost/topic'
); );
} }