Compare commits

...

6 Commits

Author SHA1 Message Date
Gavin McDonald
2ae4c6a77b teletilting 2025-06-27 18:14:06 -04:00
Gavin McDonald
a0e4f54ed9 more refactoring 2025-06-26 15:30:03 -04:00
Gavin McDonald
2c2e93649c cleanup 2025-06-26 14:39:04 -04:00
Gavin McDonald
12ae8dd6d8 refactoring 2025-06-26 13:59:27 -04:00
Gavin McDonald
1c28a603b7 moved useSocket into Context 2025-06-25 18:09:29 -04:00
Gavin McDonald
e7ebb0223b added Context 2025-06-25 17:04:18 -04:00
14 changed files with 312 additions and 180 deletions

85
app/AppContext.tsx Normal file
View File

@@ -0,0 +1,85 @@
'use client';
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import useSocket from '@/hooks/useSocket';
import type { GameUpdate, Tilt } from '@/types';
const AppContext = createContext<AppContext | undefined>(undefined);
const gameStart: GameUpdate = {
dmID: '',
spectatorID: '',
cards: [],
settings: {
positionBack: false,
positionFront: false,
prophecy: false,
notes: false,
cardStyle: 'color',
},
tilts: Array.from({ length: 5 }, () => []),
};
export interface AppContext {
gameData: GameUpdate;
noGame: boolean;
tilt: Tilt[];
selectCardIndex: number;
flipCard: (cardIndex: number) => void;
handleSettings: (gameData: GameUpdate) => void;
redraw: (cardIndex: number) => void;
select: (cardID: string) => void;
setGameID: (gameID: string) => void;
setSelectCardIndex: (cardIndex: number) => void;
setTilt: (tilt: Tilt[]) => void;
}
export function AppProvider({ children }: { children: ReactNode }) {
const [gameData, setGameData] = useState<GameUpdate>(gameStart);
const [gameID, setGameID] = useState('');
const [noGame, setNoGame] = useState(false);
const [selectCardIndex, setSelectCardIndex] = useState(-1);
const [tilt, setTilt] = useState<Tilt[]>([]);
const { flipCard, redraw, select, handleSettings, emitTilt } = useSocket({
gameID,
setGameData,
setNoGame,
});
useEffect(() => {
const cardIndex = tilt.findIndex((tilt) => !!tilt);
if (tilt[cardIndex]) {
emitTilt(cardIndex, tilt[cardIndex]);
}
}, [tilt]);
const handleSelect = (cardID: string) => {
setSelectCardIndex(-1);
select(selectCardIndex, cardID);
};
const appInterface = {
gameData,
noGame,
tilt,
selectCardIndex,
flipCard,
handleSettings,
redraw,
select: handleSelect,
setGameID,
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;
}

View File

@@ -1,105 +1,35 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect } from 'react';
import { useParams } from 'next/navigation'; import { useParams } from 'next/navigation';
import useSocket from '@/hooks/useSocket';
import { Eye } from 'lucide-react';
import Card from '@/components/Card'; import { useAppContext } from '@/app/AppContext';
import CopyButton from '@/components/CopyButton'; import CardSelect from '@/components/CardSelect';
import Notes from '@/components/Notes'; import Notes from '@/components/Notes';
import NotFound from '@/components/NotFound'; import NotFound from '@/components/NotFound';
import Settings from '@/components/Settings'; import Settings from '@/components/Settings';
import CardSelect from '@/components/CardSelect'; import { SpectatorLink } from '@/components/SpectatorLink';
import TarokkaGrid from '@/components/TarokkaGrid';
import { cardMap, layout } from '@/constants/tarokka';
import type { Deck, GameUpdate } from '@/types';
export default function GamePage() { export default function GamePage() {
const { gameID: gameIDParam } = useParams(); const { noGame, setGameID } = useAppContext();
const { gameID } = 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 });
useEffect(() => { useEffect(() => {
if (gameIDParam) { if (gameID) {
setGameID(Array.isArray(gameIDParam) ? gameIDParam[0] : gameIDParam); setGameID(Array.isArray(gameID) ? gameID[0] : gameID);
} }
}, [gameIDParam]); }, [gameID]);
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 ? ( return noGame ? (
<NotFound /> <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"> <main className="min-h-screen flex flex-col items-center justify-center gap-4 bg-[url('/img/table3.png')] bg-cover bg-center">
{isDM && ( <SpectatorLink />
<CopyButton <Settings />
copy={`${location.origin}/${gameData.spectatorID}`} <TarokkaGrid />
tooltip={`Spectator link: ${location.origin}/${gameData.spectatorID}`} <Notes />
Icon={Eye} <CardSelect />
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> </main>
) : null; );
} }

View File

@@ -1,5 +1,6 @@
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { Pirata_One, Eagle_Lake, Cinzel_Decorative } from 'next/font/google'; import { Pirata_One, Eagle_Lake, Cinzel_Decorative } from 'next/font/google';
import { AppProvider } from '@/app/AppContext';
import './globals.css'; import './globals.css';
const pirataOne = Pirata_One({ const pirataOne = Pirata_One({
@@ -40,7 +41,9 @@ export default function RootLayout({
lang="en" lang="en"
className={`${pirataOne.variable} ${eagleLake.variable} ${cinzel.variable} antialiased`} 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> </html>
); );
} }

View File

@@ -1,48 +1,43 @@
'use client'; 'use client';
import { useState } from 'react'; import { useState } from 'react';
import { useAppContext } from '@/app/AppContext';
import TiltCard from '@/components/TiltCard'; import TiltCard from '@/components/TiltCard';
import ToolTip from '@/components/ToolTip'; import ToolTip from '@/components/ToolTip';
import StackTheDeck from '@/components/StackTheDeck'; import StackTheDeck from '@/components/StackTheDeck';
import tarokkaCards from '@/constants/tarokkaCards';
import getCardInfo from '@/tools/getCardInfo'; import getCardInfo from '@/tools/getCardInfo';
import getURL from '@/tools/getURL'; 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)!; const cardBack = tarokkaCards.find((card) => card.back)!;
type CardProps = { type CardProps = {
dm: boolean;
card: TarokkaGameCard; card: TarokkaGameCard;
position: Layout; cardIndex: number;
settings: Settings;
flipAction: () => void;
redrawAction: () => void;
selectAction: () => void;
}; };
export default function Card({ export default function Card({ card, cardIndex }: CardProps) {
dm,
card,
position,
settings,
flipAction,
redrawAction,
selectAction,
}: CardProps) {
const [tooltip, setTooltip] = useState<React.ReactNode>(null); const [tooltip, setTooltip] = useState<React.ReactNode>(null);
const { flipCard, gameData, redraw, setSelectCardIndex } = useAppContext();
const { dmID, settings } = gameData;
const isDM = !!dmID;
const { aria, flipped } = card; const { aria, flipped } = card;
const position = layout[cardIndex];
const handleClick = () => { const handleClick = () => {
if (dm) { if (isDM) {
flipAction(); flipCard(cardIndex);
} }
}; };
const getTooltip = () => { const getTooltip = () => {
const text = getCardInfo(card, position, dm, settings); const text = getCardInfo(card, position, isDM, settings);
return text.length ? ( return text.length ? (
<> <>
@@ -59,14 +54,15 @@ export default function Card({
return ( return (
<ToolTip content={tooltip || getTooltip()}> <ToolTip content={tooltip || getTooltip()}>
<TiltCard <TiltCard
className={`h-[21vh] w-[15vh] relative perspective transition-transform duration-200 z-0 hover:z-10 hover:scale-150 ${dm ? 'cursor-pointer' : ''} `} className={`h-[21vh] w-[15vh] relative perspective transition-transform duration-200 z-0 hover:z-10 hover:scale-150 ${isDM ? 'cursor-pointer' : ''} `}
onClick={handleClick} cardIndex={cardIndex}
> >
<div <div
className={`absolute inset-0 transition-transform duration-500 transform-style-preserve-3d ${flipped ? 'rotate-y-180' : ''}`} 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"> <div className="absolute inset-0 group backface-hidden">
{dm && ( {isDM && (
<> <>
<img src={getURL(card, settings)} alt={aria} className="absolute rounded-lg" /> <img src={getURL(card, settings)} alt={aria} className="absolute rounded-lg" />
<img <img
@@ -79,12 +75,12 @@ export default function Card({
<img <img
src={getURL(cardBack as TarokkaGameCard, settings)} src={getURL(cardBack as TarokkaGameCard, settings)}
alt="Card Back" 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 <StackTheDeck
onRedraw={redrawAction} onRedraw={() => redraw(cardIndex)}
onSelect={() => selectAction()} onSelect={() => setSelectCardIndex(cardIndex)}
onHover={setTooltip} onHover={setTooltip}
/> />
)} )}

View File

@@ -1,41 +1,36 @@
'use client'; 'use client';
import { CircleX } from 'lucide-react'; import { CircleX } from 'lucide-react';
import { useAppContext } from '@/app/AppContext';
import TarokkaDeck from '@/lib/TarokkaDeck'; import TarokkaDeck from '@/lib/TarokkaDeck';
import getURL from '@/tools/getURL'; import getURL from '@/tools/getURL';
import { Deck, Settings, TarokkaGameCard } from '@/types'; import { Deck } from '@/types';
const tarokkaDeck = new TarokkaDeck(); const tarokkaDeck = new TarokkaDeck();
type CardSelectProps = { type CardSelectProps = {
closeAction: () => void;
selectAction: (cardID: string) => void;
hand: TarokkaGameCard[];
settings: Settings;
show: Deck | null;
className?: string; className?: string;
}; };
export default function CardSelect({ export default function CardSelect({ className = '' }: CardSelectProps) {
closeAction, const { gameData, select, selectCardIndex, setSelectCardIndex } = useAppContext();
selectAction, const { cards: hand, settings } = gameData;
hand,
settings,
show,
className = '',
}: CardSelectProps) {
const handIDs = hand.map(({ id }) => id); 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>) => { const handleClose = (event: React.MouseEvent<HTMLElement>) => {
if (event.target === event.currentTarget) { 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 ( return (
<div <div
@@ -44,7 +39,7 @@ export default function CardSelect({
> >
<button <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`} 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" /> <CircleX className="w-6 h-6" />
</button> </button>
@@ -58,7 +53,7 @@ export default function CardSelect({
<div <div
key={card.id} key={card.id}
className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10`} className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10`}
onClick={() => selectAction(card.id)} onClick={() => select(card.id)}
> >
<img <img
src={getURL(card, settings)} src={getURL(card, settings)}

View File

@@ -3,20 +3,18 @@
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { ScrollText } from 'lucide-react'; import { ScrollText } from 'lucide-react';
import { useAppContext } from '@/app/AppContext';
import CopyButton from '@/components/CopyButton'; import CopyButton from '@/components/CopyButton';
import Scrim from '@/components/Scrim'; import Scrim from '@/components/Scrim';
import getCardInfo from '@/tools/getCardInfo'; import getCardInfo from '@/tools/getCardInfo';
import { cardMap, layout } from '@/constants/tarokka'; 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 isDM = !!dmID;
const show = cards.every(({ flipped }) => flipped);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);

View File

@@ -4,12 +4,13 @@ import { useState } from 'react';
import { Settings as Gear } from 'lucide-react'; import { Settings as Gear } from 'lucide-react';
import { Cinzel_Decorative } from 'next/font/google'; import { Cinzel_Decorative } from 'next/font/google';
import { useAppContext } from '@/app/AppContext';
import BuyMeACoffee from '@/components/BuyMeACoffee'; import BuyMeACoffee from '@/components/BuyMeACoffee';
import CopyButton from '@/components/CopyButton'; import CopyButton from '@/components/CopyButton';
import GitHubButton from '@/components/GitHubButton'; import GitHubButton from '@/components/GitHubButton';
import Scrim from '@/components/Scrim'; import Scrim from '@/components/Scrim';
import Switch from '@/components/Switch'; import Switch from '@/components/Switch';
import { CardStyle, GameUpdate } from '@/types'; import { CardStyle } from '@/types';
const cinzel = Cinzel_Decorative({ const cinzel = Cinzel_Decorative({
variable: '--font-cinzel', variable: '--font-cinzel',
@@ -17,18 +18,17 @@ const cinzel = Cinzel_Decorative({
weight: '400', weight: '400',
}); });
type SettingsProps = {
gameData: GameUpdate;
changeAction: (updatedSettings: GameUpdate) => void;
};
const cardStyleOptions: CardStyle[] = ['standard', 'color', 'grayscale']; const cardStyleOptions: CardStyle[] = ['standard', 'color', 'grayscale'];
export default function Settings({ gameData, changeAction }: SettingsProps) { export default function Settings() {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const { gameData, handleSettings } = useAppContext();
const { dmID } = gameData;
const isDM = !!dmID;
const togglePermission = (key: string) => { const togglePermission = (key: string) => {
changeAction({ handleSettings({
...gameData, ...gameData,
settings: { settings: {
...gameData.settings, ...gameData.settings,
@@ -38,7 +38,7 @@ export default function Settings({ gameData, changeAction }: SettingsProps) {
}; };
const tuneRadio = (cardStyle: CardStyle) => { const tuneRadio = (cardStyle: CardStyle) => {
changeAction({ handleSettings({
...gameData, ...gameData,
settings: { settings: {
...gameData.settings, ...gameData.settings,
@@ -104,7 +104,7 @@ export default function Settings({ gameData, changeAction }: SettingsProps) {
</fieldset> </fieldset>
); );
return ( return isDM ? (
<div className={`fixed top-4 right-4 z-25 ${cinzel.className}`}> <div className={`fixed top-4 right-4 z-25 ${cinzel.className}`}>
<Scrim <Scrim
clickAction={() => setOpen((prev) => !prev)} clickAction={() => setOpen((prev) => !prev)}
@@ -129,5 +129,5 @@ export default function Settings({ gameData, changeAction }: SettingsProps) {
<Gear className="w-5 h-5" /> <Gear className="w-5 h-5" />
</button> </button>
</div> </div>
); ) : null;
} }

View 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}
/>
);
}

View 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>
);
}

View File

@@ -1,15 +1,48 @@
import { useRef } from 'react'; import { useEffect, useRef } from 'react';
import { useAppContext } from '@/app/AppContext';
import type { Tilt } from '@/types';
export default function TiltCard({ export default function TiltCard({
children, children,
cardIndex,
className = '', className = '',
onClick = () => {},
}: { }: {
children: React.ReactNode; children: React.ReactNode;
cardIndex: number;
className?: string; className?: string;
onClick: (event: React.MouseEvent) => void;
}) { }) {
const cardRef = useRef<HTMLDivElement>(null); const cardRef = useRef<HTMLDivElement>(null);
const { gameData, setTilt } = useAppContext();
useEffect(() => {
const card = cardRef.current;
if (!card) return;
const tilt = gameData.tilts[cardIndex];
if (!tilt) {
card.style.transform = `rotateX(0deg) rotateY(0deg)`;
return;
}
const tilted = tilt.filter(({ rotateX, rotateY }) => rotateX || rotateY);
const { totalX, totalY } = tilted.reduce(
({ totalX, totalY }, { rotateX, rotateY }) => ({
totalX: totalX + rotateX,
totalY: totalY + rotateY,
}),
{ totalX: 0, totalY: 0 },
);
const rotateX = totalX / tilted.length;
const rotateY = totalY / tilted.length;
if (rotateX || rotateY) {
card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
} else {
card.style.transform = `rotateX(0deg) rotateY(0deg)`;
}
}, [gameData]);
const handleMouseMove = (e: React.MouseEvent) => { const handleMouseMove = (e: React.MouseEvent) => {
const card = cardRef.current; const card = cardRef.current;
@@ -24,22 +57,18 @@ export default function TiltCard({
const rotateX = ((y - centerY) / centerY) * -20; const rotateX = ((y - centerY) / centerY) * -20;
const rotateY = ((x - centerX) / centerX) * 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);
}; };
const handleMouseLeave = () => { const handleMouseLeave = () => {
const card = cardRef.current; setTilt([]);
if (!card) return;
card.style.transform = `rotateX(0deg) rotateY(0deg)`;
}; };
return ( return (
<div <div className={`${className}`} onMouseMove={handleMouseMove} onMouseLeave={handleMouseLeave}>
className={`${className}`}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={onClick}
>
<div ref={cardRef} className={`h-full w-full transition-transform duration-0`}> <div ref={cardRef} className={`h-full w-full transition-transform duration-0`}>
{children} {children}
</div> </div>

View File

@@ -1,7 +1,8 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { socket } from '@/socket'; import { socket } from '@/socket';
import throttle from '@/tools/throttle';
import type { GameUpdate } from '@/types'; import type { GameUpdate, Tilt } from '@/types';
interface UseSocketProps { interface UseSocketProps {
gameID: string; gameID: string;
@@ -44,6 +45,13 @@ export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketP
}); });
}; };
const handleSettings = (gameData: GameUpdate) => {
socket.emit('settings', {
gameID,
gameData,
});
};
const redraw = (cardIndex: number) => { const redraw = (cardIndex: number) => {
socket.emit('redraw', { socket.emit('redraw', {
gameID, gameID,
@@ -59,17 +67,18 @@ export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketP
}); });
}; };
const handleSettings = (gameData: GameUpdate) => { const emitTilt = throttle((cardIndex: number, tilt: Tilt) => {
socket.emit('settings', { socket.emit('tilt', {
gameID, cardIndex,
gameData, tilt,
}); });
}; }, 33.3);
return { return {
flipCard, flipCard,
handleSettings,
redraw, redraw,
select, select,
handleSettings, emitTilt,
}; };
} }

View File

@@ -2,7 +2,7 @@ import Deck from '@/lib/TarokkaDeck';
import generateID from '@/tools/simpleID'; import generateID from '@/tools/simpleID';
import parseMilliseconds from '@/tools/parseMilliseconds'; import parseMilliseconds from '@/tools/parseMilliseconds';
import { HOUR, DAY } from '@/constants/time'; import { HOUR, DAY } from '@/constants/time';
import { GameState, GameUpdate, Settings } from '@/types'; import { GameState, GameUpdate, Settings, Tilt } from '@/types';
const deck = new Deck(); const deck = new Deck();
@@ -91,6 +91,7 @@ export default class GameStore {
notes: true, notes: true,
cardStyle: 'color', cardStyle: 'color',
}, },
tilts: Array.from({ length: 5 }, () => []),
}; };
this.totalCreated++; this.totalCreated++;
@@ -157,6 +158,21 @@ export default class GameStore {
return this.gameUpdate(game); 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`);
game.tilts[cardIndex] = [
...cardTilts.filter((tilt) => tilt.playerID !== playerID),
{ playerID, rotateX, rotateY },
];
game.lastUpdated = Date.now();
return this.gameUpdate(game);
}
updateSettings(gameID: string, settings: Settings) { updateSettings(gameID: string, settings: Settings) {
const game = this.getGame(gameID); const game = this.getGame(gameID);
@@ -173,10 +189,18 @@ export default class GameStore {
return game; return game;
} }
gameUpdate(game: GameState): GameUpdate { getGameByPlayerID(playerID: string): GameState {
const { dmID, spectatorID, cards, settings } = game; const game = this.players.get(playerID);
return { dmID, spectatorID, cards, settings }; if (!game) throw new Error(`Player ${playerID} not found`);
return game;
}
gameUpdate(game: GameState): GameUpdate {
const { dmID, spectatorID, cards, settings, tilts } = game;
return { dmID, spectatorID, cards, settings, tilts };
} }
playerExit(playerID: string): GameState | null { playerExit(playerID: string): GameState | null {
@@ -185,9 +209,7 @@ export default class GameStore {
return null; return null;
} else { } else {
const game = this.players.get(playerID); const game = this.getGameByPlayerID(playerID);
if (!game) throw new Error(`Player ${playerID} not found`);
this.players.delete(playerID); this.players.delete(playerID);
return this.leaveGame(game, playerID); return this.leaveGame(game, playerID);

View File

@@ -4,7 +4,7 @@ import { Server as SocketIOServer, type Socket } from 'socket.io';
import GameStore from '@/lib/GameStore'; import GameStore from '@/lib/GameStore';
import omit from '@/tools/omit'; import omit from '@/tools/omit';
import type { ClientUpdate, GameUpdate } from '@/types'; import type { ClientUpdate, GameUpdate, Tilt } from '@/types';
const dev = process.env.NODE_ENV !== 'production'; const dev = process.env.NODE_ENV !== 'production';
const hostname = '0.0.0.0'; const hostname = '0.0.0.0';
@@ -119,6 +119,16 @@ app.prepare().then(() => {
} }
}); });
socket.on('tilt', ({ cardIndex, tilt }: { cardIndex: number; tilt: Tilt }) => {
try {
const gameState = gameStore.tilt(socket.id, cardIndex, tilt);
broadcast('game-update', gameState);
} catch (e) {
const error = e instanceof Error ? e.message : e;
console.error(Date.now(), 'Error[tilt]', error);
}
});
socket.on('disconnect', () => { socket.on('disconnect', () => {
try { try {
const game = gameStore.playerExit(socket.id); const game = gameStore.playerExit(socket.id);

View File

@@ -82,6 +82,7 @@ export interface GameState {
cards: TarokkaGameCard[]; cards: TarokkaGameCard[];
lastUpdated: number; lastUpdated: number;
settings: Settings; settings: Settings;
tilts: Tilt[][];
} }
export interface GameUpdate { export interface GameUpdate {
@@ -89,6 +90,7 @@ export interface GameUpdate {
spectatorID: string; spectatorID: string;
cards: TarokkaGameCard[]; cards: TarokkaGameCard[];
settings: Settings; settings: Settings;
tilts: Tilt[][];
} }
export interface ClientUpdate { export interface ClientUpdate {
@@ -103,3 +105,9 @@ export interface Layout {
name: string; name: string;
text: string; text: string;
} }
export interface Tilt {
playerID?: string;
rotateX: number;
rotateY: number;
}