mancala/apps/frontend/src/routes/GamePage.tsx

428 lines
19 KiB
TypeScript
Raw Normal View History

import { MancalaGame, Pit } from 'mancala.js';
import * as React from 'react';
2022-07-31 00:59:18 +03:00
import { FunctionComponent, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { v4 } from 'uuid';
import { PitAnimator } from '@mancala/core';
2022-07-31 00:59:18 +03:00
import BoardToolbar from '../components/board/BoardToolbar';
import BoardView from '../components/board/BoardView';
import InfoPanel from '../components/InfoPanel';
import LoadingComponent from '../components/LoadingComponent';
import PageContainer from '../components/PageContainer';
import AppHeader from '../components/headerbar/AppHeader';
import { LeaveIcon, PlusIcon } from '../components/Icons';
2022-07-31 00:59:18 +03:00
import UserStatus from '../components/UserStatus';
import { GameRecord, channel_on_game_update, channel_on_game_crashed, channel_on_game_end, channel_on_game_user_leave, channel_on_user_connection_change, channel_leave_game, channel_game_move, channel_listen_game_events, channel_unlisten_game_events, FinishedGameSummary, GameEndMessage, getBoardAfterMove, getSeat, PlayedMove } from '@mancala/core';
import { Context } from '../context/context';
2022-07-31 00:59:18 +03:00
import useWindowDimensions from '../hooks/useWindowDimensions';
2024-06-17 15:37:17 +03:00
import { GameMove, LoadingState, Game, GameUsersConnectionInfo } from "@mancala/core";
import { Theme } from '@mancala/core';
import { getColorByBrightness, getPlayerDisplayName } from "@mancala/core";
import { BoardViewModel } from "@mancala/core";
2022-07-31 00:59:18 +03:00
import Center from '../components/Center';
2022-09-04 00:04:32 +03:00
import notyf from '../util/Notyf';
2022-09-04 00:16:14 +03:00
import swal from 'sweetalert';
2022-09-04 01:06:26 +03:00
import Util from '../util/Util';
import { useTranslation } from 'react-i18next';
import MoveList from '../components/history/MoveList';
import ReviewBanner from '../components/history/ReviewBanner';
import useMoveKeys from '../hooks/useMoveKeys';
import { createBoardViewModel } from '../util/BoardViewModels';
import { getResultText } from '../util/GameResultText';
import ReplayView from '../components/history/ReplayView';
import GameClockView from '../components/GameClockView';
import useGameClock from '../hooks/useGameClock';
2022-07-31 00:59:18 +03:00
const GamePage: FunctionComponent<{
context: Context,
userKey?: string,
theme: Theme,
2022-09-04 01:06:26 +03:00
}> = ({ context, userKey, theme }) => {
2022-07-31 00:59:18 +03:00
let params = useParams<{ gameId: string }>();
const [game, setGame] = useState<Game | undefined>(undefined);
2022-07-31 00:59:18 +03:00
const [userKeyWhoLeave, setUserKeyWhoLeave] = useState<string | undefined>(undefined);
const [boardViewModel, setBoardViewModel] = useState<BoardViewModel | undefined>(undefined);
const [boardId, setBoardId] = useState<string>("-1");
const [pitAnimator, setPitAnimator] = useState<PitAnimator | undefined>(undefined);
// It is a flag for ongoing action such as send game move.
// We have to block future actions if there is an ongoing action.
const [hasOngoingAction, setHasOngoingAction] = useState<boolean>(false);
const [gameUsersConnectionInfo, setGameUsersConnectionInfo] = useState<GameUsersConnectionInfo | undefined>();
2022-07-31 00:59:18 +03:00
// Set while an earlier position is shown instead of the live board.
const [viewedMove, setViewedMove] = useState<number | undefined>(undefined);
// Set when the game has ended and was loaded from history; the page then shows the replay.
const [replayRecord, setReplayRecord] = useState<GameRecord | undefined>(undefined);
// Set when the server says the game ended, for whatever reason.
const [gameEnd, setGameEnd] = useState<GameEndMessage | undefined>(undefined);
2022-07-31 00:59:18 +03:00
const { height, width } = useWindowDimensions();
const navigate = useNavigate();
const { t } = useTranslation();
const [gameLoadingState, setLoadingStateGame] = useState<LoadingState<Game>>(LoadingState.Unset());
2022-07-31 00:59:18 +03:00
const checkIsSpectator = (game: Game) => userKey !== game.mancalaGame.player1Id && userKey !== game.mancalaGame.player2Id;
const mancalaGame: MancalaGame | undefined = game?.mancalaGame;
const isSpectator = game ? checkIsSpectator(game) : undefined;
const isPlayer2 = !isSpectator && userKey === mancalaGame?.player2Id;
const onGameUpdate = (pitAnimator: PitAnimator, newGame: Game) => {
setGame(newGame);
pitAnimator.setUpdatedGame(newGame);
2022-07-31 00:59:18 +03:00
setHasOngoingAction(false);
setGameUsersConnectionInfo(newGame.gameUsersConnectionInfo);
}
const isUserOnline = (userId: string) => {
if (!gameUsersConnectionInfo) return false;
const user1ConnectionInfo = gameUsersConnectionInfo.user1ConnectionInfo;
const user2ConnectionInfo = gameUsersConnectionInfo.user2ConnectionInfo;
if (user1ConnectionInfo.userId === userId) return user1ConnectionInfo.isOnline;
if (user2ConnectionInfo.userId === userId) return user2ConnectionInfo.isOnline;
return false;
}
const getPlayerName = (userId: string) => {
const connectionInfos = [gameUsersConnectionInfo?.user1ConnectionInfo, gameUsersConnectionInfo?.user2ConnectionInfo];
return getPlayerDisplayName(connectionInfos.find((info) => info?.userId === userId), t);
}
const onGameUpdateEvent = (pitAnimator: PitAnimator, message: Object) => {
const newGame: Game = message as Game;
newGame.mancalaGame = MancalaGame.createFromMancalaGame(newGame.mancalaGame);
onGameUpdate(pitAnimator, newGame);
2022-07-31 00:59:18 +03:00
}
const onGameCrashed = (message: any) => {
const newCrashMessage = message as string;
notyf.error(t("InternalErrorOccurred"));
2022-07-31 00:59:18 +03:00
console.error("on_game_crash");
console.error(newCrashMessage);
}
const onGameUserLeave = (message: any) => {
const userKeyWhoLeave = message;
setUserKeyWhoLeave(userKeyWhoLeave);
setHasOngoingAction(false);
};
const onGameEnd = (message: GameEndMessage) => {
setGameEnd(message);
setHasOngoingAction(false);
};
2022-07-31 00:59:18 +03:00
const onUserConnectionChange = (message: any) => {
const gameUsersConnectionInfo = message as GameUsersConnectionInfo;
setGameUsersConnectionInfo(gameUsersConnectionInfo);
2022-07-31 00:59:18 +03:00
};
const listenMessages = (game: Game, pitAnimator: PitAnimator): () => void => {
const _onGameUpdate = (message: object) => onGameUpdateEvent(pitAnimator, message);
2022-09-02 00:04:21 +03:00
context.rtmt.addMessageListener(channel_on_game_update, _onGameUpdate);
context.rtmt.addMessageListener(channel_on_game_crashed, onGameCrashed);
context.rtmt.addMessageListener(channel_on_game_user_leave, onGameUserLeave);
context.rtmt.addMessageListener(channel_on_user_connection_change, onUserConnectionChange);
context.rtmt.addMessageListener(channel_on_game_end, onGameEnd);
2022-07-31 00:59:18 +03:00
return () => {
context.rtmt.removeMessageListener(channel_on_game_end, onGameEnd);
2022-09-02 00:04:21 +03:00
context.rtmt.removeMessageListener(channel_on_game_update, _onGameUpdate);
context.rtmt.removeMessageListener(channel_on_game_crashed, onGameCrashed);
context.rtmt.removeMessageListener(channel_on_game_user_leave, onGameUserLeave);
context.rtmt.removeMessageListener(channel_on_user_connection_change, onUserConnectionChange);
2022-07-31 00:59:18 +03:00
}
};
// Spectators tell the server they are watching once their identity is known and the connection is open,
// and again after every reconnect, since the server forgets spectators who go offline.
React.useEffect(() => {
if (!game || !userKey || !checkIsSpectator(game)) return;
const listen = () => context.rtmt.sendMessage(channel_listen_game_events, game.id);
if (context.rtmt.connectionState === "connected") listen();
context.rtmt.on("open", listen);
return () => {
context.rtmt.off("open", listen);
if (context.rtmt.connectionState === "connected") context.rtmt.sendMessage(channel_unlisten_game_events, game.id);
};
}, [game?.id, userKey]);
2022-07-31 00:59:18 +03:00
const updateBoardViewModel = (boardViewModel: BoardViewModel) => {
boardViewModel.id = v4();
setBoardId(boardViewModel.id);
setBoardViewModel(boardViewModel);
};
const getBoardIndex = (index: number) => {
if (!game || !mancalaGame) return -1;
const pitsLenght = mancalaGame.board.pits.length;
if (userKey === mancalaGame.player2Id) return index + pitsLenght / 2;
2022-07-31 00:59:18 +03:00
return index;
};
const getOpponentId = () => mancalaGame?.player1Id === userKey ? mancalaGame?.player2Id : mancalaGame?.player1Id;
2022-07-31 00:59:18 +03:00
const checkHasAnOngoingAction = () => hasOngoingAction;
const onLeaveGameClick = () => {
if (Util.checkConnectionAndMaybeAlert(context, t)) return;
2022-09-04 00:16:14 +03:00
swal({
title: t("AreYouSureToLeaveGame"),
2022-09-04 00:16:14 +03:00
icon: "warning",
buttons: [t("Cancel"), t("Yes")],
2022-09-04 00:16:14 +03:00
dangerMode: true,
})
.then((confirm) => {
if (confirm) {
2022-09-04 00:16:14 +03:00
context.rtmt.sendMessage(channel_leave_game, {});
navigate("/");
2022-09-04 00:16:14 +03:00
}
});
2022-07-31 00:59:18 +03:00
};
const onNewGameClick = () => {
if (Util.checkConnectionAndMaybeAlert(context, t)) return;
2022-07-31 00:59:18 +03:00
navigate("/loby")
};
const onPitSelect = (index: number, pit: Pit) => {
if (!game || isSpectator || !userKey) {
return;
}
if(userKeyWhoLeave || gameEnd) {
notyf.error(t("GameEnded"));
return;
}
if (viewedMove !== undefined) {
notyf.error(t("ViewingMove", { number: viewedMove }));
return;
}
2022-09-07 22:28:03 +03:00
if(game.mancalaGame.state === "ended") {
notyf.error(t("GameEnded"));
2022-09-07 22:28:03 +03:00
return;
}
if (Util.checkConnectionAndMaybeAlert(context, t)) return;
2022-09-04 00:16:14 +03:00
if (game.mancalaGame.getPlayerIdByIndex(index) !== userKey) {
notyf.error(t("UCanOnlyPlayYourOwnPits"));
2022-09-04 00:04:32 +03:00
return;
}
const pitIndexForUser = index % (game.mancalaGame.board.totalPitCount() / 2);
2022-09-04 00:04:32 +03:00
if (!game.mancalaGame.canPlayerMove(userKey, pitIndexForUser)) {
notyf.error(t("OpponentTurn"));
return;
}
2022-07-31 00:59:18 +03:00
if (checkHasAnOngoingAction()) {
notyf.error(t("UMustWaitUntilCurrentMoveComplete"));
2022-07-31 00:59:18 +03:00
return;
}
if (!boardViewModel) return;
//TODO: this check should be in mancala.js
2022-07-31 00:59:18 +03:00
if (pit.stoneCount === 0) {
notyf.error(t("UCanNotPlayEmptyPit"));
2022-07-31 00:59:18 +03:00
return;
}
2022-09-04 00:04:32 +03:00
setHasOngoingAction(true);
boardViewModel.pits[getBoardIndex(pitIndexForUser)].pitColor =
2022-07-31 00:59:18 +03:00
context.themeManager.theme.pitSelectedColor;
updateBoardViewModel(boardViewModel);
const gameMove: GameMove = { index: pitIndexForUser };
2022-07-31 00:59:18 +03:00
context.rtmt.sendMessage(channel_game_move, gameMove);
};
React.useEffect(() => {
let pitAnimator: PitAnimator | undefined;
let unlistenMessages: () => void;
2022-07-31 00:59:18 +03:00
setLoadingStateGame(LoadingState.Loading())
context.gameStore.get(params.gameId!!).then((loaded) => {
if (loaded?.kind === "live") {
const game = loaded.game;
pitAnimator = new PitAnimator(context.themeManager, updateBoardViewModel);
2022-07-31 00:59:18 +03:00
setPitAnimator(pitAnimator);
onGameUpdate(pitAnimator, game);
unlistenMessages = listenMessages(game, pitAnimator);
2022-07-31 00:59:18 +03:00
setLoadingStateGame(LoadingState.Loaded({ value: game }))
} else if (loaded?.kind === "finished") {
setReplayRecord(loaded.record);
2022-07-31 00:59:18 +03:00
} else {
setLoadingStateGame(LoadingState.Error({ errorMessage: t("GameNotFound") }))
2022-07-31 00:59:18 +03:00
}
}).catch((error) => {
console.error(error);
setLoadingStateGame(LoadingState.Error({ errorMessage: t("ErrorWhenRetrievingInformation") }))
2022-07-31 00:59:18 +03:00
})
return () => {
unlistenMessages?.();
pitAnimator?.dispose();
};
}, []);
const textColorOnAppBar = getColorByBrightness(
context.themeManager.theme.appBarBgColor,
context.themeManager.theme.textColor,
context.themeManager.theme.textLightColor
);
const isMobile = width < 600;
const renderNewGameBtn = isSpectator || (userKeyWhoLeave || gameEnd || !game || (game && game.mancalaGame.state == "ended"));
const moves = (mancalaGame?.history ?? []) as unknown as PlayedMove[];
const isReviewing = viewedMove !== undefined && viewedMove < moves.length;
const shownBoardViewModel = isReviewing && mancalaGame
? createBoardViewModel(getBoardAfterMove(moves, viewedMove!), context.themeManager.theme)
: boardViewModel;
const isGameOver = !!(userKeyWhoLeave || gameEnd || mancalaGame?.state === "ended");
const isYourTurn = !isSpectator && !isGameOver && !!userKey && mancalaGame?.turnPlayerId === userKey;
const selectMove = (moveNumber: number) => setViewedMove(moveNumber >= moves.length ? undefined : Math.max(0, moveNumber));
useMoveKeys({
previous: () => !replayRecord && selectMove((isReviewing ? viewedMove! : moves.length) - 1),
next: () => !replayRecord && isReviewing && selectMove(viewedMove! + 1),
});
const playerInfo = (userId: string) => {
const info = [gameUsersConnectionInfo?.user1ConnectionInfo, gameUsersConnectionInfo?.user2ConnectionInfo]
.find((connectionInfo) => connectionInfo?.userId === userId);
return { userId, name: info?.name, isGuest: info?.isGuest ?? true };
};
// A game that ended by a timeout or inactivity is not over by the rules, so say why it ended.
const endText = gameEnd && (gameEnd.endReason === "timeout" || gameEnd.endReason === "inactive") && mancalaGame
? `${t("GameEnded")} · ${getResultText({
result: gameEnd.result, endReason: gameEnd.endReason,
player1: playerInfo(mancalaGame.player1Id),
player2: playerInfo(mancalaGame.player2Id),
} as FinishedGameSummary, isSpectator ? undefined : userKey, t)}`
: undefined;
const clockTimes = useGameClock(game, gameEnd);
const renderClock = (playerId: string) => {
const seat = mancalaGame && getSeat(mancalaGame, playerId);
if (!clockTimes || !seat) return undefined;
const timeMs = seat === "player1" ? clockTimes.player1Ms : clockTimes.player2Ms;
return <GameClockView context={context} timeMs={timeMs} running={clockTimes.runningSeat === seat} />;
};
2022-09-02 00:04:21 +03:00
const showBoardView = game && boardViewModel && userKey && true;
const topLocatedUserId = (isSpectator ? mancalaGame?.player2Id : getOpponentId()) || "0";
const bottomLocatedUserId = (isSpectator ? mancalaGame?.player1Id : userKey) || "1";
const topLocatedUserName = getPlayerName(topLocatedUserId);
const bottomLocatedUserName = getPlayerName(bottomLocatedUserId);
2022-09-02 00:04:21 +03:00
const topLocatedUser = {
id: topLocatedUserId,
name: topLocatedUserName ?? "Anonymous",
2022-09-02 00:04:21 +03:00
isOnline: isUserOnline(topLocatedUserId),
isAnonymous: !topLocatedUserName
2022-09-02 00:04:21 +03:00
};
const bottomLocatedUser = {
id: bottomLocatedUserId,
name: bottomLocatedUserName ?? "Anonymous",
2022-09-04 01:06:26 +03:00
isOnline: isSpectator ? isUserOnline(bottomLocatedUserId) : context.rtmt.connectionState === "connected",
isAnonymous: !bottomLocatedUserName
2022-09-02 00:04:21 +03:00
};
const currentUser = isSpectator ? {
id: "2",
name: "Anonymous",
2022-09-04 01:06:26 +03:00
isOnline: context.rtmt.connectionState === "connected",
2022-09-02 00:04:21 +03:00
isAnonymous: true
} : bottomLocatedUser;
const leftPlayer = userKeyWhoLeave ? (userKeyWhoLeave === topLocatedUser.id ? topLocatedUser : bottomLocatedUser) : undefined;
if (replayRecord) {
return <ReplayView context={context} theme={theme} record={replayRecord} userKey={userKey} />;
}
return (
<PageContainer>
2022-09-02 00:04:21 +03:00
{renderHeaderBar()}
{renderMobileBoardToolbar()}
{buildBoardTopToolbar()}
{showBoardView && isReviewing && (
<ReviewBanner
context={context}
moveNumber={viewedMove!}
isYourTurn={isYourTurn}
onBackToLive={() => setViewedMove(undefined)} />
)}
2022-07-31 00:59:18 +03:00
{showBoardView && (
<BoardView
game={game}
boardId={isReviewing ? `review-${viewedMove}` : boardId}
boardViewModel={shownBoardViewModel!}
2022-07-31 00:59:18 +03:00
context={context}
onPitSelect={onPitSelect}
revert={isPlayer2} />
2022-07-31 00:59:18 +03:00
)}
{showBoardView && (
<MoveList
context={context}
moves={moves}
selectedMove={isReviewing ? viewedMove! : moves.length}
onSelect={selectMove}
playerName={(playerId) => getPlayerName(playerId) ?? t("Anonymous")}
collapsedByDefault={isMobile} />
)}
2022-07-31 00:59:18 +03:00
<Center>
<LoadingComponent loadingState={gameLoadingState}></LoadingComponent>
2022-07-31 00:59:18 +03:00
</Center>
</PageContainer>
);
2022-09-02 00:04:21 +03:00
function renderHeaderBar() {
return <AppHeader context={context}>
{renderNewGameBtn
? <button className="btn pri ic-m" aria-label={t("NewGame")} onClick={onNewGameClick}>
<PlusIcon /><span className="hide-m">{t("NewGame")}</span>
</button>
: <button className="btn ghost ic-m" aria-label={t("Leave")} onClick={onLeaveGameClick}>
<LeaveIcon /><span className="hide-m">{t("Leave")}</span>
</button>}
</AppHeader>;
2022-09-02 00:04:21 +03:00
}
function renderMobileBoardToolbar() {
return <BoardToolbar style={{ justifyContent: "center" }} visible={showBoardView && isMobile || false}>
2022-09-03 21:06:52 +03:00
{buildInfoPanel({ visible: isMobile })}
2022-09-02 00:04:21 +03:00
</BoardToolbar>;
}
function buildBoardTopToolbar() {
return <BoardToolbar style={{ alignItems: "flex-end" }} visible={showBoardView || false}>
<UserStatus style={{
marginBottom: "0.5rem", marginLeft: "6%", maxWidth: isMobile ? "40vw" : "30vw",
width: isMobile ? "40vw" : "30vw"
}} context={context} layoutMode="left" user={topLocatedUser} visible={showBoardView || false}
accessory={renderClock(topLocatedUserId)} />
2022-09-03 21:06:52 +03:00
{buildInfoPanel({ visible: !isMobile })}
2022-09-02 00:04:21 +03:00
<UserStatus style={{
marginBottom: "0.5rem", marginRight: "6%", maxWidth: isMobile ? "40vw" : "30vw",
width: isMobile ? "40vw" : "30vw"
}} context={context} layoutMode="right" user={bottomLocatedUser} visible={showBoardView || false}
accessory={renderClock(bottomLocatedUserId)} />
2022-09-02 00:04:21 +03:00
</BoardToolbar>;
}
2022-09-03 21:06:52 +03:00
function buildInfoPanel(params: { visible: boolean }) {
2022-09-02 00:04:21 +03:00
return (
<InfoPanel
// Long texts such as "Game Ended · You Won · Opponent ran out of time" wrap on phones.
style={{ marginTop: "0.5rem", marginBottom: "0.5rem", ...(isMobile && { whiteSpace: "normal", textAlign: "center" }) }}
2022-09-02 00:04:21 +03:00
context={context}
game={game}
currentUser={currentUser}
whitePlayer={topLocatedUser}
blackPlayer={bottomLocatedUser}
leftPlayer={leftPlayer}
2022-09-03 21:06:52 +03:00
visible={params.visible}
isSpectator={isSpectator}
overrideText={endText} />
2022-09-02 00:04:21 +03:00
);
}
}
2022-09-02 00:04:21 +03:00
export default GamePage;