Compare commits
1 Commits
use-reduce
...
rtc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa938f7258 |
@@ -1,91 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
import useSocket from '@/hooks/useSocket';
|
||||
import { reduceTilts } from '@/tools';
|
||||
|
||||
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;
|
||||
tilts: 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;
|
||||
setLocalTilt: (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 [localTilt, setLocalTilt] = useState<Tilt[]>([]);
|
||||
|
||||
const { emitFlip, emitRedraw, emitSelect, emitSettings, emitTilt } = useSocket({
|
||||
gameID,
|
||||
setGameData,
|
||||
setNoGame,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (localSettings.remoteTilt) {
|
||||
const cardIndex = localTilt.findIndex((tilt) => !!tilt);
|
||||
|
||||
if (localTilt[cardIndex]) {
|
||||
emitTilt(cardIndex, localTilt[cardIndex]);
|
||||
} else {
|
||||
// cardIndex does not matter
|
||||
// all tilts for this user will be cleared
|
||||
emitTilt(0, { percentX: -1, percentY: -1, rotateX: 0, rotateY: 0 });
|
||||
}
|
||||
}
|
||||
}, [localTilt, 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 },
|
||||
tilts: reduceTilts(gameData, localTilt),
|
||||
emitFlip,
|
||||
emitSettings,
|
||||
emitRedraw,
|
||||
emitSelect: handleSelect,
|
||||
setGameID,
|
||||
setLocalSettings,
|
||||
setSelectCardIndex,
|
||||
setLocalTilt,
|
||||
};
|
||||
|
||||
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,35 +1,108 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import useSocket from '@/hooks/useSocket';
|
||||
import useRTC from '@/hooks/useRTC';
|
||||
import { Eye } from 'lucide-react';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import CardSelect from '@/components/CardSelect';
|
||||
import Card from '@/components/Card';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import Notes from '@/components/Notes';
|
||||
import NotFound from '@/components/NotFound';
|
||||
import Settings from '@/components/Settings/index';
|
||||
import { SpectatorLink } from '@/components/SpectatorLink';
|
||||
import TarokkaGrid from '@/components/TarokkaGrid';
|
||||
import Settings from '@/components/Settings';
|
||||
import CardSelect from '@/components/CardSelect';
|
||||
|
||||
import { cardMap, layout } from '@/constants/tarokka';
|
||||
|
||||
import type { Deck, GameUpdate } from '@/types';
|
||||
|
||||
export default function GamePage() {
|
||||
const { noGame, setGameID } = useAppContext();
|
||||
const { gameID } = useParams();
|
||||
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 rtc = useRTC(socket);
|
||||
console.log('useRTC:', rtc);
|
||||
|
||||
useEffect(() => {
|
||||
if (gameID) {
|
||||
setGameID(Array.isArray(gameID) ? gameID[0] : gameID);
|
||||
if (gameIDParam) {
|
||||
setGameID(Array.isArray(gameIDParam) ? gameIDParam[0] : gameIDParam);
|
||||
}
|
||||
}, [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]];
|
||||
|
||||
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">
|
||||
<SpectatorLink />
|
||||
<Settings />
|
||||
<TarokkaGrid />
|
||||
<Notes />
|
||||
<CardSelect />
|
||||
{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)}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
) : null;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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({
|
||||
@@ -41,9 +40,7 @@ export default function RootLayout({
|
||||
lang="en"
|
||||
className={`${pirataOne.variable} ${eagleLake.variable} ${cinzel.variable} antialiased`}
|
||||
>
|
||||
<body className={`${eagleLake.className} antialiased`}>
|
||||
<AppProvider>{children}</AppProvider>
|
||||
</body>
|
||||
<body className={`${eagleLake.className} antialiased`}>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,43 +1,48 @@
|
||||
'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 Sheen from '@/components/Sheen';
|
||||
import { getCardInfo, getURL } from '@/tools';
|
||||
|
||||
import tarokkaCards from '@/constants/tarokkaCards';
|
||||
import { layout } from '@/constants/tarokka';
|
||||
import getCardInfo from '@/tools/getCardInfo';
|
||||
import getURL from '@/tools/getURL';
|
||||
|
||||
import { TarokkaGameCard } from '@/types';
|
||||
import { Layout, Settings, TarokkaGameCard } from '@/types';
|
||||
|
||||
const cardBack = tarokkaCards.find((card) => card.back)!;
|
||||
|
||||
type CardProps = {
|
||||
dm: boolean;
|
||||
card: TarokkaGameCard;
|
||||
cardIndex: number;
|
||||
position: Layout;
|
||||
settings: Settings;
|
||||
flipAction: () => void;
|
||||
redrawAction: () => void;
|
||||
selectAction: () => void;
|
||||
};
|
||||
|
||||
export default function Card({ card, cardIndex }: CardProps) {
|
||||
export default function Card({
|
||||
dm,
|
||||
card,
|
||||
position,
|
||||
settings,
|
||||
flipAction,
|
||||
redrawAction,
|
||||
selectAction,
|
||||
}: 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 (isDM) {
|
||||
emitFlip(cardIndex);
|
||||
if (dm) {
|
||||
flipAction();
|
||||
}
|
||||
};
|
||||
|
||||
const getTooltip = () => {
|
||||
const text = getCardInfo(card, position, isDM, settings);
|
||||
const text = getCardInfo(card, position, dm, settings);
|
||||
|
||||
return text.length ? (
|
||||
<>
|
||||
@@ -54,15 +59,14 @@ export default function Card({ card, cardIndex }: CardProps) {
|
||||
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 ${isDM ? 'cursor-pointer' : ''} `}
|
||||
cardIndex={cardIndex}
|
||||
className={`h-[21vh] w-[15vh] relative perspective transition-transform duration-200 z-0 hover:z-10 hover:scale-150 ${dm ? 'cursor-pointer' : ''} `}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<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">
|
||||
{isDM && (
|
||||
{dm && (
|
||||
<>
|
||||
<img src={getURL(card, settings)} alt={aria} className="absolute rounded-lg" />
|
||||
<img
|
||||
@@ -75,16 +79,15 @@ export default function Card({ card, cardIndex }: CardProps) {
|
||||
<img
|
||||
src={getURL(cardBack as TarokkaGameCard, settings)}
|
||||
alt="Card Back"
|
||||
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]' : ''}`}
|
||||
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]' : ''}`}
|
||||
/>
|
||||
{isDM && !flipped && (
|
||||
{dm && !flipped && (
|
||||
<StackTheDeck
|
||||
onRedraw={() => emitRedraw(cardIndex)}
|
||||
onSelect={() => setSelectCardIndex(cardIndex)}
|
||||
onRedraw={redrawAction}
|
||||
onSelect={() => selectAction()}
|
||||
onHover={setTooltip}
|
||||
/>
|
||||
)}
|
||||
<Sheen cardIndex={cardIndex} />
|
||||
</div>
|
||||
<div className="absolute inset-0 backface-hidden rotate-y-180">
|
||||
<img
|
||||
@@ -92,7 +95,6 @@ export default function Card({ card, cardIndex }: CardProps) {
|
||||
alt={aria}
|
||||
className="rounded-lg border border-yellow-500/25 hover:drop-shadow-[0_0_3px_#ffd700/50]"
|
||||
/>
|
||||
<Sheen cardIndex={cardIndex} />
|
||||
</div>
|
||||
</div>
|
||||
</TiltCard>
|
||||
|
||||
@@ -1,36 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { CircleX } from 'lucide-react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import TarokkaDeck from '@/lib/TarokkaDeck';
|
||||
import { getURL } from '@/tools';
|
||||
import getURL from '@/tools/getURL';
|
||||
|
||||
import { Deck } from '@/types';
|
||||
import { Deck, Settings, TarokkaGameCard } 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({ className = '' }: CardSelectProps) {
|
||||
const { gameData, emitSelect, selectCardIndex, setSelectCardIndex } = useAppContext();
|
||||
const { cards: hand, settings } = gameData;
|
||||
|
||||
export default function CardSelect({
|
||||
closeAction,
|
||||
selectAction,
|
||||
hand,
|
||||
settings,
|
||||
show,
|
||||
className = '',
|
||||
}: CardSelectProps) {
|
||||
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) {
|
||||
close();
|
||||
closeAction();
|
||||
}
|
||||
};
|
||||
|
||||
if (!selectDeck) return null;
|
||||
if (!show) return null;
|
||||
|
||||
const cards = selectDeck === 'high' ? tarokkaDeck.getHigh() : tarokkaDeck.getLow();
|
||||
const cards = show === 'high' ? tarokkaDeck.getHigh() : tarokkaDeck.getLow();
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -39,7 +44,7 @@ export default function CardSelect({ className = '' }: CardSelectProps) {
|
||||
>
|
||||
<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={close}
|
||||
onClick={closeAction}
|
||||
>
|
||||
<CircleX className="w-6 h-6" />
|
||||
</button>
|
||||
@@ -53,7 +58,7 @@ export default function CardSelect({ className = '' }: CardSelectProps) {
|
||||
<div
|
||||
key={card.id}
|
||||
className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10`}
|
||||
onClick={() => emitSelect(card.id)}
|
||||
onClick={() => selectAction(card.id)}
|
||||
>
|
||||
<img
|
||||
src={getURL(card, settings)}
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { CircleX, ScrollText } from 'lucide-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';
|
||||
import getCardInfo from '@/tools/getCardInfo';
|
||||
import { cardMap, layout } from '@/constants/tarokka';
|
||||
|
||||
export default function Notes() {
|
||||
const { gameData } = useAppContext();
|
||||
const { dmID, cards, settings } = gameData;
|
||||
import { GameUpdate } from '@/types';
|
||||
|
||||
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);
|
||||
|
||||
@@ -51,24 +53,13 @@ export default function Notes() {
|
||||
className={`transition-all duration-250 ${showNotes ? 'pointer-events-auto opacity-100' : 'pointer-events-none opacity-0'}`}
|
||||
>
|
||||
<div
|
||||
className={`
|
||||
fixed bottom-4 right-4
|
||||
transition-all duration-250
|
||||
bg-slate-800
|
||||
border border-yellow-400 rounded-lg
|
||||
${showNotes ? 'sm:w-[50vw] sm:h-[67vh] w-[80vw] h-[80vh]' : 'w-0 h-0'}
|
||||
`}
|
||||
className={`fixed bottom-4 right-4 transition-all duration-250 bg-slate-800 border border-yellow-400 rounded-lg space-y-2 ${showNotes ? 'sm:w-[33vw] sm:h-[67vh] w-[80vw] h-[80vh]' : 'w-0 h-0'}`}
|
||||
>
|
||||
<CopyButton
|
||||
copy={notes.map((note) => note!.join('\n')).join('\n\n')}
|
||||
className={`
|
||||
absolute top-2 right-2
|
||||
cursor-pointer p-2
|
||||
transition-all duration-250
|
||||
text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700]
|
||||
`}
|
||||
className="text-yellow-400 hover:drop-shadow-[0_0_1px_#ffd700] absolute top-2 right-2 p-2 transition-all duration-250 bg-black/20 hover:bg-black/40 rounded-full cursor-pointer"
|
||||
/>
|
||||
<div className="text-yellow-400 h-full overflow-scroll p-8 transition-all delay-200 duration-50 ${showNotes ? 'opacity-100' : 'opacity-0'}">
|
||||
<div className="text-yellow-400 h-full overflow-scroll p-6 transition-all delay-200 duration-50 ${showNotes ? 'opacity-100' : 'opacity-0'}">
|
||||
{notes.map((note, index) => (
|
||||
<div key={index}>
|
||||
<div className="flex flex-col gap-2">
|
||||
@@ -81,17 +72,6 @@ export default function Notes() {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className={`
|
||||
fixed bottom-4 right-4
|
||||
cursor-pointer p-2
|
||||
transition-all duration-250
|
||||
text-yellow-400 hover:text-yellow-300 hover:drop-shadow-[0_0_3px_#ffd700]
|
||||
`}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<CircleX className="w-5 h-5" />
|
||||
</button>
|
||||
</Scrim>
|
||||
</div>
|
||||
);
|
||||
|
||||
133
components/Settings.tsx
Normal file
133
components/Settings.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import type { CardStyle } from '@/types';
|
||||
|
||||
const cardStyleOptions: CardStyle[] = ['standard', 'color', 'grayscale'];
|
||||
|
||||
export default function CardStyle({ className }: { className?: string }) {
|
||||
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 ${className}`}>
|
||||
<div className="text-xs ml-1 mb-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
|
||||
cursor-pointer
|
||||
w-full px-3 py-2
|
||||
text-xs font-medium
|
||||
border border-yellow-500
|
||||
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;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import BuyMeACoffee from '@/components/BuyMeACoffee';
|
||||
import GitHubButton from '@/components/GitHubButton';
|
||||
|
||||
export default function CardStyle({ className }: { className?: string }) {
|
||||
return (
|
||||
<span className={`w-full flex flex-row justify-between ${className}`}>
|
||||
<GitHubButton className="h-[35px] w-[125px]" />
|
||||
<BuyMeACoffee className="h-[35px] w-[125px]" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
|
||||
export default function Links({ className }: { className?: string }) {
|
||||
const { gameData, isDM } = useAppContext();
|
||||
|
||||
return (
|
||||
<div className={`w-full flex flex-col justify-between gap-2 ${className}`}>
|
||||
{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"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
'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)} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { CircleX, 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-between
|
||||
bg-slate-800 text-yellow-400
|
||||
rounded-lg border border-yellow-400
|
||||
h-full p-8
|
||||
transition-all duration-250
|
||||
${open ? `opacity-100 ${isDM ? 'w-[350px] max-h-[425px]' : 'w-[325px] max-h-[200px]'}` : 'opacity-0 w-0 max-h-0'}
|
||||
`}
|
||||
>
|
||||
<GameLinks />
|
||||
<Permissions />
|
||||
<CardStyle />
|
||||
<ExternalLinks />
|
||||
</div>
|
||||
<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={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<CircleX className="w-5 h-5" />
|
||||
</button>
|
||||
</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`}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<Gear className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import { validTilt } from '@/tools';
|
||||
|
||||
const tiltSheen = (sheen: HTMLDivElement, x: number, y: number) => {
|
||||
const rect = sheen.getBoundingClientRect();
|
||||
const sheenX = rect.width - x * rect.width;
|
||||
const sheenY = rect.height - y * rect.height;
|
||||
|
||||
sheen.style.opacity = '1';
|
||||
sheen.style.backgroundImage = `
|
||||
radial-gradient(
|
||||
circle at
|
||||
${sheenX}px ${sheenY}px,
|
||||
#ffffff44,
|
||||
#0000000f
|
||||
)
|
||||
`;
|
||||
};
|
||||
|
||||
export default function Sheen({ cardIndex, className }: { cardIndex: number; className?: string }) {
|
||||
const sheenRef = useRef<HTMLDivElement>(null);
|
||||
const [untilt, setUntilt] = useState(false);
|
||||
const { tilts } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
const sheen = sheenRef.current;
|
||||
if (!sheen) return;
|
||||
|
||||
const tilt = tilts[cardIndex];
|
||||
|
||||
if (validTilt(tilt)) {
|
||||
setUntilt(false);
|
||||
tiltSheen(sheen, tilt.percentX, tilt.percentY);
|
||||
} else {
|
||||
setUntilt(true);
|
||||
}
|
||||
}, [tilts]);
|
||||
|
||||
useEffect(() => {
|
||||
const sheen = sheenRef.current;
|
||||
if (!sheen || !untilt) return;
|
||||
|
||||
sheen.style.opacity = '0';
|
||||
}, [untilt]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={sheenRef}
|
||||
className={`
|
||||
absolute inset-0
|
||||
rounded-lg pointer-events-none
|
||||
transition-opacity duration-500
|
||||
bg-gradient-to-tr from-transparent via-white/20 to-transparent mix-blend-screen opacity-0
|
||||
${className}
|
||||
`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
'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,44 +1,25 @@
|
||||
import type { ChangeEventHandler } from 'react';
|
||||
|
||||
export interface SwitchProps {
|
||||
label: string;
|
||||
value: boolean;
|
||||
toggleAction: ChangeEventHandler<HTMLInputElement>;
|
||||
className?: string;
|
||||
toggleAction: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
}
|
||||
|
||||
const nonInitialCaps = /(?!^)([A-Z])/g;
|
||||
|
||||
export default function Switch({ label, value, toggleAction, className }: SwitchProps) {
|
||||
export default function Switch({ label, value, toggleAction }: SwitchProps) {
|
||||
return (
|
||||
<label
|
||||
className={`flex items-center justify-between gap-2 w-full cursor-pointer text-yellow-400 hover:text-yellow-300 ${className}`}
|
||||
>
|
||||
<span className="text-sm capitalize">{label.replace(nonInitialCaps, ' $1')}</span>
|
||||
<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>
|
||||
|
||||
<div className="relative inline-block w-8 h-4 align-middle select-none transition duration-200 ease-in">
|
||||
<input
|
||||
id={`switch-${label}`}
|
||||
type="checkbox"
|
||||
checked={value}
|
||||
onChange={toggleAction}
|
||||
className="sr-only peer"
|
||||
<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'
|
||||
}`}
|
||||
/>
|
||||
<div
|
||||
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
|
||||
`}
|
||||
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'}`}
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
'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,47 +1,17 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useAppContext } from '@/app/AppContext';
|
||||
import { throttle, validTilt } from '@/tools';
|
||||
|
||||
import { thirtyFPS } from '@/constants/time';
|
||||
import type { Tilt } from '@/types';
|
||||
|
||||
const ZERO_ROTATION = 'rotateX(0deg) rotateY(0deg)';
|
||||
import { useRef } from 'react';
|
||||
|
||||
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 [untilt, setUntilt] = useState(false);
|
||||
const { settings, tilts, setLocalTilt } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
const card = cardRef.current;
|
||||
if (!card) return;
|
||||
|
||||
const tilt = tilts[cardIndex];
|
||||
|
||||
if (validTilt(tilt)) {
|
||||
setUntilt(false);
|
||||
card.style.transform = `rotateX(${tilt.rotateX}deg) rotateY(${tilt.rotateY}deg)`;
|
||||
} else {
|
||||
setUntilt(true);
|
||||
}
|
||||
}, [tilts]);
|
||||
|
||||
useEffect(() => {
|
||||
const card = cardRef.current;
|
||||
if (!card || !untilt) return;
|
||||
|
||||
card.style.transform = ZERO_ROTATION;
|
||||
}, [untilt]);
|
||||
|
||||
const handleMouseMove = throttle((e: React.MouseEvent) => {
|
||||
const handleMouseMove = (e: React.MouseEvent) => {
|
||||
const card = cardRef.current;
|
||||
if (!card) return;
|
||||
|
||||
@@ -53,35 +23,24 @@ export default function TiltCard({
|
||||
|
||||
const rotateX = ((y - centerY) / centerY) * -20;
|
||||
const rotateY = ((x - centerX) / centerX) * 20;
|
||||
const percentX = x / rect.width;
|
||||
const percentY = y / rect.height;
|
||||
|
||||
const newTilt: Tilt[] = [];
|
||||
newTilt[cardIndex] = {
|
||||
percentX,
|
||||
percentY,
|
||||
rotateX,
|
||||
rotateY,
|
||||
};
|
||||
|
||||
setLocalTilt(newTilt);
|
||||
}, thirtyFPS);
|
||||
card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
|
||||
};
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
setLocalTilt([]);
|
||||
const card = cardRef.current;
|
||||
if (!card) return;
|
||||
card.style.transform = `rotateX(0deg) rotateY(0deg)`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group ${className}`}
|
||||
onMouseMove={settings.tilt ? handleMouseMove : undefined}
|
||||
className={`${className}`}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div
|
||||
ref={cardRef}
|
||||
onAnimationEnd={() => setUntilt(false)}
|
||||
className={`h-full w-full transition-transform ${untilt ? 'duration-500' : 'duration-0'}`}
|
||||
>
|
||||
<div ref={cardRef} className={`h-full w-full transition-transform duration-0`}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
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: true,
|
||||
positionBack: true,
|
||||
positionFront: true,
|
||||
prophecy: true,
|
||||
tilt: true,
|
||||
remoteTilt: true,
|
||||
};
|
||||
|
||||
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,5 +2,3 @@ export const SECOND = 1000;
|
||||
export const MINUTE = 60 * SECOND;
|
||||
export const HOUR = 60 * MINUTE;
|
||||
export const DAY = 24 * HOUR;
|
||||
|
||||
export const thirtyFPS = SECOND / 30;
|
||||
|
||||
95
hooks/useChatGPT.ts
Normal file
95
hooks/useChatGPT.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
|
||||
interface CursorPosition {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface PeerMouseHook {
|
||||
cursors: Record<string, CursorPosition>;
|
||||
}
|
||||
|
||||
export function usePeerMouse(roomId: string): PeerMouseHook {
|
||||
const [cursors, setCursors] = useState<Record<string, CursorPosition>>({});
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
const peers = useRef<Record<string, RTCPeerConnection>>({});
|
||||
const channels = useRef<Record<string, RTCDataChannel>>({});
|
||||
|
||||
useEffect(() => {
|
||||
const socket = io();
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.emit('join-room', roomId);
|
||||
|
||||
socket.on('new-peer', async (peerId: string) => {
|
||||
const pc = createPeer(peerId, true);
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
socket.emit('signal', { to: peerId, data: { description: pc.localDescription } });
|
||||
});
|
||||
|
||||
socket.on('signal', async ({ from, data }) => {
|
||||
const pc = peers.current[from] || createPeer(from, false);
|
||||
|
||||
if (data.description) {
|
||||
await pc.setRemoteDescription(data.description);
|
||||
|
||||
if (data.description.type === 'offer') {
|
||||
const answer = await pc.createAnswer();
|
||||
await pc.setLocalDescription(answer);
|
||||
socket.emit('signal', { to: from, data: { description: pc.localDescription } });
|
||||
}
|
||||
}
|
||||
|
||||
if (data.candidate) {
|
||||
await pc.addIceCandidate(data.candidate);
|
||||
}
|
||||
});
|
||||
|
||||
function createPeer(peerId: string, isInitiator: boolean): RTCPeerConnection {
|
||||
const pc = new RTCPeerConnection();
|
||||
|
||||
if (isInitiator) {
|
||||
const channel = pc.createDataChannel('mouse');
|
||||
setupChannel(peerId, channel);
|
||||
} else {
|
||||
pc.ondatachannel = (e) => setupChannel(peerId, e.channel);
|
||||
}
|
||||
|
||||
pc.onicecandidate = (e) => {
|
||||
if (e.candidate) {
|
||||
socket.emit('signal', { to: peerId, data: { candidate: e.candidate } });
|
||||
}
|
||||
};
|
||||
|
||||
peers.current[peerId] = pc;
|
||||
return pc;
|
||||
}
|
||||
|
||||
function setupChannel(peerId: string, channel: RTCDataChannel) {
|
||||
channels.current[peerId] = channel;
|
||||
channel.onmessage = (e) => {
|
||||
const pos = JSON.parse(e.data);
|
||||
setCursors((prev) => ({ ...prev, [peerId]: pos }));
|
||||
};
|
||||
}
|
||||
|
||||
function handleMouseMove(e: MouseEvent) {
|
||||
const pos = JSON.stringify({ x: e.clientX, y: e.clientY });
|
||||
Object.values(channels.current).forEach((ch) => {
|
||||
if (ch.readyState === 'open') ch.send(pos);
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener('mousemove', handleMouseMove);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('mousemove', handleMouseMove);
|
||||
socket.disconnect();
|
||||
Object.values(peers.current).forEach((pc) => pc.close());
|
||||
};
|
||||
}, [roomId]);
|
||||
|
||||
return { cursors };
|
||||
}
|
||||
54
hooks/useRTC.ts
Normal file
54
hooks/useRTC.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import RTCPeer from '@/lib/RTCPeer';
|
||||
|
||||
import type { UseSocket } from '@/hooks/useSocket';
|
||||
|
||||
import type {} from '@/types';
|
||||
|
||||
// interface UseSocketProps {
|
||||
// gameID: string;
|
||||
// setGameData: (gameUpdate: GameUpdate) => void;
|
||||
// setNoGame: (noGame: boolean) => void;
|
||||
// }
|
||||
|
||||
const channelName = 'tilt';
|
||||
|
||||
export default function useRTC({
|
||||
ready,
|
||||
registerAnsweredReceiver,
|
||||
registerOfferredReceiver,
|
||||
rtcAnswer: sendAnswer,
|
||||
rtcOffer: sendOffer,
|
||||
}: UseSocket) {
|
||||
const [peers, setPeers] = useState<RTCPeer[]>([]);
|
||||
|
||||
const answerHandler = (answer: RTCSessionDescriptionInit) => {
|
||||
console.log('[useRTC] answer received', answer);
|
||||
console.log('[useRTC] peers:', peers.length);
|
||||
const peer = peers[0];
|
||||
console.log('peer:', peer);
|
||||
peer.onAnswer(answer);
|
||||
};
|
||||
|
||||
const offerHandler = (offer: RTCSessionDescriptionInit) => {
|
||||
console.log('[useRTC] offer received', offer);
|
||||
setPeers((peers) => {
|
||||
peers.push(new RTCPeer({ channelName, offer, sendAnswer, sendOffer }));
|
||||
return peers;
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (ready) {
|
||||
console.log('-=-= SETTING THINGS UP =-=-');
|
||||
registerAnsweredReceiver(answerHandler);
|
||||
registerOfferredReceiver(offerHandler);
|
||||
|
||||
setPeers([new RTCPeer({ channelName, sendAnswer, sendOffer })]);
|
||||
}
|
||||
}, [ready]);
|
||||
|
||||
return {
|
||||
count: peers.length,
|
||||
};
|
||||
}
|
||||
@@ -1,29 +1,41 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { socket } from '@/socket';
|
||||
import type { GameUpdate, Tilt } from '@/types';
|
||||
|
||||
interface UseSocketProps {
|
||||
import type { GameUpdate } from '@/types';
|
||||
|
||||
export interface UseSocketProps {
|
||||
gameID: string;
|
||||
setGameData: (gameUpdate: GameUpdate) => void;
|
||||
setNoGame: (noGame: boolean) => void;
|
||||
}
|
||||
|
||||
export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketProps) {
|
||||
const [connect, setConnect] = useState(1);
|
||||
const [disconnected, setDisconnected] = useState(true);
|
||||
export interface UseSocket {
|
||||
ready: boolean;
|
||||
flipCard: (cardIndex: number) => void;
|
||||
handleSettings: (cardData: GameUpdate) => void;
|
||||
redraw: (cardIndex: number) => void;
|
||||
rtcAnswer: (answer: RTCSessionDescriptionInit) => void;
|
||||
registerAnsweredReceiver: (receiver: (answer: RTCSessionDescriptionInit) => void) => void;
|
||||
rtcOffer: (offer: RTCSessionDescriptionInit) => void;
|
||||
registerOfferredReceiver: (receiver: (offer: RTCSessionDescriptionInit) => void) => void;
|
||||
select: (cardIndex: number, cardID: string) => void;
|
||||
}
|
||||
|
||||
export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketProps): UseSocket {
|
||||
const [ready, setReady] = useState(false);
|
||||
const answerRef = useRef<(answer: RTCSessionDescriptionInit) => void>(null);
|
||||
const offerRef = useRef<(offer: RTCSessionDescriptionInit) => void>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (gameID) {
|
||||
socket.emit('join', gameID);
|
||||
|
||||
socket.on('init', (data: GameUpdate) => {
|
||||
setDisconnected(false);
|
||||
setReady(true);
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -36,46 +48,58 @@ export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketP
|
||||
console.error('Error:', error);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setDisconnected(true);
|
||||
socket.on('rtc-answered', (answered: RTCSessionDescriptionInit) => {
|
||||
if (answerRef.current) answerRef.current(answered);
|
||||
});
|
||||
|
||||
socket.on('rtc-offered', (offered: RTCSessionDescriptionInit) => {
|
||||
if (offerRef.current) {
|
||||
offerRef.current(offered);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
socket.removeAllListeners();
|
||||
};
|
||||
}, [gameID, connect]);
|
||||
|
||||
const emitFlip = (cardIndex: number) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
}, [gameID]);
|
||||
|
||||
const flipCard = (cardIndex: number) => {
|
||||
console.log('flip-card', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
});
|
||||
socket.emit('flip-card', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
});
|
||||
};
|
||||
|
||||
const emitSettings = (gameData: GameUpdate) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
const handleSettings = (gameData: GameUpdate) => {
|
||||
socket.emit('settings', {
|
||||
gameID,
|
||||
gameData,
|
||||
});
|
||||
};
|
||||
|
||||
const emitRedraw = (cardIndex: number) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
const redraw = (cardIndex: number) => {
|
||||
socket.emit('redraw', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
});
|
||||
};
|
||||
|
||||
const emitSelect = (cardIndex: number, cardID: string) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
const rtcAnswer = (answer: RTCSessionDescriptionInit) => {
|
||||
console.log('rtc-answer', { gameID, answer });
|
||||
socket.emit('rtc-answer', { gameID, answer });
|
||||
};
|
||||
|
||||
const rtcOffer = (offer: RTCSessionDescriptionInit) => {
|
||||
console.log('rtc-offer', { gameID, offer });
|
||||
socket.emit('rtc-offer', { gameID, offer });
|
||||
};
|
||||
|
||||
const select = (cardIndex: number, cardID: string) => {
|
||||
socket.emit('select', {
|
||||
gameID,
|
||||
cardIndex,
|
||||
@@ -83,20 +107,17 @@ export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketP
|
||||
});
|
||||
};
|
||||
|
||||
const emitTilt = (cardIndex: number, tilt: Tilt) => {
|
||||
if (disconnected) setConnect(connect + 1);
|
||||
|
||||
socket.emit('tilt', {
|
||||
cardIndex,
|
||||
tilt,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
emitFlip,
|
||||
emitSettings,
|
||||
emitRedraw,
|
||||
emitSelect,
|
||||
emitTilt,
|
||||
ready,
|
||||
flipCard,
|
||||
handleSettings,
|
||||
redraw,
|
||||
rtcAnswer,
|
||||
registerAnsweredReceiver: (receiver: (obj: RTCSessionDescriptionInit) => void[]) =>
|
||||
(answerRef.current = receiver),
|
||||
rtcOffer,
|
||||
registerOfferredReceiver: (receiver: (obj: RTCSessionDescriptionInit) => void[]) =>
|
||||
(offerRef.current = receiver),
|
||||
select,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import Deck from '@/lib/TarokkaDeck';
|
||||
import { generateID, parseMilliseconds } from '@/tools';
|
||||
|
||||
import { HOUR, DAY, SETTINGS } from '@/constants';
|
||||
import { GameState, GameUpdate, Settings, Tilt } from '@/types';
|
||||
import generateID from '@/tools/simpleID';
|
||||
import parseMilliseconds from '@/tools/parseMilliseconds';
|
||||
import { HOUR, DAY } from '@/constants/time';
|
||||
import { GameState, GameUpdate, Settings } from '@/types';
|
||||
|
||||
const deck = new Deck();
|
||||
|
||||
@@ -84,8 +84,13 @@ export default class GameStore {
|
||||
players: new Set(),
|
||||
cards: deck.getHand(),
|
||||
lastUpdated: Date.now(),
|
||||
settings: SETTINGS,
|
||||
tilts: Array.from({ length: 5 }, () => []),
|
||||
settings: {
|
||||
positionBack: true,
|
||||
positionFront: true,
|
||||
prophecy: true,
|
||||
notes: true,
|
||||
cardStyle: 'color',
|
||||
},
|
||||
};
|
||||
|
||||
this.totalCreated++;
|
||||
@@ -106,15 +111,11 @@ export default class GameStore {
|
||||
return this.gameUpdate(game);
|
||||
}
|
||||
|
||||
leaveGame(playerID: string): GameUpdate {
|
||||
const game = this.getGameByPlayerID(playerID);
|
||||
|
||||
this.players.delete(playerID);
|
||||
leaveGame(game: GameState, playerID: string): GameState {
|
||||
game.players.delete(playerID);
|
||||
this._clearTilts(game, playerID);
|
||||
game.lastUpdated = Date.now();
|
||||
|
||||
return this.gameUpdate(game);
|
||||
return game;
|
||||
}
|
||||
|
||||
flipCard(gameID: string, cardIndex: number): GameUpdate {
|
||||
@@ -156,27 +157,6 @@ export default class GameStore {
|
||||
return this.gameUpdate(game);
|
||||
}
|
||||
|
||||
tilt(playerID: string, cardIndex: number, tilt: 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 (tilt.rotateX && tilt.rotateY) {
|
||||
game.tilts[cardIndex] = [...game.tilts[cardIndex], { ...tilt, playerID }];
|
||||
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);
|
||||
|
||||
@@ -193,27 +173,24 @@ export default class GameStore {
|
||||
return game;
|
||||
}
|
||||
|
||||
getGameByPlayerID(playerID: string): GameState {
|
||||
const game = this.players.get(playerID);
|
||||
|
||||
if (!game) throw new Error(`Player ${playerID} not found`);
|
||||
|
||||
return game;
|
||||
}
|
||||
|
||||
gameUpdate(game: GameState): GameUpdate {
|
||||
const { dmID, spectatorID, cards, settings, tilts } = game;
|
||||
const { dmID, spectatorID, cards, settings } = game;
|
||||
|
||||
return { dmID, spectatorID, cards, settings, tilts };
|
||||
return { dmID, spectatorID, cards, settings };
|
||||
}
|
||||
|
||||
playerExit(playerID: string): GameUpdate | null {
|
||||
playerExit(playerID: string): GameState | null {
|
||||
if (this.startUps.has(playerID)) {
|
||||
this.startUps.delete(playerID);
|
||||
|
||||
return null;
|
||||
} else {
|
||||
return this.leaveGame(playerID);
|
||||
const game = this.players.get(playerID);
|
||||
|
||||
if (!game) throw new Error(`Player ${playerID} not found`);
|
||||
|
||||
this.players.delete(playerID);
|
||||
return this.leaveGame(game, playerID);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
131
lib/RTCPeer.ts
Normal file
131
lib/RTCPeer.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
const servers = {
|
||||
iceServers: [
|
||||
{ url: 'stun:stun01.sipphone.com' },
|
||||
{ url: 'stun:stun.ekiga.net' },
|
||||
{ url: 'stun:stun.fwdnet.net' },
|
||||
{ url: 'stun:stun.ideasip.com' },
|
||||
{ url: 'stun:stun.iptel.org' },
|
||||
{ url: 'stun:stun.rixtelecom.se' },
|
||||
{ url: 'stun:stun.schlund.de' },
|
||||
{ url: 'stun:stun.l.google.com:19302' },
|
||||
{ url: 'stun:stun1.l.google.com:19302' },
|
||||
{ url: 'stun:stun2.l.google.com:19302' },
|
||||
{ url: 'stun:stun3.l.google.com:19302' },
|
||||
{ url: 'stun:stun4.l.google.com:19302' },
|
||||
{ url: 'stun:stunserver.org' },
|
||||
{ url: 'stun:stun.softjoys.com' },
|
||||
{ url: 'stun:stun.voiparound.com' },
|
||||
{ url: 'stun:stun.voipbuster.com' },
|
||||
{ url: 'stun:stun.voipstunt.com' },
|
||||
{ url: 'stun:stun.voxgratia.org' },
|
||||
{ url: 'stun:stun.xten.com' },
|
||||
|
||||
// {
|
||||
// url: 'turn:numb.viagenie.ca',
|
||||
// credential: 'muazkh',
|
||||
// username: 'webrtc@live.com',
|
||||
// },
|
||||
// {
|
||||
// url: 'turn:192.158.29.39:3478?transport=udp',
|
||||
// credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
|
||||
// username: '28224511:1379330808',
|
||||
// },
|
||||
// {
|
||||
// url: 'turn:192.158.29.39:3478?transport=tcp',
|
||||
// credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
|
||||
// username: '28224511:1379330808',
|
||||
// },
|
||||
],
|
||||
};
|
||||
|
||||
const pcConstraints = {
|
||||
optional: [{ DtlsSrtpKeyAgreement: true }],
|
||||
};
|
||||
|
||||
export interface RTCPeerProps {
|
||||
channelName: string;
|
||||
offer?: RTCSessionDescriptionInit;
|
||||
sendAnswer: (offer: RTCSessionDescriptionInit) => void;
|
||||
sendOffer: (offer: RTCSessionDescriptionInit) => void;
|
||||
}
|
||||
|
||||
export default class RTCPeer {
|
||||
channelName: string;
|
||||
peerConnection: RTCPeerConnection;
|
||||
channel: RTCDataChannel;
|
||||
|
||||
sendAnswer: (offer: RTCSessionDescriptionInit) => void;
|
||||
sendOffer: (offer: RTCSessionDescriptionInit) => void;
|
||||
|
||||
constructor({ channelName, offer, sendAnswer, sendOffer }: RTCPeerProps) {
|
||||
this.sendOffer = sendOffer;
|
||||
this.sendAnswer = sendAnswer;
|
||||
this.channelName = channelName;
|
||||
|
||||
this.peerConnection = new RTCPeerConnection(); //(servers, pcConstraints);
|
||||
this.peerConnection.onicecandidate = offer
|
||||
? this.#handleIceCandidateAnswer
|
||||
: this.#handleIceCandidateOffer;
|
||||
|
||||
this.#createDataChannel();
|
||||
|
||||
if (offer) {
|
||||
console.log('answer');
|
||||
this.peerConnection.setRemoteDescription(offer);
|
||||
this.peerConnection.createAnswer().then((answer) => {
|
||||
this.peerConnection.setLocalDescription(answer);
|
||||
});
|
||||
} else {
|
||||
console.log('call');
|
||||
this.peerConnection.createOffer().then((offer) => {
|
||||
this.peerConnection.setLocalDescription(offer);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onAnswer = (answer: RTCSessionDescriptionInit) => {
|
||||
this.peerConnection.setRemoteDescription(answer);
|
||||
};
|
||||
|
||||
#handleIceCandidateAnswer = (event: RTCPeerConnectionIceEvent) => {
|
||||
if (!event.candidate) {
|
||||
const answer = this.peerConnection.localDescription;
|
||||
|
||||
console.log('send-answer', { answer });
|
||||
if (answer) {
|
||||
this.sendAnswer(answer);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#handleIceCandidateOffer = (event: RTCPeerConnectionIceEvent) => {
|
||||
if (!event.candidate) {
|
||||
const offer = this.peerConnection.localDescription;
|
||||
|
||||
if (offer) {
|
||||
console.log('send-offer', { offer });
|
||||
this.sendOffer(offer);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#createDataChannel = () => {
|
||||
try {
|
||||
this.channel = this.peerConnection.createDataChannel(this.channelName);
|
||||
|
||||
this.channel.onopen = () => {
|
||||
console.log('Receive Channel[onopen]:', this.channel.readyState);
|
||||
};
|
||||
|
||||
this.channel.onmessage = (event: MessageEvent) => {
|
||||
console.log('Receive Channel[onmessage]:', event.data);
|
||||
};
|
||||
|
||||
this.channel.onclose = () => {
|
||||
console.log('Receive Channel[onclose]:', this.channel.readyState);
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[RTCPeer|#createDataChannel] ERROR', error);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getRandomItems } from '@/tools';
|
||||
import getRandomItems from '@/tools/getRandomItems';
|
||||
import cards from '@/constants/standardCards';
|
||||
import type { StandardCard } from '@/types';
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getRandomItems } from '@/tools';
|
||||
import getRandomItems from '@/tools/getRandomItems';
|
||||
import cards from '@/constants/tarokkaCards';
|
||||
import type { TarokkaCard, TarokkaGameCard } from '@/types';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tarokka",
|
||||
"version": "1.1.1",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "nodemon",
|
||||
|
||||
52
server.ts
52
server.ts
@@ -3,10 +3,8 @@ import { createServer } from 'http';
|
||||
import { Server as SocketIOServer, type Socket } from 'socket.io';
|
||||
|
||||
import GameStore from '@/lib/GameStore';
|
||||
import { omit } from '@/tools';
|
||||
|
||||
import { thirtyFPS } from '@/constants/time';
|
||||
import type { ClientUpdate, GameUpdate, Tilt } from '@/types';
|
||||
import omit from '@/tools/omit';
|
||||
import type { ClientUpdate, GameUpdate } from '@/types';
|
||||
|
||||
const dev = process.env.NODE_ENV !== 'production';
|
||||
const hostname = '0.0.0.0';
|
||||
@@ -17,10 +15,9 @@ 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) => {
|
||||
@@ -28,25 +25,6 @@ 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}`);
|
||||
|
||||
@@ -141,13 +119,29 @@ app.prepare().then(() => {
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('tilt', ({ cardIndex, tilt }: { cardIndex: number; tilt: Tilt }) => {
|
||||
socket.on('rtc-answer', ({ gameID, answer }: { gameID: string; answer: any }) => {
|
||||
try {
|
||||
const gameState = gameStore.tilt(socket.id, cardIndex, tilt);
|
||||
timedRelease('game-update', gameState, thirtyFPS);
|
||||
const gameState = gameStore.getGame(gameID);
|
||||
console.log('[rtc-answer]', gameID);
|
||||
|
||||
io.to(gameState.dmID).emit('rtc-answered', answer);
|
||||
io.to(gameState.spectatorID).emit('rtc-answered', answer);
|
||||
} catch (e) {
|
||||
const error = e instanceof Error ? e.message : e;
|
||||
console.error(Date.now(), 'Error[tilt]', error);
|
||||
console.error(Date.now(), 'Error[rtc-answer]', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('rtc-offer', ({ gameID, offer }: { gameID: string; offer: any }) => {
|
||||
try {
|
||||
const gameState = gameStore.getGame(gameID);
|
||||
console.log('[rtc-offer]', gameID);
|
||||
|
||||
io.to(gameState.dmID).emit('rtc-offered', offer);
|
||||
io.to(gameState.spectatorID).emit('rtc-offered', offer);
|
||||
} catch (e) {
|
||||
const error = e instanceof Error ? e.message : e;
|
||||
console.error(Date.now(), 'Error[rtc-offer]', error);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { isHighCard, isLowCard } from '@/tools';
|
||||
import { isHighCard, isLowCard } from '@/tools/cardTypes';
|
||||
import { Layout, Settings, TarokkaGameCard } from '@/types';
|
||||
|
||||
export const getCardInfo = (
|
||||
export default function getTooltip(
|
||||
card: TarokkaGameCard,
|
||||
position: Layout,
|
||||
dm: boolean,
|
||||
settings: Settings,
|
||||
) => {
|
||||
) {
|
||||
const { card: cardName, description, flipped } = card;
|
||||
|
||||
let text: string[] = [];
|
||||
@@ -39,4 +39,4 @@ export const getCardInfo = (
|
||||
}
|
||||
|
||||
return text;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const getRandomItems = <T>(items: T[], count: number): T[] => {
|
||||
export default function getRandomItems<T>(items: T[], count: number): T[] {
|
||||
const shuffled = [...items];
|
||||
|
||||
// Fisher-Yates shuffle
|
||||
@@ -8,4 +8,4 @@ export const getRandomItems = <T>(items: T[], count: number): T[] => {
|
||||
}
|
||||
|
||||
return count > shuffled.length ? shuffled : shuffled.slice(0, count);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { cardStyles, standardMap } from '@/constants/tarokka';
|
||||
import { Settings, TarokkaCard, TarokkaGameCard } from '@/types';
|
||||
|
||||
export const getURL = (card: TarokkaCard | TarokkaGameCard, settings: Settings) => {
|
||||
export default function getURL(card: TarokkaCard | TarokkaGameCard, settings: Settings) {
|
||||
const styleConfig = cardStyles[settings.cardStyle];
|
||||
const fileBase = settings.cardStyle === 'standard' ? standardMap[card.id] : card.id;
|
||||
return `${styleConfig.baseURL}${fileBase}${card.extension || styleConfig.extension}`;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
export * from '@/tools/cardTypes';
|
||||
export * from '@/tools/getCardInfo';
|
||||
export * from '@/tools/getRandomItems';
|
||||
export * from '@/tools/getURL';
|
||||
export * from '@/tools/log';
|
||||
export * from '@/tools/omit';
|
||||
export * from '@/tools/parseMilliseconds';
|
||||
export * from '@/tools/reduceTilts';
|
||||
export * from '@/tools/simpleID';
|
||||
export * from '@/tools/throttle';
|
||||
export * from '@/tools/validTilt';
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* A logging utility designed to be inserted into functional chains.
|
||||
* Logs all parameters with an optional prefix, then returns the first argument unchanged.
|
||||
*
|
||||
* @param {string} [prefix=''] - A label or message to prepend to the logged output.
|
||||
* @returns {(value: any, ...rest: any[]) => any} - A function that logs its arguments and returns the first one.
|
||||
*
|
||||
* @example
|
||||
* const result = [1, 2, 3]
|
||||
* .map((n) => n * 2)
|
||||
* .map(log('doubled:'))
|
||||
* .filter((n) => n > 2);
|
||||
*/
|
||||
export const log =
|
||||
(prefix: string = ''): ((value: any, ...rest: any[]) => any) =>
|
||||
(...args: any[]) => {
|
||||
console.log(prefix, ...args);
|
||||
return args[0];
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
export const omit = <T extends Record<string, any>>(
|
||||
export default function omit<T extends Record<string, any>>(
|
||||
obj: T,
|
||||
propToRemove: keyof T,
|
||||
): Omit<T, typeof propToRemove> => {
|
||||
): Omit<T, typeof propToRemove> {
|
||||
const { [propToRemove]: _, ...rest } = obj;
|
||||
return rest;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface ParsedMilliseconds {
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
export const parseMilliseconds = (timestamp: number): ParsedMilliseconds => {
|
||||
export default function parseMilliseconds(timestamp: number): ParsedMilliseconds {
|
||||
const days = Math.floor(timestamp / DAY);
|
||||
timestamp %= DAY;
|
||||
|
||||
@@ -21,4 +21,4 @@ export const parseMilliseconds = (timestamp: number): ParsedMilliseconds => {
|
||||
timestamp %= SECOND;
|
||||
|
||||
return { days, hours, minutes, seconds };
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { log, validTilt } from '@/tools';
|
||||
import { GameUpdate, Tilt } from '@/types';
|
||||
|
||||
const combineTilts = (tilts: Tilt[]) =>
|
||||
tilts.reduce(
|
||||
({ pX, pY, rX, rY, count }, { percentX, percentY, rotateX, rotateY }) => ({
|
||||
pX: pX + percentX,
|
||||
pY: pY + percentY,
|
||||
rX: rX + rotateX,
|
||||
rY: rY + rotateY,
|
||||
count: count + 1,
|
||||
}),
|
||||
{ pX: 0, pY: 0, rX: 0, rY: 0, count: 0 },
|
||||
);
|
||||
|
||||
export function reduceTilts(gameData: GameUpdate, localTilt: Tilt[]): Tilt[] {
|
||||
const remoteTilts = gameData.tilts;
|
||||
const tiltEnabled = gameData.settings.tilt;
|
||||
const remoteTiltEnabled = gameData.settings.remoteTilt;
|
||||
|
||||
if (!tiltEnabled) return [];
|
||||
if (!remoteTiltEnabled) return Array.from({ length: 5 }, (_, i) => localTilt[i]);
|
||||
|
||||
return Array.from({ length: 5 }, (_, i) => (localTilt[i] ? [localTilt[i]] : []))
|
||||
.map((cardTilts, cardIndex) => [...remoteTilts[cardIndex], ...cardTilts])
|
||||
.map((cardTilts) => cardTilts.filter(validTilt))
|
||||
.map(combineTilts)
|
||||
.map(({ pX, pY, rX, rY, count }) => ({
|
||||
percentX: count ? pX / count : -1,
|
||||
percentY: count ? pY / count : -1,
|
||||
rotateX: count ? rX / count : 0,
|
||||
rotateY: count ? rY / count : 0,
|
||||
}));
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { getRandomItems } from '@/tools';
|
||||
import getRandomItems from '@/tools/getRandomItems';
|
||||
|
||||
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
|
||||
|
||||
export const generateID = (length: number = 6) => {
|
||||
const generateID = (length: number = 6) => {
|
||||
return getRandomItems(alphabet.split(''), length).join('');
|
||||
};
|
||||
|
||||
export default generateID;
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
export function throttle(func: Function, threshold: number) {
|
||||
let lastCall = 0;
|
||||
|
||||
return (...args: any[]) => {
|
||||
const now = Date.now();
|
||||
|
||||
if (now - lastCall >= threshold) {
|
||||
lastCall = now;
|
||||
func(...args);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import { Tilt } from '@/types';
|
||||
|
||||
export const validTilt = ({ percentX, percentY, rotateX, rotateY }: Tilt) =>
|
||||
percentX >= 0 && percentY >= 0 && !!rotateX && !!rotateY;
|
||||
@@ -4,18 +4,11 @@ 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;
|
||||
tilt: boolean;
|
||||
remoteTilt: boolean;
|
||||
}
|
||||
|
||||
export interface LocalSettings {
|
||||
tilt: boolean;
|
||||
remoteTilt: boolean;
|
||||
notes: boolean;
|
||||
cardStyle: CardStyle;
|
||||
}
|
||||
|
||||
export interface StandardCard {
|
||||
@@ -89,7 +82,6 @@ export interface GameState {
|
||||
cards: TarokkaGameCard[];
|
||||
lastUpdated: number;
|
||||
settings: Settings;
|
||||
tilts: Tilt[][];
|
||||
}
|
||||
|
||||
export interface GameUpdate {
|
||||
@@ -97,7 +89,6 @@ export interface GameUpdate {
|
||||
spectatorID: string;
|
||||
cards: TarokkaGameCard[];
|
||||
settings: Settings;
|
||||
tilts: Tilt[][];
|
||||
}
|
||||
|
||||
export interface ClientUpdate {
|
||||
@@ -112,11 +103,3 @@ export interface Layout {
|
||||
name: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface Tilt {
|
||||
playerID?: string;
|
||||
percentX: number;
|
||||
percentY: number;
|
||||
rotateX: number;
|
||||
rotateY: number;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user