reconexion establecida

This commit is contained in:
2025-08-11 18:36:24 -06:00
parent e5e5ad452a
commit 9a44afc81a
6 changed files with 100 additions and 79 deletions

View File

@@ -25,11 +25,7 @@ class ColyseusService {
private client: Client; private client: Client;
private currentRoom: Room | null = null; private currentRoom: Room | null = null;
private apiBase: string; private apiBase: string;
private desiredName: string | null = null; private readonly LS_KEY_RECONNECT = "snatch.game.rtoken";
private nameRetryCount: number = 0;
private nameRetryTimer: any = null;
private readonly LS_KEY_NAME = "snatch.player.name";
private readonly LS_KEY_COLOR = "snatch.player.color";
public lobbyRoom: Ref<Room | null> = ref(null); public lobbyRoom: Ref<Room | null> = ref(null);
public gameRoom: Ref<Room | null> = ref(null); public gameRoom: Ref<Room | null> = ref(null);
@@ -49,13 +45,6 @@ class ColyseusService {
const httpProtocol = typeof window !== "undefined" && window.location.protocol === "https:" ? "https" : "http"; const httpProtocol = typeof window !== "undefined" && window.location.protocol === "https:" ? "https" : "http";
const apiFallback = `${httpProtocol}://${defaultHost}:${defaultPort}/api`; const apiFallback = `${httpProtocol}://${defaultHost}:${defaultPort}/api`;
this.apiBase = (import.meta.env as any).VITE_API_URL || apiFallback; this.apiBase = (import.meta.env as any).VITE_API_URL || apiFallback;
// Hydrate from localStorage for immediate UI
try {
const savedName = typeof window !== 'undefined' ? (window.localStorage.getItem(this.LS_KEY_NAME) || "") : "";
const savedColor = typeof window !== 'undefined' ? (window.localStorage.getItem(this.LS_KEY_COLOR) || "") : "";
if (savedName) this.playerName.value = savedName;
if (savedColor) this.playerColor.value = savedColor;
} catch {}
} }
async joinLobby(): Promise<Room> { async joinLobby(): Promise<Room> {
@@ -63,12 +52,8 @@ class ColyseusService {
const room = await this.client.joinOrCreate("lobby"); const room = await this.client.joinOrCreate("lobby");
this.lobbyRoom.value = room; this.lobbyRoom.value = room;
this.currentRoom = room; this.currentRoom = room;
// Require explicit confirmation each time we join the lobby // Require explicit confirmation each time we join the lobby (auto-confirm if saved name exists)
this.nameConfirmed.value = false; this.nameConfirmed.value = false;
// Clear any pending name retry from previous sessions
this.desiredName = null;
this.nameRetryCount = 0;
if (this.nameRetryTimer) { clearTimeout(this.nameRetryTimer); this.nameRetryTimer = null; }
room.onMessage("welcome", async (data) => { room.onMessage("welcome", async (data) => {
this.sessionId.value = data.sessionId; this.sessionId.value = data.sessionId;
@@ -81,52 +66,21 @@ class ColyseusService {
if (profile?.color && profile.color !== this.playerColor.value) { if (profile?.color && profile.color !== this.playerColor.value) {
this.setPlayerColor(profile.color); this.setPlayerColor(profile.color);
} }
let candidateName = profile?.name || ""; if (profile?.name) {
if (!candidateName) { this.playerName.value = profile.name;
try { candidateName = typeof window !== 'undefined' ? (window.localStorage.getItem(this.LS_KEY_NAME) || "") : ""; } catch {} try { localDB.setName(profile.name); } catch {}
} this.setPlayerName(profile.name);
if (candidateName) { this.nameConfirmed.value = true;
this.playerName.value = candidateName;
try { localDB.setName(candidateName); } catch {}
this.claimSavedName(candidateName);
} }
} catch (e) { } catch (e) {
console.warn("Local DB init failed", e); console.warn("Local DB init failed", e);
// Fallback purely to localStorage
try {
const candidateName = typeof window !== 'undefined' ? (window.localStorage.getItem(this.LS_KEY_NAME) || "") : "";
if (candidateName) {
this.playerName.value = candidateName;
this.claimSavedName(candidateName);
}
} catch {}
} }
}); });
room.onMessage("nameUpdated", (data) => { room.onMessage("nameUpdated", (data) => {
this.playerName.value = data.name; this.playerName.value = data.name;
try { localDB.setName(data.name); } catch {} try { localDB.setName(data.name); } catch {}
try { if (typeof window !== 'undefined') window.localStorage.setItem(this.LS_KEY_NAME, data.name || ""); } catch {}
this.nameConfirmed.value = true; this.nameConfirmed.value = true;
// If we are trying to reclaim a saved name and got a suffixed one, retry briefly.
if (this.desiredName) {
const desired = (this.desiredName || "").trim().toLowerCase();
const got = (data.name || "").trim().toLowerCase();
if (desired && desired !== got && this.nameRetryCount < 2) {
const attempt = ++this.nameRetryCount;
if (this.nameRetryTimer) clearTimeout(this.nameRetryTimer);
this.nameRetryTimer = setTimeout(() => {
// Attempt again; if the previous session has now left, exact name may be free
this.setPlayerName(this.desiredName || "");
}, attempt * 400);
return;
}
// Either matched desired or exceeded retries; stop retrying
this.desiredName = null;
this.nameRetryCount = 0;
if (this.nameRetryTimer) { clearTimeout(this.nameRetryTimer); this.nameRetryTimer = null; }
}
}); });
room.onMessage("colorUpdated", (data) => { room.onMessage("colorUpdated", (data) => {
@@ -143,29 +97,35 @@ class ColyseusService {
} }
} }
async setPlayerName(name: string): Promise<void> { async tryReconnectToOngoingGame(): Promise<Room | null> {
if (this.lobbyRoom.value) { try {
this.lobbyRoom.value.send("setName", name); const token = typeof window !== 'undefined' ? (window.localStorage.getItem(this.LS_KEY_RECONNECT) || "") : "";
try { if (typeof window !== 'undefined') window.localStorage.setItem(this.LS_KEY_NAME, name || ""); } catch {} if (!token) return null;
const room = await this.client.reconnect(token);
this.gameRoom.value = room;
this.currentRoom = room;
// Ensure local session id reflects the active room session
try { this.sessionId.value = (room as any).sessionId || this.sessionId.value; } catch {}
try { if (typeof window !== 'undefined') window.localStorage.setItem(this.LS_KEY_RECONNECT, (room as any).reconnectionToken || token); } catch {}
return room;
} catch (e) {
console.warn('Reconnection failed, clearing tokens');
try {
if (typeof window !== 'undefined') { window.localStorage.removeItem(this.LS_KEY_RECONNECT); }
} catch {}
return null;
} }
} }
// Attempt to reclaim the saved name with a short retry window to avoid race async setPlayerName(name: string): Promise<void> {
private claimSavedName(name: string): void { if (this.lobbyRoom.value) {
this.desiredName = name; this.lobbyRoom.value.send("setName", name);
this.nameRetryCount = 0; }
if (this.nameRetryTimer) { clearTimeout(this.nameRetryTimer); this.nameRetryTimer = null; }
// Small delay to let any previous session fully leave the lobby
this.nameRetryTimer = setTimeout(() => {
this.setPlayerName(name);
this.nameConfirmed.value = true;
}, 150);
} }
async setPlayerColor(color: string): Promise<void> { async setPlayerColor(color: string): Promise<void> {
if (this.lobbyRoom.value) { if (this.lobbyRoom.value) {
this.lobbyRoom.value.send("setColor", color); this.lobbyRoom.value.send("setColor", color);
try { if (typeof window !== 'undefined') window.localStorage.setItem(this.LS_KEY_COLOR, color || ""); } catch {}
} }
} }
@@ -197,6 +157,9 @@ class ColyseusService {
console.log('Setting gameRoom.value...'); console.log('Setting gameRoom.value...');
this.gameRoom.value = gameRoom; this.gameRoom.value = gameRoom;
this.currentRoom = gameRoom; this.currentRoom = gameRoom;
// Update current session id for correct role mapping
try { this.sessionId.value = (gameRoom as any).sessionId || this.sessionId.value; } catch {}
try { if (typeof window !== 'undefined') window.localStorage.setItem(this.LS_KEY_RECONNECT, (gameRoom as any).reconnectionToken || ""); } catch {}
console.log('gameRoom.value is now:', this.gameRoom.value); console.log('gameRoom.value is now:', this.gameRoom.value);
// Don't register message handlers here - let the Game component handle them // Don't register message handlers here - let the Game component handle them
@@ -226,7 +189,8 @@ class ColyseusService {
playerName: this.playerName.value, playerName: this.playerName.value,
playerColor: this.playerColor.value playerColor: this.playerColor.value
}); });
try { this.sessionId.value = (gameRoom as any).sessionId || this.sessionId.value; } catch {}
try { if (typeof window !== 'undefined') window.localStorage.setItem(this.LS_KEY_RECONNECT, (gameRoom as any).reconnectionToken || ""); } catch {}
this.gameRoom.value = gameRoom; this.gameRoom.value = gameRoom;
this.currentRoom = gameRoom; this.currentRoom = gameRoom;
@@ -314,6 +278,7 @@ class ColyseusService {
this.currentRoom = null; this.currentRoom = null;
} }
} }
try { if (typeof window !== 'undefined') { window.localStorage.removeItem(this.LS_KEY_RECONNECT); } } catch {}
} }
leaveCurrentRoom(): void { leaveCurrentRoom(): void {

View File

@@ -115,12 +115,22 @@ const componentMap: Record<string, any> = { G1, G2, G3, G4, G5 };
const currentComponent = computed(() => componentMap[currentVariant.value]); const currentComponent = computed(() => componentMap[currentVariant.value]);
onMounted(() => { onMounted(() => {
const room = colyseusService.gameRoom.value; let room = colyseusService.gameRoom.value;
if (!room) { if (!room) {
// Try reconnection first
colyseusService.tryReconnectToOngoingGame().then(r => {
if (!r) {
router.push('/'); router.push('/');
return; return;
} }
setupRoom(r);
});
return;
}
setupRoom(room);
function setupRoom(room: any) {
const $ = getStateCallbacks(room); const $ = getStateCallbacks(room);
room.onStateChange.once((state: any) => { room.onStateChange.once((state: any) => {
@@ -171,6 +181,11 @@ onMounted(() => {
colyseusService.sessionId.value = info.sessionId; colyseusService.sessionId.value = info.sessionId;
colyseusService.playerName.value = info.name; colyseusService.playerName.value = info.name;
}); });
room.onMessage("gameEnd", () => {
try { if (typeof window !== 'undefined') { window.localStorage.removeItem('snatch.game.rtoken'); } } catch {}
});
}
}); });
function roomOffer<K extends string>(key: K): any { function roomOffer<K extends string>(key: K): any {
@@ -189,8 +204,11 @@ function onP2Action(action: 'accept'|'reject'|'snatch') { colyseusService.p2Acti
function onReport(val: boolean) { colyseusService.report(val); } function onReport(val: boolean) { colyseusService.report(val); }
function onAssignShame(val: boolean) { colyseusService.assignShame(val); } function onAssignShame(val: boolean) { colyseusService.assignShame(val); }
function leaveGame() { colyseusService.leaveGame(); function leaveGame() {
router.push('/'); } colyseusService.leaveGame();
try { if (typeof window !== 'undefined') { window.localStorage.removeItem('snatch.game.roomId'); window.localStorage.removeItem('snatch.game.sessionId'); } } catch {}
router.push('/');
}
</script> </script>
<style scoped> <style scoped>

View File

@@ -95,17 +95,28 @@ onMounted(() => {
console.log('Game component mounted'); console.log('Game component mounted');
console.log('colyseusService.gameRoom:', colyseusService.gameRoom); console.log('colyseusService.gameRoom:', colyseusService.gameRoom);
console.log('colyseusService.gameRoom.value:', colyseusService.gameRoom.value); console.log('colyseusService.gameRoom.value:', colyseusService.gameRoom.value);
const room = colyseusService.gameRoom.value; let room = colyseusService.gameRoom.value;
console.log('Current game room:', room); console.log('Current game room:', room);
if (!room) { if (!room) {
console.error('No game room found, redirecting to lobby...'); console.warn('No game room found, trying reconnection...');
// Attempt reconnection if tokens are available
colyseusService.tryReconnectToOngoingGame().then((r) => {
if (!r) {
console.error('Reconnection failed, redirecting to lobby...');
router.push('/'); router.push('/');
return; return;
} }
setupRoom(r);
});
return;
}
setupRoom(room);
console.log('Setting up game room listeners...'); console.log('Setting up game room listeners...');
function setupRoom(room: any) {
const $ = getStateCallbacks(room); const $ = getStateCallbacks(room);
// Wait for the initial state sync (do not manually push players here to avoid duplicates) // Wait for the initial state sync (do not manually push players here to avoid duplicates)
@@ -174,6 +185,7 @@ onMounted(() => {
room.onMessage("gameEnd", (data) => { room.onMessage("gameEnd", (data) => {
console.log("Game ended!", data); console.log("Game ended!", data);
gameStatus.value = 'finished'; gameStatus.value = 'finished';
try { if (typeof window !== 'undefined') { window.localStorage.removeItem('snatch.game.rtoken'); } } catch {}
}); });
room.onMessage("gamePaused", () => { room.onMessage("gamePaused", () => {
@@ -186,6 +198,7 @@ onMounted(() => {
players.value.forEach(p => p.clicks = 0); players.value.forEach(p => p.clicks = 0);
gameStatus.value = 'waiting'; gameStatus.value = 'waiting';
}); });
}
}); });
onUnmounted(() => { onUnmounted(() => {

View File

@@ -111,6 +111,12 @@ const previewPlayer = computed(() => ({
onMounted(async () => { onMounted(async () => {
try { try {
// Try reconnect to an ongoing game first
const reconnected = await colyseusService.tryReconnectToOngoingGame();
if (reconnected) {
router.push('/demo');
return;
}
const room = await colyseusService.joinLobby(); const room = await colyseusService.joinLobby();
colorInput.value = colyseusService.playerColor.value || '#667eea'; colorInput.value = colyseusService.playerColor.value || '#667eea';
@@ -228,7 +234,7 @@ async function joinRoom(roomId: string) {
colyseusService.lobbyRoom.value.leave(); colyseusService.lobbyRoom.value.leave();
colyseusService.lobbyRoom.value = null; colyseusService.lobbyRoom.value = null;
} }
router.push('/game'); router.push('/demo');
} catch (error) { } catch (error) {
console.error('Failed to join room:', error); console.error('Failed to join room:', error);
isJoining.value = false; isJoining.value = false;

View File

@@ -21,6 +21,8 @@ export class GameRoom extends Room<GameState> {
onCreate(options: any) { onCreate(options: any) {
this.setState(new GameState()); this.setState(new GameState());
this.state.roomId = this.roomId; this.state.roomId = this.roomId;
// Expose status via metadata for lobby listing
this.setMetadata({ gameStatus: 'waiting' });
// Variant selection (both players can change) // Variant selection (both players can change)
this.onMessage("setVariant", (client, variant: string) => { this.onMessage("setVariant", (client, variant: string) => {
@@ -207,6 +209,11 @@ export class GameRoom extends Room<GameState> {
onJoin(client: Client, options: any) { onJoin(client: Client, options: any) {
console.log(`[GameRoom] ${client.sessionId} joined room ${this.roomId} with name: ${options.playerName}`); console.log(`[GameRoom] ${client.sessionId} joined room ${this.roomId} with name: ${options.playerName}`);
// Prevent new joins if game already started or two players are registered
if (this.state.gameStatus !== GameStatus.WAITING || this.state.players.size >= 2) {
try { client.leave(1000); } catch {}
return;
}
// Use the playerName passed from the lobby - don't generate a new one! // Use the playerName passed from the lobby - don't generate a new one!
const playerName = options.playerName || "player"; const playerName = options.playerName || "player";
@@ -256,6 +263,13 @@ export class GameRoom extends Room<GameState> {
player.connected = true; player.connected = true;
} }
// Send player info so client can rehydrate local session state
client.send("playerInfo", {
sessionId: client.sessionId,
name: player?.name || "player",
roomId: this.roomId
});
if (this.state.gameStatus === GameStatus.PAUSED && this.getConnectedPlayersCount() === 2) { if (this.state.gameStatus === GameStatus.PAUSED && this.getConnectedPlayersCount() === 2) {
this.state.resumeGame(); this.state.resumeGame();
} }
@@ -274,6 +288,7 @@ export class GameRoom extends Room<GameState> {
private startGame() { private startGame() {
console.log(`[GameRoom] Starting demo game in room ${this.roomId}`); console.log(`[GameRoom] Starting demo game in room ${this.roomId}`);
this.state.startGame(); this.state.startGame();
this.setMetadata({ gameStatus: 'playing' });
// G2: Force offer by default when starting game // G2: Force offer by default when starting game
if (this.state.currentVariant === 'G2') { if (this.state.currentVariant === 'G2') {
this.state.forcedByP2 = true; this.state.forcedByP2 = true;
@@ -287,11 +302,13 @@ export class GameRoom extends Room<GameState> {
console.log(`[GameRoom] Pausing game in room ${this.roomId}`); console.log(`[GameRoom] Pausing game in room ${this.roomId}`);
this.state.pauseGame(); this.state.pauseGame();
this.broadcast("gamePaused"); this.broadcast("gamePaused");
this.setMetadata({ gameStatus: 'paused' });
} }
private endGame() { private endGame() {
console.log(`[GameRoom] Demo game ended in room ${this.roomId}`); console.log(`[GameRoom] Demo game ended in room ${this.roomId}`);
this.broadcast("gameEnd", {}); this.broadcast("gameEnd", {});
this.setMetadata({ gameStatus: 'finished' });
} }
private resolveP2Action() { private resolveP2Action() {
@@ -352,6 +369,7 @@ export class GameRoom extends Room<GameState> {
this.state.restartGame(); this.state.restartGame();
this.broadcast("gameRestart"); this.broadcast("gameRestart");
this.setMetadata({ gameStatus: 'waiting' });
if (this.state.players.size === 2) { if (this.state.players.size === 2) {
setTimeout(() => this.startGame(), 500); setTimeout(() => this.startGame(), 500);

View File

@@ -148,7 +148,8 @@ export class LobbyRoom extends Room<LobbyState> {
// Verify the room exists and is available // Verify the room exists and is available
const rooms = await matchMaker.query({ roomId }); const rooms = await matchMaker.query({ roomId });
if (rooms.length === 0 || rooms[0].clients >= 2) { const status = rooms[0]?.metadata?.gameStatus || "waiting";
if (rooms.length === 0 || rooms[0].clients >= 2 || status !== "waiting") {
throw new Error("Room not available"); throw new Error("Room not available");
} }
@@ -175,7 +176,7 @@ export class LobbyRoom extends Room<LobbyState> {
const rooms = await matchMaker.query({ name: "game" }); const rooms = await matchMaker.query({ name: "game" });
const availableRooms = rooms const availableRooms = rooms
.filter(room => !room.locked && room.clients < 2) .filter(room => (room.metadata?.gameStatus || "waiting") === "waiting" && room.clients < 2)
.map(room => new AvailableRoom( .map(room => new AvailableRoom(
room.roomId, room.roomId,
room.clients, room.clients,