Compare commits
18 Commits
trunk
...
ed6fef5ef1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed6fef5ef1 | ||
|
|
0ed38ee098 | ||
|
|
743177486a | ||
|
|
2f861dbd38 | ||
|
|
522fdf106e | ||
|
|
d531a9bd6a | ||
|
|
c6dfed9bed | ||
|
|
ddb1575dc8 | ||
|
|
4ec4ac0242 | ||
|
|
f61ca0d0a1 | ||
|
|
6b3ab9a54e | ||
|
|
1dbe6b7ec0 | ||
|
|
2ae4c6a77b | ||
|
|
a0e4f54ed9 | ||
|
|
2c2e93649c | ||
|
|
12ae8dd6d8 | ||
|
|
1c28a603b7 | ||
|
|
e7ebb0223b |
90
app/AppContext.tsx
Normal file
90
app/AppContext.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
import useSocket from '@/hooks/useSocket';
|
||||
|
||||
import { GAME_START, LOCAL_DEFAULTS } from '@/constants';
|
||||
import type { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import type { GameUpdate, LocalSettings, Settings, Tilt } from '@/types';
|
||||
|
||||
const AppContext = createContext<AppContext | undefined>(undefined);
|
||||
|
||||
export interface AppContext {
|
||||
gameData: GameUpdate;
|
||||
isDM: boolean;
|
||||
noGame: boolean;
|
||||
selectCardIndex: number;
|
||||
settings: Settings;
|
||||
tilt: Tilt[];
|
||||
emitFlip: (cardIndex: number) => void;
|
||||
emitSettings: (gameData: GameUpdate) => void;
|
||||
emitRedraw: (cardIndex: number) => void;
|
||||
emitSelect: (cardID: string) => void;
|
||||
setGameID: (gameID: string) => void;
|
||||
setLocalSettings: Dispatch<SetStateAction<LocalSettings>>;
|
||||
setSelectCardIndex: (cardIndex: number) => void;
|
||||
setTilt: (tilt: Tilt[]) => void;
|
||||
}
|
||||
|
||||
export function AppProvider({ children }: { children: ReactNode }) {
|
||||
const [gameData, setGameData] = useState<GameUpdate>({ ...GAME_START });
|
||||
const [localSettings, setLocalSettings] = useState<LocalSettings>(() => ({ ...LOCAL_DEFAULTS }));
|
||||
const [gameID, setGameID] = useState('');
|
||||
const [noGame, setNoGame] = useState(false);
|
||||
const [selectCardIndex, setSelectCardIndex] = useState(-1);
|
||||
const [tilt, setTilt] = useState<Tilt[]>([]);
|
||||
|
||||
const { emitFlip, emitRedraw, emitSelect, emitSettings, emitTilt } = useSocket({
|
||||
gameID,
|
||||
setGameData,
|
||||
setNoGame,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (localSettings.remoteTilt) {
|
||||
const cardIndex = tilt.findIndex((tilt) => !!tilt);
|
||||
|
||||
if (tilt[cardIndex]) {
|
||||
emitTilt(cardIndex, tilt[cardIndex]);
|
||||
} else {
|
||||
// cardIndex does not matter
|
||||
// all tilts for this user will be cleared
|
||||
emitTilt(0, { rotateX: 0, rotateY: 0 });
|
||||
}
|
||||
}
|
||||
}, [tilt, localSettings]);
|
||||
|
||||
const handleSelect = (cardID: string) => {
|
||||
setSelectCardIndex(-1);
|
||||
|
||||
emitSelect(selectCardIndex, cardID);
|
||||
};
|
||||
|
||||
const { dmID } = gameData;
|
||||
const isDM = !!dmID;
|
||||
|
||||
const appInterface = {
|
||||
gameData,
|
||||
isDM,
|
||||
noGame,
|
||||
selectCardIndex,
|
||||
settings: { ...gameData.settings, ...localSettings },
|
||||
tilt,
|
||||
emitFlip,
|
||||
emitSettings,
|
||||
emitRedraw,
|
||||
emitSelect: handleSelect,
|
||||
setGameID,
|
||||
setLocalSettings,
|
||||
setSelectCardIndex,
|
||||
setTilt,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={appInterface}>{children}</AppContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAppContext(): AppContext {
|
||||
const context = useContext(AppContext);
|
||||
if (!context) throw new Error('useAppContext must be used within AppProvider');
|
||||
return context;
|
||||
}
|
||||
@@ -1,105 +1,35 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import useSocket from '@/hooks/useSocket';
|
||||
import { Eye } from 'lucide-react';
|
||||
|
||||
import Card from '@/components/Card';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import CardSelect from '@/components/CardSelect';
|
||||
import Notes from '@/components/Notes';
|
||||
import NotFound from '@/components/NotFound';
|
||||
import Settings from '@/components/Settings';
|
||||
import CardSelect from '@/components/CardSelect';
|
||||
|
||||
import { cardMap, layout } from '@/constants/tarokka';
|
||||
|
||||
import type { Deck, GameUpdate } from '@/types';
|
||||
import Settings from '@/components/Settings/index';
|
||||
import { SpectatorLink } from '@/components/SpectatorLink';
|
||||
import TarokkaGrid from '@/components/TarokkaGrid';
|
||||
|
||||
export default function GamePage() {
|
||||
const { gameID: gameIDParam } = useParams();
|
||||
|
||||
const [gameID, setGameID] = useState('');
|
||||
const [noGame, setNoGame] = useState(false);
|
||||
const [selectCard, setSelectCard] = useState(-1);
|
||||
const [gameData, setGameData] = useState<GameUpdate>({
|
||||
dmID: '',
|
||||
spectatorID: '',
|
||||
cards: [],
|
||||
settings: {
|
||||
positionBack: false,
|
||||
positionFront: false,
|
||||
prophecy: false,
|
||||
notes: false,
|
||||
cardStyle: 'color',
|
||||
},
|
||||
});
|
||||
|
||||
const { dmID, cards, settings } = gameData;
|
||||
const isDM = !!dmID;
|
||||
const selectDeck: Deck | null = selectCard >= 0 ? cards[selectCard].deck : null;
|
||||
|
||||
const socket = useSocket({ gameID, setGameData, setNoGame });
|
||||
const { noGame, setGameID } = useAppContext();
|
||||
const { gameID } = useParams();
|
||||
|
||||
useEffect(() => {
|
||||
if (gameIDParam) {
|
||||
setGameID(Array.isArray(gameIDParam) ? gameIDParam[0] : gameIDParam);
|
||||
if (gameID) {
|
||||
setGameID(Array.isArray(gameID) ? gameID[0] : gameID);
|
||||
}
|
||||
}, [gameIDParam]);
|
||||
|
||||
const select = (cardIndex: number, cardID: string) => {
|
||||
setSelectCard(-1);
|
||||
|
||||
socket.select(cardIndex, cardID);
|
||||
};
|
||||
|
||||
// map our five Tarokka cards to their proper locations in a 3x3 grid
|
||||
// common deck cards: left, top, and right
|
||||
// high deck cards: bottom and center
|
||||
const arrangeCards = (_cell: unknown, index: number) => cards[cardMap[index]];
|
||||
}, [gameID]);
|
||||
|
||||
return noGame ? (
|
||||
<NotFound />
|
||||
) : cards ? (
|
||||
) : (
|
||||
<main className="min-h-screen flex flex-col items-center justify-center gap-4 bg-[url('/img/table3.png')] bg-cover bg-center">
|
||||
{isDM && (
|
||||
<CopyButton
|
||||
copy={`${location.origin}/${gameData.spectatorID}`}
|
||||
tooltip={`Spectator link: ${location.origin}/${gameData.spectatorID}`}
|
||||
Icon={Eye}
|
||||
className={`fixed top-3 left-3 p-2 z-25 transition-all duration-250 text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700] cursor-pointer`}
|
||||
size={24}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isDM && <Settings gameData={gameData} changeAction={socket.handleSettings} />}
|
||||
<div className="grid grid-cols-3 grid-rows-3 gap-8 w-fit mx-auto">
|
||||
{Array.from({ length: 9 })
|
||||
.map(arrangeCards)
|
||||
.map((card, index) => (
|
||||
<div key={index} className="aspect-[2/3]}">
|
||||
{card && (
|
||||
<Card
|
||||
dm={isDM}
|
||||
card={card}
|
||||
position={layout[cardMap[index]]}
|
||||
settings={settings}
|
||||
flipAction={() => socket.flipCard(cardMap[index])}
|
||||
redrawAction={() => socket.redraw(cardMap[index])}
|
||||
selectAction={() => setSelectCard(cardMap[index])}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Notes gameData={gameData} show={cards.every(({ flipped }) => flipped)} />
|
||||
<CardSelect
|
||||
show={selectDeck}
|
||||
hand={cards}
|
||||
settings={settings}
|
||||
closeAction={() => setSelectCard(-1)}
|
||||
selectAction={(cardID) => select(selectCard, cardID)}
|
||||
/>
|
||||
<SpectatorLink />
|
||||
<Settings />
|
||||
<TarokkaGrid />
|
||||
<Notes />
|
||||
<CardSelect />
|
||||
</main>
|
||||
) : null;
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { Pirata_One, Eagle_Lake, Cinzel_Decorative } from 'next/font/google';
|
||||
import { AppProvider } from '@/app/AppContext';
|
||||
import './globals.css';
|
||||
|
||||
const pirataOne = Pirata_One({
|
||||
@@ -40,7 +41,9 @@ export default function RootLayout({
|
||||
lang="en"
|
||||
className={`${pirataOne.variable} ${eagleLake.variable} ${cinzel.variable} antialiased`}
|
||||
>
|
||||
<body className={`${eagleLake.className} antialiased`}>{children}</body>
|
||||
<body className={`${eagleLake.className} antialiased`}>
|
||||
<AppProvider>{children}</AppProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,48 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import TiltCard from '@/components/TiltCard';
|
||||
import ToolTip from '@/components/ToolTip';
|
||||
import StackTheDeck from '@/components/StackTheDeck';
|
||||
import tarokkaCards from '@/constants/tarokkaCards';
|
||||
import getCardInfo from '@/tools/getCardInfo';
|
||||
import getURL from '@/tools/getURL';
|
||||
|
||||
import { Layout, Settings, TarokkaGameCard } from '@/types';
|
||||
import tarokkaCards from '@/constants/tarokkaCards';
|
||||
import { layout } from '@/constants/tarokka';
|
||||
|
||||
import { TarokkaGameCard } from '@/types';
|
||||
|
||||
const cardBack = tarokkaCards.find((card) => card.back)!;
|
||||
|
||||
type CardProps = {
|
||||
dm: boolean;
|
||||
card: TarokkaGameCard;
|
||||
position: Layout;
|
||||
settings: Settings;
|
||||
flipAction: () => void;
|
||||
redrawAction: () => void;
|
||||
selectAction: () => void;
|
||||
cardIndex: number;
|
||||
};
|
||||
|
||||
export default function Card({
|
||||
dm,
|
||||
card,
|
||||
position,
|
||||
settings,
|
||||
flipAction,
|
||||
redrawAction,
|
||||
selectAction,
|
||||
}: CardProps) {
|
||||
export default function Card({ card, cardIndex }: CardProps) {
|
||||
const [tooltip, setTooltip] = useState<React.ReactNode>(null);
|
||||
const { emitFlip, gameData, emitRedraw, setSelectCardIndex } = useAppContext();
|
||||
|
||||
const { dmID, settings } = gameData;
|
||||
const isDM = !!dmID;
|
||||
|
||||
const { aria, flipped } = card;
|
||||
const position = layout[cardIndex];
|
||||
|
||||
const handleClick = () => {
|
||||
if (dm) {
|
||||
flipAction();
|
||||
if (isDM) {
|
||||
emitFlip(cardIndex);
|
||||
}
|
||||
};
|
||||
|
||||
const getTooltip = () => {
|
||||
const text = getCardInfo(card, position, dm, settings);
|
||||
const text = getCardInfo(card, position, isDM, settings);
|
||||
|
||||
return text.length ? (
|
||||
<>
|
||||
@@ -59,14 +54,15 @@ export default function Card({
|
||||
return (
|
||||
<ToolTip content={tooltip || getTooltip()}>
|
||||
<TiltCard
|
||||
className={`h-[21vh] w-[15vh] relative perspective transition-transform duration-200 z-0 hover:z-10 hover:scale-150 ${dm ? 'cursor-pointer' : ''} `}
|
||||
onClick={handleClick}
|
||||
className={`h-[21vh] w-[15vh] relative perspective transition-transform duration-200 z-0 hover:z-10 hover:scale-150 ${isDM ? 'cursor-pointer' : ''} `}
|
||||
cardIndex={cardIndex}
|
||||
>
|
||||
<div
|
||||
className={`absolute inset-0 transition-transform duration-500 transform-style-preserve-3d ${flipped ? 'rotate-y-180' : ''}`}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<div className="absolute inset-0 group backface-hidden">
|
||||
{dm && (
|
||||
{isDM && (
|
||||
<>
|
||||
<img src={getURL(card, settings)} alt={aria} className="absolute rounded-lg" />
|
||||
<img
|
||||
@@ -79,12 +75,12 @@ export default function Card({
|
||||
<img
|
||||
src={getURL(cardBack as TarokkaGameCard, settings)}
|
||||
alt="Card Back"
|
||||
className={`absolute rounded-lg ${dm ? 'transition duration-500 group-hover:opacity-0' : ''} ${settings.cardStyle === 'grayscale' ? 'border border-yellow-500/25 group-hover:drop-shadow-[0_0_3px_#ffd700/50]' : ''}`}
|
||||
className={`absolute rounded-lg ${isDM ? 'transition duration-500 group-hover:opacity-0' : ''} ${settings.cardStyle === 'grayscale' ? 'border border-yellow-500/25 group-hover:drop-shadow-[0_0_3px_#ffd700/50]' : ''}`}
|
||||
/>
|
||||
{dm && !flipped && (
|
||||
{isDM && !flipped && (
|
||||
<StackTheDeck
|
||||
onRedraw={redrawAction}
|
||||
onSelect={() => selectAction()}
|
||||
onRedraw={() => emitRedraw(cardIndex)}
|
||||
onSelect={() => setSelectCardIndex(cardIndex)}
|
||||
onHover={setTooltip}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,41 +1,36 @@
|
||||
'use client';
|
||||
|
||||
import { CircleX } from 'lucide-react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import TarokkaDeck from '@/lib/TarokkaDeck';
|
||||
import getURL from '@/tools/getURL';
|
||||
|
||||
import { Deck, Settings, TarokkaGameCard } from '@/types';
|
||||
import { Deck } from '@/types';
|
||||
|
||||
const tarokkaDeck = new TarokkaDeck();
|
||||
|
||||
type CardSelectProps = {
|
||||
closeAction: () => void;
|
||||
selectAction: (cardID: string) => void;
|
||||
hand: TarokkaGameCard[];
|
||||
settings: Settings;
|
||||
show: Deck | null;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function CardSelect({
|
||||
closeAction,
|
||||
selectAction,
|
||||
hand,
|
||||
settings,
|
||||
show,
|
||||
className = '',
|
||||
}: CardSelectProps) {
|
||||
export default function CardSelect({ className = '' }: CardSelectProps) {
|
||||
const { gameData, emitSelect, selectCardIndex, setSelectCardIndex } = useAppContext();
|
||||
const { cards: hand, settings } = gameData;
|
||||
|
||||
const handIDs = hand.map(({ id }) => id);
|
||||
const selectDeck: Deck | null = selectCardIndex >= 0 ? hand[selectCardIndex].deck : null;
|
||||
|
||||
const close = () => setSelectCardIndex(-1);
|
||||
|
||||
const handleClose = (event: React.MouseEvent<HTMLElement>) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
closeAction();
|
||||
close();
|
||||
}
|
||||
};
|
||||
|
||||
if (!show) return null;
|
||||
if (!selectDeck) return null;
|
||||
|
||||
const cards = show === 'high' ? tarokkaDeck.getHigh() : tarokkaDeck.getLow();
|
||||
const cards = selectDeck === 'high' ? tarokkaDeck.getHigh() : tarokkaDeck.getLow();
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -44,7 +39,7 @@ export default function CardSelect({
|
||||
>
|
||||
<button
|
||||
className={`fixed top-4 right-4 p-2 transition-all duration-250 text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700] cursor-pointer`}
|
||||
onClick={closeAction}
|
||||
onClick={close}
|
||||
>
|
||||
<CircleX className="w-6 h-6" />
|
||||
</button>
|
||||
@@ -58,7 +53,7 @@ export default function CardSelect({
|
||||
<div
|
||||
key={card.id}
|
||||
className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10`}
|
||||
onClick={() => selectAction(card.id)}
|
||||
onClick={() => emitSelect(card.id)}
|
||||
>
|
||||
<img
|
||||
src={getURL(card, settings)}
|
||||
|
||||
@@ -3,20 +3,18 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { ScrollText } from 'lucide-react';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import Scrim from '@/components/Scrim';
|
||||
import getCardInfo from '@/tools/getCardInfo';
|
||||
import { cardMap, layout } from '@/constants/tarokka';
|
||||
|
||||
import { GameUpdate } from '@/types';
|
||||
export default function Notes() {
|
||||
const { gameData } = useAppContext();
|
||||
const { dmID, cards, settings } = gameData;
|
||||
|
||||
type NotesProps = {
|
||||
gameData: GameUpdate;
|
||||
show: boolean;
|
||||
};
|
||||
|
||||
export default function Notes({ gameData: { dmID, cards, settings }, show }: NotesProps) {
|
||||
const isDM = !!dmID;
|
||||
const show = cards.every(({ flipped }) => flipped);
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Settings as Gear } from 'lucide-react';
|
||||
import { Cinzel_Decorative } from 'next/font/google';
|
||||
|
||||
import BuyMeACoffee from '@/components/BuyMeACoffee';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import GitHubButton from '@/components/GitHubButton';
|
||||
import Scrim from '@/components/Scrim';
|
||||
import Switch from '@/components/Switch';
|
||||
import { CardStyle, GameUpdate } from '@/types';
|
||||
|
||||
const cinzel = Cinzel_Decorative({
|
||||
variable: '--font-cinzel',
|
||||
subsets: ['latin'],
|
||||
weight: '400',
|
||||
});
|
||||
|
||||
type SettingsProps = {
|
||||
gameData: GameUpdate;
|
||||
changeAction: (updatedSettings: GameUpdate) => void;
|
||||
};
|
||||
|
||||
const cardStyleOptions: CardStyle[] = ['standard', 'color', 'grayscale'];
|
||||
|
||||
export default function Settings({ gameData, changeAction }: SettingsProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const togglePermission = (key: string) => {
|
||||
changeAction({
|
||||
...gameData,
|
||||
settings: {
|
||||
...gameData.settings,
|
||||
[key]: !gameData.settings[key],
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const tuneRadio = (cardStyle: CardStyle) => {
|
||||
changeAction({
|
||||
...gameData,
|
||||
settings: {
|
||||
...gameData.settings,
|
||||
cardStyle,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const Links = () => (
|
||||
<>
|
||||
<CopyButton
|
||||
title="Copy DM link"
|
||||
copy={`${location.origin}/${gameData.dmID}`}
|
||||
tooltip={`${location.origin}/${gameData.dmID}`}
|
||||
className="flex flex-row content-between w-full py-1 px-2 transition-all duration-250 bg-slate-700 hover:bg-slate-600 hover:text-yellow-300 rounded-lg shadow"
|
||||
/>
|
||||
<CopyButton
|
||||
title="Copy Spectator link"
|
||||
copy={`${location.origin}/${gameData.spectatorID}`}
|
||||
tooltip={`${location.origin}/${gameData.spectatorID}`}
|
||||
className="flex flex-row content-between w-full py-1 px-2 transition-all duration-250 bg-slate-700 hover:bg-slate-600 hover:text-yellow-300 rounded-lg shadow"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
const Permissions = () => (
|
||||
<>
|
||||
{Object.entries(gameData.settings)
|
||||
.filter(([_key, value]) => typeof value === 'boolean')
|
||||
.map(([key, value]) => (
|
||||
<Switch key={key} label={key} value={value} toggleAction={() => togglePermission(key)} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
||||
const CardStyle = () => (
|
||||
<fieldset className="flex flex-col w-full">
|
||||
<div className="text-xs my-1">Card style:</div>
|
||||
<div className="inline-flex overflow-hidden rounded-md w-full">
|
||||
{cardStyleOptions.map((option, index) => (
|
||||
<label
|
||||
key={option}
|
||||
className={`flex justify-center items-center cursor-pointer w-full px-4 py-2 text-sm font-medium transition
|
||||
${gameData.settings.cardStyle === option ? 'bg-slate-700 text-yellow-300 font-extrabold' : 'bg-slate-800 hover:bg-slate-700'}
|
||||
${index === 0 ? 'rounded-l-md' : ''}
|
||||
${index === cardStyleOptions.length - 1 ? 'rounded-r-md' : ''}
|
||||
${index !== 0 && 'border-l border-gray-600'}
|
||||
border border-yellow-500 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700]
|
||||
`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="cardStyle"
|
||||
value={option}
|
||||
checked={gameData.settings.cardStyle === option}
|
||||
onChange={() => tuneRadio(option)}
|
||||
className="sr-only"
|
||||
/>
|
||||
{option}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={`fixed top-4 right-4 z-25 ${cinzel.className}`}>
|
||||
<Scrim
|
||||
clickAction={() => setOpen((prev) => !prev)}
|
||||
className={`transition-all duration-250 ${open ? 'pointer-events-auto opacity-100' : 'pointer-events-none opacity-0'}`}
|
||||
>
|
||||
<div
|
||||
className={`fixed top-4 right-4 flex flex-col items-center justify-evenly bg-slate-800 text-yellow-400 rounded-lg border border-yellow-400 py-3 px-4 transition-all duration-250 ${open ? 'opacity-100 w-[350px] h-[350px]' : 'opacity-0 w-0 h-0'}`}
|
||||
>
|
||||
<Links />
|
||||
<Permissions />
|
||||
<CardStyle />
|
||||
<span className="w-full flex flex-row justify-evenly">
|
||||
<GitHubButton className="h-[35px] w-[125px]" />
|
||||
<BuyMeACoffee className="h-[35px] w-[125px]" />
|
||||
</span>
|
||||
</div>
|
||||
</Scrim>
|
||||
<button
|
||||
className={`p-2 transition-all duration-250 text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700] cursor-pointer ${open ? 'pointer-events-none opacity-0' : 'pointer-events-auto opacity-100'}`}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<Gear className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
55
components/Settings/CardStyle.tsx
Normal file
55
components/Settings/CardStyle.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import type { CardStyle } from '@/types';
|
||||
|
||||
const cardStyleOptions: CardStyle[] = ['standard', 'color', 'grayscale'];
|
||||
|
||||
export default function CardStyle() {
|
||||
const { gameData, isDM, settings, emitSettings } = useAppContext();
|
||||
|
||||
const tuneRadio = (cardStyle: CardStyle) => {
|
||||
emitSettings({
|
||||
...gameData,
|
||||
settings: {
|
||||
...gameData.settings,
|
||||
cardStyle,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return isDM ? (
|
||||
<fieldset className="flex flex-col w-full">
|
||||
<div className="text-xs my-1">Card style:</div>
|
||||
<div className="inline-flex overflow-hidden rounded-md w-full">
|
||||
{cardStyleOptions.map((option, index) => (
|
||||
<label
|
||||
key={option}
|
||||
className={`
|
||||
cursor-pointer
|
||||
w-full px-4 py-2
|
||||
text-sm font-medium
|
||||
border border-yellow-500
|
||||
flex justify-center items-center
|
||||
transition hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700]
|
||||
${settings.cardStyle === option ? 'bg-slate-700 text-yellow-300 font-extrabold' : 'bg-slate-800 hover:bg-slate-700'}
|
||||
${index === 0 ? 'rounded-l-md' : ''}
|
||||
${index === cardStyleOptions.length - 1 ? 'rounded-r-md' : ''}
|
||||
${index !== 0 && 'border-l border-gray-600'}
|
||||
`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="cardStyle"
|
||||
value={option}
|
||||
checked={settings.cardStyle === option}
|
||||
onChange={() => tuneRadio(option)}
|
||||
className="sr-only"
|
||||
/>
|
||||
{option}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
) : null;
|
||||
}
|
||||
16
components/Settings/ExternalLinks.tsx
Normal file
16
components/Settings/ExternalLinks.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import BuyMeACoffee from '@/components/BuyMeACoffee';
|
||||
import GitHubButton from '@/components/GitHubButton';
|
||||
|
||||
export default function CardStyle() {
|
||||
const { isDM } = useAppContext();
|
||||
|
||||
return (
|
||||
<span className={`w-full flex flex-row ${isDM ? 'justify-evenly' : 'justify-between'}`}>
|
||||
<GitHubButton className="h-[35px] w-[125px]" />
|
||||
<BuyMeACoffee className="h-[35px] w-[125px]" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
27
components/Settings/GameLinks.tsx
Normal file
27
components/Settings/GameLinks.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
|
||||
export default function Links() {
|
||||
const { gameData, isDM } = useAppContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
{isDM && (
|
||||
<CopyButton
|
||||
title="Copy DM link"
|
||||
copy={`${location.origin}/${gameData.dmID}`}
|
||||
tooltip={`${location.origin}/${gameData.dmID}`}
|
||||
className="flex flex-row content-between w-full py-1 px-2 transition-all duration-250 bg-slate-700 hover:bg-slate-600 hover:text-yellow-300 rounded-lg shadow"
|
||||
/>
|
||||
)}
|
||||
<CopyButton
|
||||
title="Copy Spectator link"
|
||||
copy={`${location.origin}/${gameData.spectatorID}`}
|
||||
tooltip={`${location.origin}/${gameData.spectatorID}`}
|
||||
className="flex flex-row content-between w-full py-1 px-2 transition-all duration-250 bg-slate-700 hover:bg-slate-600 hover:text-yellow-300 rounded-lg shadow"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
34
components/Settings/Permissions.tsx
Normal file
34
components/Settings/Permissions.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import Switch from '@/components/Switch';
|
||||
import { LOCAL_SETTINGS, SPECTATOR_SETTINGS } from '@/constants';
|
||||
|
||||
export default function Permissions() {
|
||||
const { gameData, isDM, settings, emitSettings, setLocalSettings } = useAppContext();
|
||||
|
||||
const togglePermission = (key: string) => {
|
||||
if (LOCAL_SETTINGS.includes(key)) {
|
||||
setLocalSettings((prev) => ({ ...prev, [key]: !prev[key] }));
|
||||
} else if (isDM) {
|
||||
emitSettings({
|
||||
...gameData,
|
||||
settings: {
|
||||
...gameData.settings,
|
||||
[key]: !gameData.settings[key],
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{Object.entries(settings)
|
||||
.filter(([_key, value]) => typeof value === 'boolean')
|
||||
.filter(([key]) => isDM || SPECTATOR_SETTINGS.includes(key))
|
||||
.map(([key, value]) => (
|
||||
<Switch key={key} label={key} value={value} toggleAction={() => togglePermission(key)} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
56
components/Settings/index.tsx
Normal file
56
components/Settings/index.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Settings as Gear } from 'lucide-react';
|
||||
import { Cinzel_Decorative } from 'next/font/google';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import Scrim from '@/components/Scrim';
|
||||
|
||||
import CardStyle from './CardStyle';
|
||||
import ExternalLinks from './ExternalLinks';
|
||||
import GameLinks from './GameLinks';
|
||||
import Permissions from './Permissions';
|
||||
|
||||
const cinzel = Cinzel_Decorative({
|
||||
variable: '--font-cinzel',
|
||||
subsets: ['latin'],
|
||||
weight: '400',
|
||||
});
|
||||
|
||||
export default function Settings() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { isDM } = useAppContext();
|
||||
|
||||
return (
|
||||
<div className={`fixed top-4 right-4 z-25 ${cinzel.className}`}>
|
||||
<Scrim
|
||||
clickAction={() => setOpen((prev) => !prev)}
|
||||
className={`transition-all duration-250 ${open ? 'pointer-events-auto opacity-100' : 'pointer-events-none opacity-0'}`}
|
||||
>
|
||||
<div
|
||||
className={`
|
||||
fixed top-4 right-4
|
||||
flex flex-col items-center justify-evenly
|
||||
bg-slate-800 text-yellow-400
|
||||
rounded-lg border border-yellow-400
|
||||
h-full py-3 px-4
|
||||
transition-all duration-250
|
||||
${open ? `opacity-100 ${isDM ? 'w-[350px] max-h-[375px]' : 'w-[300px] max-h-[175px]'}` : 'opacity-0 w-0 max-h-0'}
|
||||
`}
|
||||
>
|
||||
<GameLinks />
|
||||
<Permissions />
|
||||
<CardStyle />
|
||||
<ExternalLinks />
|
||||
</div>
|
||||
</Scrim>
|
||||
<button
|
||||
className={`p-2 transition-all duration-250 text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700] cursor-pointer ${open ? 'pointer-events-none opacity-0' : 'pointer-events-auto opacity-100'}`}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<Gear className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
components/SpectatorLink.tsx
Normal file
19
components/SpectatorLink.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import { Eye } from 'lucide-react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
|
||||
export function SpectatorLink() {
|
||||
const { gameData } = useAppContext();
|
||||
|
||||
return (
|
||||
<CopyButton
|
||||
copy={`${location.origin}/${gameData.spectatorID}`}
|
||||
tooltip={`Spectator link: ${location.origin}/${gameData.spectatorID}`}
|
||||
Icon={Eye}
|
||||
className={`fixed top-3 left-3 p-2 z-25 transition-all duration-250 text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700] cursor-pointer`}
|
||||
size={24}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,41 @@
|
||||
import type { ChangeEventHandler } from 'react';
|
||||
|
||||
export interface SwitchProps {
|
||||
label: string;
|
||||
value: boolean;
|
||||
toggleAction: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
toggleAction: ChangeEventHandler<HTMLInputElement>;
|
||||
}
|
||||
|
||||
const nonInitialCaps = /(?!^)([A-Z])/g;
|
||||
|
||||
export default function Switch({ label, value, toggleAction }: SwitchProps) {
|
||||
return (
|
||||
<label className="flex items-center justify-between w-full gap-2 cursor-pointer text-yellow-400 hover:text-yellow-300">
|
||||
<span className="text-sm capitalize">{label}</span>
|
||||
<span className="text-sm capitalize">{label.replace(nonInitialCaps, ' $1')}</span>
|
||||
|
||||
<div className="relative inline-block w-8 h-4 align-middle select-none transition duration-200 ease-in">
|
||||
<input type="checkbox" checked={value} onChange={toggleAction} className="sr-only" />
|
||||
<div
|
||||
className={`block w-8 h-4 rounded-full transition ${
|
||||
value ? 'bg-slate-500' : 'bg-slate-600'
|
||||
}`}
|
||||
<input
|
||||
id={`switch-${label}`}
|
||||
type="checkbox"
|
||||
checked={value}
|
||||
onChange={toggleAction}
|
||||
className="sr-only peer"
|
||||
/>
|
||||
<div
|
||||
className={`absolute top-[2px] left-[2px] w-3 h-3 rounded-full transition-all duration-250 ease-out transform
|
||||
${value ? 'translate-x-4 scale-110' : 'scale-95'}
|
||||
${value ? 'bg-yellow-400' : 'bg-yellow-500'}`}
|
||||
className={`
|
||||
block w-8 h-4 rounded-full
|
||||
transition-colors duration-200 ease-in
|
||||
bg-slate-600 peer-checked:bg-slate-500
|
||||
`}
|
||||
/>
|
||||
<div
|
||||
className={`
|
||||
absolute top-[2px] left-[2px]
|
||||
w-3 h-3 rounded-full
|
||||
transition-all duration-250 ease-out
|
||||
translate-x-0 scale-95 bg-yellow-500
|
||||
peer-checked:translate-x-4 peer-checked:scale-110 peer-checked:bg-yellow-400
|
||||
`}
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
28
components/TarokkaGrid.tsx
Normal file
28
components/TarokkaGrid.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import Card from '@/components/Card';
|
||||
import { cardMap } from '@/constants/tarokka';
|
||||
import type {} from '@/types';
|
||||
|
||||
export default function TarokkaGrid() {
|
||||
const { gameData } = useAppContext();
|
||||
const { cards } = gameData;
|
||||
|
||||
// map our five Tarokka cards to their proper locations in a 3x3 grid
|
||||
// common deck cards: left, top, and right
|
||||
// high deck cards: bottom and center
|
||||
const arrangeCards = (_cell: unknown, index: number) => cards[cardMap[index]];
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-3 grid-rows-3 gap-8 w-fit mx-auto">
|
||||
{Array.from({ length: 9 })
|
||||
.map(arrangeCards)
|
||||
.map((card, index) => (
|
||||
<div key={index} className="aspect-[2/3]}">
|
||||
{card && <Card card={card} cardIndex={cardMap[index]} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,99 @@
|
||||
import { useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import throttle from '@/tools/throttle';
|
||||
|
||||
import { thirtyFPS } from '@/constants/time';
|
||||
import type { Tilt } from '@/types';
|
||||
|
||||
const ZERO_ROTATION = 'rotateX(0deg) rotateY(0deg)';
|
||||
|
||||
const tiltSheen = (sheen: HTMLDivElement, tiltX: number, tiltY: number) => {
|
||||
const rect = sheen.getBoundingClientRect();
|
||||
const centerX = rect.width / 2;
|
||||
const centerY = rect.height / 2;
|
||||
const sheenX = centerX + (tiltY / -20) * centerX;
|
||||
const sheenY = centerY + (tiltX / 20) * centerY;
|
||||
|
||||
sheen.style.opacity = '1';
|
||||
sheen.style.backgroundImage = `
|
||||
radial-gradient(
|
||||
circle at
|
||||
${sheenX}px ${sheenY}px,
|
||||
#ffffff44,
|
||||
#0000000f
|
||||
)
|
||||
`;
|
||||
};
|
||||
|
||||
export default function TiltCard({
|
||||
children,
|
||||
cardIndex,
|
||||
className = '',
|
||||
onClick = () => {},
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
cardIndex: number;
|
||||
className?: string;
|
||||
onClick: (event: React.MouseEvent) => void;
|
||||
}) {
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
const sheenRef = useRef<HTMLDivElement>(null);
|
||||
const [untilt, setUntilt] = useState(false);
|
||||
const {
|
||||
gameData,
|
||||
settings: { tilt, remoteTilt },
|
||||
setTilt,
|
||||
tilt: localTilts,
|
||||
} = useAppContext();
|
||||
|
||||
const handleMouseMove = (e: React.MouseEvent) => {
|
||||
useEffect(() => {
|
||||
const card = cardRef.current;
|
||||
const sheen = sheenRef.current;
|
||||
if (!card || !sheen) return;
|
||||
|
||||
if (tilt) {
|
||||
const rotateX = localTilts[cardIndex]?.rotateX || 0;
|
||||
const rotateY = localTilts[cardIndex]?.rotateY || 0;
|
||||
|
||||
const tilts = remoteTilt
|
||||
? [...gameData.tilts[cardIndex], { rotateX, rotateY }]
|
||||
: [{ rotateX, rotateY }];
|
||||
|
||||
const { totalX, totalY, count } = tilts
|
||||
.filter(({ rotateX, rotateY }) => !!rotateX && !!rotateY)
|
||||
.reduce(
|
||||
({ totalX, totalY, count }, { rotateX, rotateY }) => ({
|
||||
totalX: totalX + rotateX,
|
||||
totalY: totalY + rotateY,
|
||||
count: ++count,
|
||||
}),
|
||||
{ totalX: 0, totalY: 0, count: 0 },
|
||||
);
|
||||
|
||||
if (count && (totalX || totalY)) {
|
||||
setUntilt(false);
|
||||
|
||||
const x = totalX / count;
|
||||
const y = totalY / count;
|
||||
|
||||
card.style.transform = `rotateX(${x}deg) rotateY(${y}deg)`;
|
||||
tiltSheen(sheen, x, y);
|
||||
} else {
|
||||
setUntilt(true);
|
||||
}
|
||||
} else if (card.style.transform !== ZERO_ROTATION) {
|
||||
setUntilt(true);
|
||||
}
|
||||
}, [tilt, localTilts, gameData]);
|
||||
|
||||
useEffect(() => {
|
||||
const card = cardRef.current;
|
||||
const sheen = sheenRef.current;
|
||||
if (!card || !sheen || !untilt) return;
|
||||
|
||||
card.style.transform = ZERO_ROTATION;
|
||||
sheen.style.opacity = '0';
|
||||
}, [untilt]);
|
||||
|
||||
const handleMouseMove = throttle((e: React.MouseEvent) => {
|
||||
const card = cardRef.current;
|
||||
if (!card) return;
|
||||
|
||||
@@ -24,24 +106,32 @@ export default function TiltCard({
|
||||
const rotateX = ((y - centerY) / centerY) * -20;
|
||||
const rotateY = ((x - centerX) / centerX) * 20;
|
||||
|
||||
card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
|
||||
};
|
||||
const newTilt: Tilt[] = [];
|
||||
newTilt[cardIndex] = { rotateX, rotateY };
|
||||
|
||||
setTilt(newTilt);
|
||||
}, thirtyFPS);
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
const card = cardRef.current;
|
||||
if (!card) return;
|
||||
card.style.transform = `rotateX(0deg) rotateY(0deg)`;
|
||||
setTilt([]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${className}`}
|
||||
onMouseMove={handleMouseMove}
|
||||
className={`group ${className}`}
|
||||
onMouseMove={tilt ? handleMouseMove : undefined}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div ref={cardRef} className={`h-full w-full transition-transform duration-0`}>
|
||||
<div
|
||||
ref={cardRef}
|
||||
onAnimationEnd={() => setUntilt(false)}
|
||||
className={`h-full w-full transition-transform ${untilt ? 'duration-500' : 'duration-0'}`}
|
||||
>
|
||||
{children}
|
||||
<div
|
||||
ref={sheenRef}
|
||||
className="pointer-events-none absolute inset-0 rounded-lg bg-gradient-to-tr from-transparent via-white/20 to-transparent mix-blend-screen opacity-0 transition-opacity duration-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
33
constants/index.ts
Normal file
33
constants/index.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
export * from '@/constants/standardCards';
|
||||
export * from '@/constants/tarokka';
|
||||
export * from '@/constants/tarokkaCards';
|
||||
export * from '@/constants/time';
|
||||
|
||||
import type { GameUpdate, LocalSettings, Settings } from '@/types';
|
||||
|
||||
export const SETTINGS: Settings = {
|
||||
cardStyle: 'color',
|
||||
notes: false,
|
||||
positionBack: false,
|
||||
positionFront: false,
|
||||
prophecy: false,
|
||||
tilt: true,
|
||||
remoteTilt: false,
|
||||
};
|
||||
|
||||
export const GAME_START: GameUpdate = {
|
||||
dmID: '',
|
||||
spectatorID: '',
|
||||
cards: [],
|
||||
settings: SETTINGS,
|
||||
tilts: Array.from({ length: 5 }, () => []),
|
||||
};
|
||||
|
||||
export const LOCAL_DEFAULTS: LocalSettings = {
|
||||
tilt: true,
|
||||
remoteTilt: true,
|
||||
};
|
||||
|
||||
export const LOCAL_SETTINGS = ['tilt', 'remoteTilt'];
|
||||
|
||||
export const SPECTATOR_SETTINGS = ['tilt', 'remoteTilt'];
|
||||
@@ -2,3 +2,5 @@ export const SECOND = 1000;
|
||||
export const MINUTE = 60 * SECOND;
|
||||
export const HOUR = 60 * MINUTE;
|
||||
export const DAY = 24 * HOUR;
|
||||
|
||||
export const thirtyFPS = SECOND / 30;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { socket } from '@/socket';
|
||||
|
||||
import type { GameUpdate } from '@/types';
|
||||
import type { GameUpdate, Tilt } from '@/types';
|
||||
|
||||
interface UseSocketProps {
|
||||
gameID: string;
|
||||
@@ -10,15 +9,21 @@ interface UseSocketProps {
|
||||
}
|
||||
|
||||
export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketProps) {
|
||||
const [connect, setConnect] = useState(1);
|
||||
const [disconnected, setDisconnected] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (gameID) {
|
||||
socket.emit('join', gameID);
|
||||
|
||||
socket.on('init', (data: GameUpdate) => {
|
||||
setDisconnected(false);
|
||||
setGameData(data);
|
||||
});
|
||||
|
||||
socket.on('game-update', (data: GameUpdate) => {
|
||||
// remove user's own tilts in favor of local values
|
||||
data.tilts = data.tilts.map((card) => card.filter((tilt) => tilt.playerID !== socket.id));
|
||||
setGameData(data);
|
||||
});
|
||||
|
||||
@@ -30,28 +35,47 @@ export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketP
|
||||
socket.on('flip-error', (error) => {
|
||||
console.error('Error:', error);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setDisconnected(true);
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
socket.removeAllListeners();
|
||||
};
|
||||
}, [gameID]);
|
||||
}, [gameID, connect]);
|
||||
|
||||
const emitFlip = (cardIndex: number) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
const flipCard = (cardIndex: number) => {
|
||||
socket.emit('flip-card', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
});
|
||||
};
|
||||
|
||||
const redraw = (cardIndex: number) => {
|
||||
const emitSettings = (gameData: GameUpdate) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
socket.emit('settings', {
|
||||
gameID,
|
||||
gameData,
|
||||
});
|
||||
};
|
||||
|
||||
const emitRedraw = (cardIndex: number) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
socket.emit('redraw', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
});
|
||||
};
|
||||
|
||||
const select = (cardIndex: number, cardID: string) => {
|
||||
const emitSelect = (cardIndex: number, cardID: string) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
socket.emit('select', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
@@ -59,17 +83,20 @@ export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketP
|
||||
});
|
||||
};
|
||||
|
||||
const handleSettings = (gameData: GameUpdate) => {
|
||||
socket.emit('settings', {
|
||||
gameID,
|
||||
gameData,
|
||||
const emitTilt = (cardIndex: number, tilt: Tilt) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
socket.emit('tilt', {
|
||||
cardIndex,
|
||||
tilt,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
flipCard,
|
||||
redraw,
|
||||
select,
|
||||
handleSettings,
|
||||
emitFlip,
|
||||
emitSettings,
|
||||
emitRedraw,
|
||||
emitSelect,
|
||||
emitTilt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import Deck from '@/lib/TarokkaDeck';
|
||||
import generateID from '@/tools/simpleID';
|
||||
import parseMilliseconds from '@/tools/parseMilliseconds';
|
||||
import { HOUR, DAY } from '@/constants/time';
|
||||
import { GameState, GameUpdate, Settings } from '@/types';
|
||||
|
||||
import { HOUR, DAY, SETTINGS } from '@/constants';
|
||||
import { GameState, GameUpdate, Settings, Tilt } from '@/types';
|
||||
|
||||
const deck = new Deck();
|
||||
|
||||
@@ -84,13 +85,8 @@ export default class GameStore {
|
||||
players: new Set(),
|
||||
cards: deck.getHand(),
|
||||
lastUpdated: Date.now(),
|
||||
settings: {
|
||||
positionBack: true,
|
||||
positionFront: true,
|
||||
prophecy: true,
|
||||
notes: true,
|
||||
cardStyle: 'color',
|
||||
},
|
||||
settings: SETTINGS,
|
||||
tilts: Array.from({ length: 5 }, () => []),
|
||||
};
|
||||
|
||||
this.totalCreated++;
|
||||
@@ -111,11 +107,15 @@ export default class GameStore {
|
||||
return this.gameUpdate(game);
|
||||
}
|
||||
|
||||
leaveGame(game: GameState, playerID: string): GameState {
|
||||
leaveGame(playerID: string): GameUpdate {
|
||||
const game = this.getGameByPlayerID(playerID);
|
||||
|
||||
this.players.delete(playerID);
|
||||
game.players.delete(playerID);
|
||||
this._clearTilts(game, playerID);
|
||||
game.lastUpdated = Date.now();
|
||||
|
||||
return game;
|
||||
return this.gameUpdate(game);
|
||||
}
|
||||
|
||||
flipCard(gameID: string, cardIndex: number): GameUpdate {
|
||||
@@ -157,6 +157,27 @@ export default class GameStore {
|
||||
return this.gameUpdate(game);
|
||||
}
|
||||
|
||||
tilt(playerID: string, cardIndex: number, { rotateX, rotateY }: Tilt) {
|
||||
const game = this.getGameByPlayerID(playerID);
|
||||
const cardTilts = game.tilts[cardIndex];
|
||||
|
||||
if (!cardTilts) throw new Error(`Card tilts ${cardIndex} not found`);
|
||||
|
||||
this._clearTilts(game, playerID);
|
||||
|
||||
if (rotateX && rotateY) {
|
||||
game.tilts[cardIndex] = [...game.tilts[cardIndex], { playerID, rotateX, rotateY }];
|
||||
game.lastUpdated = Date.now();
|
||||
}
|
||||
|
||||
return this.gameUpdate(game);
|
||||
}
|
||||
|
||||
_clearTilts(game: GameState, playerID: string) {
|
||||
game.tilts = game.tilts.map((card) => card.filter((tilt) => tilt.playerID !== playerID));
|
||||
game.lastUpdated = Date.now();
|
||||
}
|
||||
|
||||
updateSettings(gameID: string, settings: Settings) {
|
||||
const game = this.getGame(gameID);
|
||||
|
||||
@@ -173,24 +194,27 @@ export default class GameStore {
|
||||
return game;
|
||||
}
|
||||
|
||||
gameUpdate(game: GameState): GameUpdate {
|
||||
const { dmID, spectatorID, cards, settings } = game;
|
||||
getGameByPlayerID(playerID: string): GameState {
|
||||
const game = this.players.get(playerID);
|
||||
|
||||
return { dmID, spectatorID, cards, settings };
|
||||
if (!game) throw new Error(`Player ${playerID} not found`);
|
||||
|
||||
return game;
|
||||
}
|
||||
|
||||
playerExit(playerID: string): GameState | null {
|
||||
gameUpdate(game: GameState): GameUpdate {
|
||||
const { dmID, spectatorID, cards, settings, tilts } = game;
|
||||
|
||||
return { dmID, spectatorID, cards, settings, tilts };
|
||||
}
|
||||
|
||||
playerExit(playerID: string): GameUpdate | null {
|
||||
if (this.startUps.has(playerID)) {
|
||||
this.startUps.delete(playerID);
|
||||
|
||||
return null;
|
||||
} else {
|
||||
const game = this.players.get(playerID);
|
||||
|
||||
if (!game) throw new Error(`Player ${playerID} not found`);
|
||||
|
||||
this.players.delete(playerID);
|
||||
return this.leaveGame(game, playerID);
|
||||
return this.leaveGame(playerID);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
36
server.ts
36
server.ts
@@ -4,7 +4,9 @@ import { Server as SocketIOServer, type Socket } from 'socket.io';
|
||||
|
||||
import GameStore from '@/lib/GameStore';
|
||||
import omit from '@/tools/omit';
|
||||
import type { ClientUpdate, GameUpdate } from '@/types';
|
||||
|
||||
import { thirtyFPS } from '@/constants/time';
|
||||
import type { ClientUpdate, GameUpdate, Tilt } from '@/types';
|
||||
|
||||
const dev = process.env.NODE_ENV !== 'production';
|
||||
const hostname = '0.0.0.0';
|
||||
@@ -15,9 +17,10 @@ const handler = app.getRequestHandler();
|
||||
|
||||
const gameStore = new GameStore();
|
||||
|
||||
const timedReleases = {};
|
||||
|
||||
app.prepare().then(() => {
|
||||
const httpServer = createServer(handler);
|
||||
|
||||
const io = new SocketIOServer(httpServer);
|
||||
|
||||
const broadcast = (event: string, gameUpdate: GameUpdate) => {
|
||||
@@ -25,6 +28,25 @@ app.prepare().then(() => {
|
||||
io.to(gameUpdate.spectatorID).emit(event, omit(gameUpdate, 'dmID'));
|
||||
};
|
||||
|
||||
const timedRelease = (event: string, gameUpdate: GameUpdate, threshold: number) => {
|
||||
const now = Date.now();
|
||||
const lastEvent = timedReleases[event];
|
||||
clearTimeout(lastEvent?.to);
|
||||
|
||||
if (lastEvent?.embargo >= now) {
|
||||
const embargo = lastEvent.embargo - now;
|
||||
|
||||
const to = setTimeout(() => {
|
||||
broadcast(event, gameUpdate);
|
||||
}, embargo);
|
||||
|
||||
timedReleases[event] = { embargo, to };
|
||||
} else {
|
||||
broadcast(event, gameUpdate);
|
||||
timedReleases[event] = { embargo: now + threshold };
|
||||
}
|
||||
};
|
||||
|
||||
io.on('connection', (socket: Socket) => {
|
||||
//console.log(Date.now(), `Client connected: ${socket.id}`);
|
||||
|
||||
@@ -119,6 +141,16 @@ app.prepare().then(() => {
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('tilt', ({ cardIndex, tilt }: { cardIndex: number; tilt: Tilt }) => {
|
||||
try {
|
||||
const gameState = gameStore.tilt(socket.id, cardIndex, tilt);
|
||||
timedRelease('game-update', gameState, thirtyFPS);
|
||||
} catch (e) {
|
||||
const error = e instanceof Error ? e.message : e;
|
||||
console.error(Date.now(), 'Error[tilt]', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
try {
|
||||
const game = gameStore.playerExit(socket.id);
|
||||
|
||||
12
tools/throttle.ts
Normal file
12
tools/throttle.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export default function throttle(func: Function, threshold: number) {
|
||||
let lastCall = 0;
|
||||
|
||||
return (...args: any[]) => {
|
||||
const now = Date.now();
|
||||
|
||||
if (now - lastCall >= threshold) {
|
||||
lastCall = now;
|
||||
func(...args);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -4,11 +4,18 @@ export type CardStyle = 'standard' | 'color' | 'grayscale';
|
||||
export type Deck = 'high' | 'common' | 'both' | 'back' | 'all';
|
||||
|
||||
export interface Settings {
|
||||
cardStyle: CardStyle;
|
||||
notes: boolean;
|
||||
positionBack: boolean;
|
||||
positionFront: boolean;
|
||||
prophecy: boolean;
|
||||
notes: boolean;
|
||||
cardStyle: CardStyle;
|
||||
tilt: boolean;
|
||||
remoteTilt: boolean;
|
||||
}
|
||||
|
||||
export interface LocalSettings {
|
||||
tilt: boolean;
|
||||
remoteTilt: boolean;
|
||||
}
|
||||
|
||||
export interface StandardCard {
|
||||
@@ -82,6 +89,7 @@ export interface GameState {
|
||||
cards: TarokkaGameCard[];
|
||||
lastUpdated: number;
|
||||
settings: Settings;
|
||||
tilts: Tilt[][];
|
||||
}
|
||||
|
||||
export interface GameUpdate {
|
||||
@@ -89,6 +97,7 @@ export interface GameUpdate {
|
||||
spectatorID: string;
|
||||
cards: TarokkaGameCard[];
|
||||
settings: Settings;
|
||||
tilts: Tilt[][];
|
||||
}
|
||||
|
||||
export interface ClientUpdate {
|
||||
@@ -103,3 +112,9 @@ export interface Layout {
|
||||
name: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface Tilt {
|
||||
playerID?: string;
|
||||
rotateX: number;
|
||||
rotateY: number;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user