[Server/Client/Protocol] Shuffle or reorder player seats before a game starts (#7398)

* [Protocol] Add shuffle players option and player order command/event

Adds a 'Shuffle players at start' option to game creation plus a local
player id on the game state so clients can reconcile seat changes, and a
SET_PLAYER_ORDER command (1206) with a PLAYER_ORDER_CHANGED event (2023)
so the game host can set or randomize the seating order.

Took 6 minutes

* [Server] Shuffle and reorder player seats before a game starts

Auto-shuffles the seats at game start when enabled (now for games with
two or more players instead of three or more) and handles the new
SET_PLAYER_ORDER command so the game host or a moderator can reorder or
randomize the seats before the game starts. Re-seating re-keys the
player ids while keeping the per-user game/seat routing and persistent
player records in sync, then broadcasts the new order to everyone.

* [Client] Add shuffle players option and turn order dialog

Adds the 'Shuffle players at start' checkbox to game creation and a
host-only 'Set turn order...' action that opens a dialog to reorder or
randomize the seats before the game starts. Seating changes are shown in
the game's message log.

* [Client] Move the turn order dialog strings into retranslateUi

Follows the DlgInviteToGame convention so the dialog can be retranslated
instead of freezing its strings at construction time.

* [Server] Keep player ids stable across seat shuffles

* [Client] Lay out table and turn order dialog in seat order

* [Server] Send game-joined player list in seat order

* [Client] Reword the shuffle option to match its behaviour

* [Client] Address the seat-order review comments

- Give the game setup checkboxes a row of their own so they no longer
  collide in the create-game dialog
- Rename DlgTurnOrder::randomize() to isRandomizeRequested()
- Document what the ids in GameState::seatOrder mean
- Keep "Set turn order..." in sync with the game: hidden for non-hosts
  and once the game has started, re-shown when the game ends or hosting
  moves to the local player (new GameState::hostChanged signal)

* [Client] Do not preview a randomized turn order

Randomizing is a request to the server, not a local shuffle. Shuffling the
list locally meant the dialog showed an order the server then discarded, and
let the host re-open it until a favourable order appeared. The dialog now
switches to a mode that says the server will randomize and toggles back to the
manual list on request.

* [Client] Let moderators set the turn order

The server accepts SET_PLAYER_ORDER from the host or a moderator, but the
client hid the action from everyone except the host, making the moderator
branch unreachable. Visibility and the handler now share canSetTurnOrder().

* [Server] Rely on the player order event instead of a full state resend

cmdSetPlayerOrder re-sent the whole game state after reseating, so every
client reloaded its deck view mid-lobby for no reason. The new seating reaches
clients through the Event_PlayerOrderChanged that reseatPlayers broadcasts.

* [Client] Show random turn order in the game selector

The restrictions column listed "open decklists" but not the new seating
option, so a joining player had no way to see that seats will be randomized
each game. Game info already shows the disabled checkbox.

---------

Co-authored-by: Lukas Brübach <Bruebach.Lukas@bdosecurity.de>
This commit is contained in:
BruebachL 2026-11-04 15:44:50 +01:00 • committed by GitHub
parent ca2301bc96
commit 5ea16c805f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 1054 additions and 15 deletions

View file

@ -116,14 +116,17 @@ void DlgCreateGame::sharedCtor()
shareDecklistsOnLoadCheckBox = new QCheckBox(tr("Open decklists in lobby"));
shufflePlayersCheckBox = new QCheckBox(tr("Randomize turn order (seats) on each game start"));
createGameAsJudgeCheckBox = new QCheckBox(tr("Create game as judge"));
auto *gameSetupOptionsLayout = new QGridLayout;
gameSetupOptionsLayout->addWidget(startingLifeTotalLabel, 0, 0);
gameSetupOptionsLayout->addWidget(startingLifeTotalEdit, 0, 1);
gameSetupOptionsLayout->addWidget(shareDecklistsOnLoadCheckBox, 1, 0);
gameSetupOptionsLayout->addWidget(shareDecklistsOnLoadCheckBox, 1, 0, 1, 2);
gameSetupOptionsLayout->addWidget(shufflePlayersCheckBox, 2, 0, 1, 2);
if (room && room->getUserInfo()->user_level() & ServerInfo_User::IsJudge) {
gameSetupOptionsLayout->addWidget(createGameAsJudgeCheckBox, 2, 0);
gameSetupOptionsLayout->addWidget(createGameAsJudgeCheckBox, 3, 0, 1, 2);
} else {
createGameAsJudgeCheckBox->setChecked(false);
createGameAsJudgeCheckBox->setHidden(true);
@ -184,6 +187,7 @@ DlgCreateGame::DlgCreateGame(TabRoom *_room, const QMap<int, QString> &_gameType
createGameAsSpectatorCheckBox->setChecked(SettingsCache::instance().game().getCreateGameAsSpectator());
startingLifeTotalEdit->setValue(SettingsCache::instance().game().getDefaultStartingLifeTotal());
shareDecklistsOnLoadCheckBox->setChecked(SettingsCache::instance().game().getShareDecklistsOnLoad());
shufflePlayersCheckBox->setChecked(SettingsCache::instance().game().getShufflePlayers());
if (!rememberGameSettings->isChecked()) {
actReset();
@ -217,6 +221,7 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QS
createGameAsSpectatorCheckBox->setEnabled(false);
startingLifeTotalEdit->setEnabled(false);
shareDecklistsOnLoadCheckBox->setEnabled(false);
shufflePlayersCheckBox->setEnabled(false);
descriptionEdit->setText(QString::fromStdString(gameInfo.description()));
maxPlayersEdit->setValue(gameInfo.max_players());
@ -227,6 +232,7 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QS
spectatorsCanTalkCheckBox->setChecked(gameInfo.spectators_can_chat());
spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient());
shareDecklistsOnLoadCheckBox->setChecked(gameInfo.share_decklists_on_load());
shufflePlayersCheckBox->setChecked(gameInfo.shuffle_players());
QSet<int> types;
for (int i = 0; i < gameInfo.game_types_size(); ++i) {
@ -264,6 +270,7 @@ void DlgCreateGame::actReset()
startingLifeTotalEdit->setValue(20);
shareDecklistsOnLoadCheckBox->setChecked(false);
shufflePlayersCheckBox->setChecked(false);
createGameAsJudgeCheckBox->setChecked(false);
QMapIterator<int, QRadioButton *> gameTypeCheckBoxIterator(gameTypeCheckBoxes);
@ -294,6 +301,7 @@ void DlgCreateGame::actOK()
cmd.set_join_as_spectator(createGameAsSpectatorCheckBox->isChecked());
cmd.set_starting_life_total(startingLifeTotalEdit->value());
cmd.set_share_decklists_on_load(shareDecklistsOnLoadCheckBox->isChecked());
cmd.set_shuffle_players(shufflePlayersCheckBox->isChecked());
auto _gameTypes = QString();
QMapIterator<int, QRadioButton *> gameTypeCheckBoxIterator(gameTypeCheckBoxes);
@ -318,6 +326,7 @@ void DlgCreateGame::actOK()
SettingsCache::instance().game().setCreateGameAsSpectator(createGameAsSpectatorCheckBox->isChecked());
SettingsCache::instance().game().setDefaultStartingLifeTotal(startingLifeTotalEdit->value());
SettingsCache::instance().game().setShareDecklistsOnLoad(shareDecklistsOnLoadCheckBox->isChecked());
SettingsCache::instance().game().setShufflePlayers(shufflePlayersCheckBox->isChecked());
SettingsCache::instance().game().setGameTypes(_gameTypes);
}
PendingCommand *pend = room->prepareRoomCommand(cmd);

View file

@ -51,6 +51,7 @@ private:
QCheckBox *spectatorsAllowedCheckBox, *spectatorsNeedPasswordCheckBox, *spectatorsCanTalkCheckBox,
*spectatorsSeeEverythingCheckBox, *createGameAsJudgeCheckBox, *createGameAsSpectatorCheckBox;
QCheckBox *shareDecklistsOnLoadCheckBox;
QCheckBox *shufflePlayersCheckBox;
QDialogButtonBox *buttonBox;
QPushButton *clearButton;
QCheckBox *rememberGameSettings;

View file

@ -0,0 +1,136 @@
#include "dlg_turn_order.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QListWidget>
#include <QListWidgetItem>
#include <QPushButton>
#include <QVBoxLayout>
DlgTurnOrder::DlgTurnOrder(const QStringList &_playerNames, QWidget *parent)
: QDialog(parent), randomizeRequested(false)
{
listWidget = new QListWidget(this);
listWidget->addItems(_playerNames);
listWidget->setCurrentRow(0);
connect(listWidget, &QListWidget::currentRowChanged, this, &DlgTurnOrder::selectionChanged);
moveUpButton = new QPushButton(this);
connect(moveUpButton, &QPushButton::clicked, this, &DlgTurnOrder::actMoveUp);
moveDownButton = new QPushButton(this);
connect(moveDownButton, &QPushButton::clicked, this, &DlgTurnOrder::actMoveDown);
randomizeButton = new QPushButton(this);
connect(randomizeButton, &QPushButton::clicked, this, &DlgTurnOrder::actRandomize);
// Shown in place of the list while the server is asked to randomize: the
// order is chosen server side, so there is nothing to preview here.
hintLabel = new QLabel(this);
hintLabel->setWordWrap(true);
hintLabel->setAlignment(Qt::AlignCenter);
auto *buttonColumn = new QVBoxLayout;
buttonColumn->addWidget(moveUpButton);
buttonColumn->addWidget(moveDownButton);
buttonColumn->addWidget(randomizeButton);
buttonColumn->addStretch();
auto *listLayout = new QHBoxLayout;
listLayout->addWidget(listWidget);
listLayout->addWidget(hintLabel, 1);
listLayout->addLayout(buttonColumn);
auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, &QDialogButtonBox::accepted, this, &DlgTurnOrder::actOk);
connect(buttonBox, &QDialogButtonBox::rejected, this, &DlgTurnOrder::reject);
auto *mainLayout = new QVBoxLayout;
mainLayout->addLayout(listLayout);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
updateButtons();
updateMode();
setMinimumWidth(300);
}
void DlgTurnOrder::retranslateUi()
{
setWindowTitle(tr("Set turn order"));
moveUpButton->setText(tr("Move up"));
moveDownButton->setText(tr("Move down"));
randomizeButton->setText(randomizeRequested ? tr("Set order manually") : tr("Randomize"));
hintLabel->setText(tr("The server will randomize the turn order."));
}
QStringList DlgTurnOrder::order() const
{
QStringList playerNames;
for (int i = 0; i < listWidget->count(); ++i) {
playerNames.append(listWidget->item(i)->text());
}
return playerNames;
}
void DlgTurnOrder::moveSelected(int delta)
{
const int row = listWidget->currentRow();
const int newRow = row + delta;
if (row < 0 || newRow < 0 || newRow >= listWidget->count()) {
return;
}
QListWidgetItem *item = listWidget->takeItem(row);
listWidget->insertItem(newRow, item);
listWidget->setCurrentRow(newRow);
updateButtons();
}
void DlgTurnOrder::updateMode()
{
listWidget->setVisible(!randomizeRequested);
hintLabel->setVisible(randomizeRequested);
moveUpButton->setVisible(!randomizeRequested);
moveDownButton->setVisible(!randomizeRequested);
retranslateUi();
}
void DlgTurnOrder::updateButtons()
{
const int row = listWidget->currentRow();
const int count = listWidget->count();
const bool manualOrder = !randomizeRequested;
moveUpButton->setEnabled(manualOrder && row > 0);
moveDownButton->setEnabled(manualOrder && row >= 0 && row < count - 1);
}
void DlgTurnOrder::actMoveUp()
{
moveSelected(-1);
}
void DlgTurnOrder::actMoveDown()
{
moveSelected(1);
}
void DlgTurnOrder::actRandomize()
{
// Randomizing is a request to the server, not a local shuffle: showing a
// preview would let the host re-open the dialog until the order looks
// favourable for them.
randomizeRequested = !randomizeRequested;
updateMode();
updateButtons();
}
void DlgTurnOrder::actOk()
{
accept();
}
void DlgTurnOrder::selectionChanged()
{
updateButtons();
}

View file

@ -0,0 +1,51 @@
/**
* @file dlg_turn_order.h
* @ingroup GameDialogs
*/
//! \todo Document this file.
#ifndef DLG_TURN_ORDER_H
#define DLG_TURN_ORDER_H
#include <QDialog>
#include <QStringList>
class QLabel;
class QListWidget;
class QPushButton;
class DlgTurnOrder : public QDialog
{
Q_OBJECT
private:
QListWidget *listWidget;
QLabel *hintLabel;
QPushButton *moveUpButton;
QPushButton *moveDownButton;
QPushButton *randomizeButton;
bool randomizeRequested;
void moveSelected(int delta);
void updateMode();
void updateButtons();
private slots:
void actMoveUp();
void actMoveDown();
void actRandomize();
void actOk();
void selectionChanged();
public:
explicit DlgTurnOrder(const QStringList &_playerNames, QWidget *parent = nullptr);
void retranslateUi();
[[nodiscard]] bool isRandomizeRequested() const
{
return randomizeRequested;
}
[[nodiscard]] QStringList order() const;
};
#endif

View file

@ -185,6 +185,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
if (gameentry.share_decklists_on_load()) {
result.append(tr("open decklists"));
}
if (gameentry.shuffle_players()) {
result.append(tr("random turn order"));
}
return result.join(", ");
}
case Qt::DecorationRole: {

View file

@ -20,6 +20,7 @@
#include "../interface/widgets/cards/card_info_frame_widget.h"
#include "../interface/widgets/dialogs/dlg_create_game.h"
#include "../interface/widgets/dialogs/dlg_invite_to_game.h"
#include "../interface/widgets/dialogs/dlg_turn_order.h"
#include "../interface/widgets/server/game_link.h"
#include "../interface/widgets/server/user/user_list_manager.h"
#include "../interface/widgets/utility/completer_utils.h"
@ -195,6 +196,7 @@ void TabGame::connectToGameState()
{
connect(game->getGameState(), &GameState::gameStarted, this, &TabGame::startGame);
connect(game->getGameState(), &GameState::gameStopped, this, &TabGame::stopGame);
connect(game->getGameState(), &GameState::hostChanged, this, &TabGame::updateTurnOrderAction);
connect(game->getGameState(), &GameState::activePhaseChanged, this, &TabGame::setActivePhase);
connect(game->getGameState(), &GameState::activePlayerChanged, this, &TabGame::setActivePlayer);
}
@ -263,6 +265,8 @@ void TabGame::connectMessageLogToGameEventHandler()
connect(game->getGameEventHandler(), &GameEventHandler::logTurnReversed, messageLog,
&MessageLogWidget::logReverseTurn);
connect(game->getGameEventHandler(), &GameEventHandler::logTurnOrderChanged, messageLog,
&MessageLogWidget::logTurnOrderChanged);
connect(game->getGameEventHandler(), &GameEventHandler::logConcede, messageLog, &MessageLogWidget::logConcede);
connect(game->getGameEventHandler(), &GameEventHandler::logUnconcede, messageLog, &MessageLogWidget::logUnconcede);
@ -373,6 +377,9 @@ void TabGame::retranslateUi()
if (aReverseTurn) {
aReverseTurn->setText(tr("Reverse turn order"));
}
if (aTurnOrder) {
aTurnOrder->setText(tr("&Set turn order..."));
}
if (aRemoveLocalArrows) {
aRemoveLocalArrows->setText(tr("&Remove all local arrows"));
}
@ -629,6 +636,73 @@ void TabGame::actConcede()
}
}
void TabGame::actTurnOrder()
{
if (!canSetTurnOrder()) {
return;
}
QStringList playerNames;
const QList<int> seatOrder = game->getGameState()->getSeatOrder();
const auto &players = game->getPlayerManager()->getPlayers();
if (!seatOrder.isEmpty()) {
for (int playerId : seatOrder) {
if (PlayerLogic *player = players.value(playerId, nullptr)) {
playerNames.append(player->getPlayerInfo()->getName());
}
}
// Include any players missing from the tracked order rather than dropping them.
for (auto it = players.constBegin(); it != players.constEnd(); ++it) {
const QString name = it.value()->getPlayerInfo()->getName();
if (!playerNames.contains(name)) {
playerNames.append(name);
}
}
} else {
for (PlayerLogic *player : players) {
playerNames.append(player->getPlayerInfo()->getName());
}
}
DlgTurnOrder dlg(playerNames, this);
if (dlg.exec() != QDialog::Accepted) {
return;
}
game->getGameEventHandler()->handleSetPlayerOrder(dlg.order(), dlg.isRandomizeRequested());
}
/**
* Whether the local user may change the seating order: only while the game has
* not started, and only as the host or a moderator - the server allows both
* (Server_AbstractParticipant::cmdSetPlayerOrder).
*/
bool TabGame::canSetTurnOrder() const
{
if (game->getGameMetaInfo()->started()) {
return false;
}
if (game->isHost()) {
return true;
}
const ServerInfo_User *userInfo = tabSupervisor->getUserInfo();
return userInfo != nullptr && (userInfo->user_level() & ServerInfo_User::IsModerator);
}
/**
* Shows the turn order action only when it can actually change anything: the
* player must be allowed to set the order and the game must not have started.
* Called whenever either condition may have changed (game start/stop, host
* change).
*/
void TabGame::updateTurnOrderAction()
{
if (aTurnOrder == nullptr) {
return;
}
aTurnOrder->setVisible(canSetTurnOrder());
}
/**
* Confirms the leave game and sends the leave game command, if applicable.
*
@ -840,6 +914,15 @@ void TabGame::processPlayerLeave(PlayerLogic *leavingPlayer)
}
}
// A shuffled local player has their seat changed, so the deck view container
// keyed by their previous id must be cleaned up alongside the leaving player.
int leavingPlayerId = leavingPlayer->getPlayerInfo()->getId();
if (deckViewContainers.contains(leavingPlayerId)) {
TabbedDeckViewContainer *deckView = deckViewContainers.take(leavingPlayerId);
deckViewContainerLayout->removeWidget(deckView);
deckView->deleteLater();
}
scene->removePlayer(leavingPlayer);
}
@ -948,6 +1031,7 @@ void TabGame::startGame(bool _resuming)
aConcede->setText(tr("&Concede"));
aConcede->setEnabled(true);
}
updateTurnOrderAction();
}
void TabGame::stopGame()
@ -970,6 +1054,7 @@ void TabGame::stopGame()
aConcede->setText(tr("&Concede"));
aConcede->setEnabled(false);
}
updateTurnOrderAction();
}
void TabGame::closeGame()
@ -1094,6 +1179,9 @@ void TabGame::createMenuItems()
connect(aNextTurn, &QAction::triggered, game->getGameEventHandler(), &GameEventHandler::handleNextTurn);
aReverseTurn = new QAction(this);
connect(aReverseTurn, &QAction::triggered, game->getGameEventHandler(), &GameEventHandler::handleReverseTurn);
aTurnOrder = new QAction(this);
connect(aTurnOrder, &QAction::triggered, this, &TabGame::actTurnOrder);
updateTurnOrderAction();
aRemoveLocalArrows = new QAction(this);
connect(aRemoveLocalArrows, &QAction::triggered, this, &TabGame::actRemoveLocalArrows);
aRotateViewCW = new QAction(this);
@ -1144,6 +1232,7 @@ void TabGame::createMenuItems()
gameMenu->addAction(aNextTurn);
aNextTurn->setObjectName("aNextTurn");
gameMenu->addAction(aReverseTurn);
gameMenu->addAction(aTurnOrder);
gameMenu->addSeparator();
gameMenu->addAction(aRemoveLocalArrows);
gameMenu->addAction(aRotateViewCW);
@ -1172,6 +1261,7 @@ void TabGame::createReplayMenuItems()
aNextPhaseAction = nullptr;
aNextTurn = nullptr;
aReverseTurn = nullptr;
aTurnOrder = nullptr;
aRemoveLocalArrows = nullptr;
aRotateViewCW = nullptr;
aRotateViewCCW = nullptr;
@ -1302,6 +1392,7 @@ void TabGame::createPlayAreaWidget(bool bReplay)
scene = new GameScene(phasesToolbar, this);
connect(game->getPlayerManager(), &PlayerManager::playerConceded, scene, &GameScene::rearrange);
connect(game->getPlayerManager(), &PlayerManager::playerCountChanged, scene, &GameScene::rearrange);
connect(game->getGameState(), &GameState::seatOrderChanged, scene, &GameScene::rearrange);
connect(scene, &GameScene::arrowDeletionRequested, game->getGameEventHandler(),
&GameEventHandler::handleArrowDeletion);
connect(game->getGameEventHandler(), &GameEventHandler::arrowDeleted, scene, &GameScene::deleteArrow);

View file

@ -94,7 +94,8 @@ private:
QMenu *gameMenu, *viewMenu;
TearOffMenu *phasesMenu;
QAction *aGameInfo, *aConcede, *aCopyGameLink, *aLeaveGame, *aNextPhase, *aNextPhaseAction, *aNextTurn,
*aReverseTurn, *aRemoveLocalArrows, *aRotateViewCW, *aRotateViewCCW, *aResetLayout, *aResetReplayLayout;
*aReverseTurn, *aTurnOrder, *aRemoveLocalArrows, *aRotateViewCW, *aRotateViewCCW, *aResetLayout,
*aResetReplayLayout;
QAction *aFocusChat;
QAction *aInviteToGame = nullptr;
QList<QAction *> phaseActions;
@ -129,6 +130,7 @@ private:
PlayerLogic *setActivePlayer(int id);
void setActivePhase(int phase);
bool canSetTurnOrder() const;
void createMenuItems();
void createReplayMenuItems();
void createViewMenuItems();
@ -162,6 +164,8 @@ private slots:
void actInviteToGame();
void actConcede();
void actCopyGameLink();
void actTurnOrder();
void updateTurnOrderAction();
void actRemoveLocalArrows();
void actRotateViewCW();
void actRotateViewCCW();