Start repository
This commit is contained in:
68
src/hooks/usePartyKit.ts
Normal file
68
src/hooks/usePartyKit.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import PartySocket from 'partysocket';
|
||||
import { GameState } from '../types';
|
||||
|
||||
const PARTY_HOST = import.meta.env.DEV ? 'localhost:1998' : 'bozo-clicker.your-username.partykit.dev';
|
||||
|
||||
export function usePartyKit() {
|
||||
const [gameState, setGameState] = useState<GameState | null>(null);
|
||||
const [socket, setSocket] = useState<PartySocket | null>(null);
|
||||
const [userId] = useState(() => Math.random().toString(36).substring(7));
|
||||
const [userName] = useState(() => `Bozo${Math.floor(Math.random() * 1000)}`);
|
||||
|
||||
useEffect(() => {
|
||||
const ws = new PartySocket({
|
||||
host: PARTY_HOST,
|
||||
room: 'bozo-clicker'
|
||||
});
|
||||
|
||||
ws.onopen = () => {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'user-join',
|
||||
userId,
|
||||
userName
|
||||
}));
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'game-state') {
|
||||
setGameState(data.state);
|
||||
}
|
||||
};
|
||||
|
||||
setSocket(ws);
|
||||
|
||||
return () => {
|
||||
ws.close();
|
||||
};
|
||||
}, [userId, userName]);
|
||||
|
||||
const sendClick = useCallback(() => {
|
||||
if (socket) {
|
||||
socket.send(JSON.stringify({
|
||||
type: 'click',
|
||||
userId,
|
||||
userName
|
||||
}));
|
||||
}
|
||||
}, [socket, userId, userName]);
|
||||
|
||||
const purchaseUpgrade = useCallback((upgradeId: string) => {
|
||||
if (socket) {
|
||||
socket.send(JSON.stringify({
|
||||
type: 'purchase-upgrade',
|
||||
userId,
|
||||
upgradeId
|
||||
}));
|
||||
}
|
||||
}, [socket, userId]);
|
||||
|
||||
return {
|
||||
gameState,
|
||||
sendClick,
|
||||
purchaseUpgrade,
|
||||
userId,
|
||||
userName
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user