diff --git a/SerpentRace_Frontend/src/pages/Game/Lobby.jsx b/SerpentRace_Frontend/src/pages/Game/Lobby.jsx index bfee0932..68f94c39 100644 --- a/SerpentRace_Frontend/src/pages/Game/Lobby.jsx +++ b/SerpentRace_Frontend/src/pages/Game/Lobby.jsx @@ -1,5 +1,7 @@ import React, { useEffect, useRef, useState } from "react" import { useLocation } from "react-router-dom" +import { useNavigate } from "react-router-dom" +import { notifyError, notifyWarning, notifySuccess } from "../../components/Toastify/toastifyServices" import HandleNavigate from "../../utils/HandleNavigate/HandleNavigate" import Navbar from "../../components/Navbar/Navbar.jsx" import Background from "../../assets/backgrounds/Background.jsx" @@ -12,10 +14,11 @@ const Lobby = () => { const [isStarting, setIsStarting] = useState(false) const sectionRef = useRef(null) const { goHome, goGame } = HandleNavigate() + const navigate = useNavigate() const location = useLocation() const [user, setUser] = useRequireAuth() - + // Get game code from location state or WebSocket const gameCodeFromState = location.state?.gameCode const gameToken = localStorage.getItem('gameToken') @@ -41,8 +44,8 @@ const Lobby = () => { } }, [gameToken, connect]) - const gameCode = gameCodeFromState || gameState?.gameCode || 'Loading...' - + const gameCode = gameCodeFromState || gameState?.gameCode || "Loading..." + // Players list - gamemaster is separate, don't filter // Backend should handle this correctly const currentPlayers = players || [] @@ -50,12 +53,12 @@ const Lobby = () => { // Debug logging useEffect(() => { if (import.meta.env.DEV) { - console.log('🎮 Lobby state update:') - console.log(' - isGamemaster:', isGamemaster) - console.log(' - gameState:', gameState) - console.log(' - players:', players) - console.log(' - currentPlayers:', currentPlayers) - console.log(' - pendingPlayers:', pendingPlayers) + console.log("🎮 Lobby state update:") + console.log(" - isGamemaster:", isGamemaster) + console.log(" - gameState:", gameState) + console.log(" - players:", players) + console.log(" - currentPlayers:", currentPlayers) + console.log(" - pendingPlayers:", pendingPlayers) } }, [isGamemaster, gameState, players, currentPlayers, pendingPlayers]) @@ -73,7 +76,7 @@ const Lobby = () => { // Auto-navigate when game starts useEffect(() => { if (gameStarted) { - console.log('🎮 Game started, navigating to /game') + console.log("🎮 Game started, navigating to /game") goGame() } }, [gameStarted, goGame]) @@ -83,7 +86,7 @@ const Lobby = () => { if (approvalStatus === 'denied') { alert('A gamemaster elutasította a csatlakozási kérelmedet.') localStorage.removeItem('gameToken') - goHome() + navigate("/home") } else if (approvalStatus === 'approved') { console.log('✅ Join approved, you can now see the lobby') } @@ -91,7 +94,8 @@ const Lobby = () => { const handleExit = () => { if (window.confirm("Biztosan ki szeretnél lépni a lobbyból?")) { - localStorage.removeItem('gameToken') + localStorage.removeItem("gameToken") + notifyWarning("Kiléptél a lobbyból.") goHome() } } @@ -99,44 +103,44 @@ const Lobby = () => { const handleStartGame = async () => { // Prevent double-click if (isStarting) { - console.log('⚠️ Game start already in progress, ignoring duplicate request') + console.log("⚠️ Game start already in progress, ignoring duplicate request") return } - + try { setIsStarting(true) - + // Get gameId from gameState const gameId = gameState?.gameId if (!gameId) { - alert('Hiba: Játék azonosító nem található') + notifyError("Hiba: Játék azonosító nem található") return } - console.log('Starting game with ID:', gameId) + console.log("Starting game with ID:", gameId) const response = await startGame(gameId) - console.log('Game start response:', response) - + console.log("Game start response:", response) + // Store boardData and updated game state for GameScreen if (response.boardData) { - localStorage.setItem('boardData', JSON.stringify(response.boardData)) - console.log('✅ boardData stored in localStorage') + localStorage.setItem("boardData", JSON.stringify(response.boardData)) + console.log("✅ boardData stored in localStorage") } - + // Navigate immediately after successful start (don't wait for WebSocket) console.log('🎮 Navigating to /game...') - goGame() + navigate('/game') } catch (error) { - console.error('Failed to start game:', error) - + console.error("Failed to start game:", error) + // Check if game already started if (error.response?.status === 409) { - console.log('Game already started, navigating to /game...') + console.log("Game already started, navigating to /game...") // Navigate anyway - game is already running - goGame() + navigate('/game') } else { - alert(`Nem sikerült elindítani a játékot: ${error.response?.data?.error || error.message}`) + notifyError(`Nem sikerült elindítani a játékot: ${error.response?.data?.error || error.message}`) } } finally { setIsStarting(false) @@ -145,7 +149,7 @@ const Lobby = () => { const copyGameCode = () => { navigator.clipboard.writeText(gameCode) - alert('Játék kód vágólapra másolva: ' + gameCode) + notifySuccess("Játék kód vágólapra másolva: " + gameCode) } const handleApprovePlayer = (playerName) => { @@ -155,8 +159,9 @@ const Lobby = () => { } const handleRejectPlayer = (playerName) => { - const reason = prompt(`Miért utasítod el ${playerName}-t?`, 'Nincs hely a játékban') - if (reason !== null) { // User didn't cancel + const reason = prompt(`Miért utasítod el ${playerName}-t?`, "Nincs hely a játékban") + if (reason !== null) { + // User didn't cancel if (rejectPlayer(playerName, reason)) { console.log(`❌ Player ${playerName} rejected`) } @@ -183,7 +188,7 @@ const Lobby = () => { {/* Waiting for Approval Screen (Non-gamemaster, PRIVATE games) */} - {!isGamemaster && approvalStatus === 'pending' && ( + {!isGamemaster && approvalStatus === "pending" && (
@@ -192,9 +197,7 @@ const Lobby = () => {
-

- Várakozás jóváhagyásra -

+

Várakozás jóváhagyásra

A gamemaster még nem hagyta jóvá a csatlakozásodat.

@@ -204,9 +207,7 @@ const Lobby = () => {

Játék kód:

-

- {gameCode} -

+

{gameCode}

+
+

+ Oszd meg ezt a kódot másokkal, hogy csatlakozhassanak a játékhoz!

-
-

- Oszd meg ezt a kódot másokkal, hogy csatlakozhassanak a játékhoz! -

- - {/* Connection Status */} -
- - {isConnected ? '🟢 Kapcsolódva' : '🔴 Kapcsolat megszakadt'} - -
+ {/* Connection Status */} +
+ + {isConnected ? "🟢 Kapcsolódva" : "🔴 Kapcsolat megszakadt"} + +
-

- Játékosok ({currentPlayers.length}): -

+

Játékosok ({currentPlayers.length}):

- {/* Pending Players Section (Gamemaster only, PRIVATE games) */} - {isGamemaster && pendingPlayers && pendingPlayers.length > 0 && ( -
-

- - Jóváhagyásra váró játékosok ({pendingPlayers.length}) -

-
- )} -
- -
+ - {/* Role indicator */} -
- {isGamemaster ? ( -
-

👑 Te vagy a Gamemaster!

-

Te nem játszol, csak indítod és moderálod a játékot.

-
- ) : ( -
-

🎮 Te vagy egy Játékos!

-

Várj, amíg a gamemaster elindítja a játékot.

-
- )} -
- -
- {isGamemaster ? ( - /* Gamemaster view - can start game */ +
+ {isGamemaster ? ( + /* Gamemaster view - can start game */ + + ) : ( + /* Player view - cannot start game, just wait */ +
+

Várakozás a gamemaster-re...

+

Csak a gamemaster indíthatja el a játékot

+
+ )} - ) : ( - /* Player view - cannot start game, just wait */ -
-

Várakozás a gamemaster-re...

-

Csak a gamemaster indíthatja el a játékot

-
- )} - -
- +
+ )} diff --git a/SerpentRace_Frontend/src/pages/Game/PlayerSetup.jsx b/SerpentRace_Frontend/src/pages/Game/PlayerSetup.jsx index 7702b0a6..f21d3885 100644 --- a/SerpentRace_Frontend/src/pages/Game/PlayerSetup.jsx +++ b/SerpentRace_Frontend/src/pages/Game/PlayerSetup.jsx @@ -20,20 +20,20 @@ const GameLobbySetup = () => { const [isPublic, setIsPublic] = useState(true) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) - const [createdGameCode, setCreatedGameCode] = useState('') + const [createdGameCode, setCreatedGameCode] = useState("") const [showSuccess, setShowSuccess] = useState(false) const handleCreateLobby = async () => { setLoading(true) setError(null) - + try { - const username = localStorage.getItem('username') - - console.log('Creating game - username:', username) - + const username = localStorage.getItem("username") + + console.log("Creating game - username:", username) + if (!username) { - setError('Kérlek jelentkezz be először!') + setError("Kérlek jelentkezz be először!") setLoading(false) return } @@ -45,48 +45,48 @@ const GameLobbySetup = () => { logintype: isPublic ? 0 : 1, // 0=PUBLIC, 1=PRIVATE, 2=ORGANIZATION } - console.log('Creating game with data:', gameData) + console.log("Creating game with data:", gameData) const response = await createGame(gameData) - console.log('Game created:', response) - + console.log("Game created:", response) + // Verify localStorage still has username - console.log('After create - username:', localStorage.getItem('username')) - + console.log("After create - username:", localStorage.getItem("username")) + // Backend returns game object directly const code = response.gamecode || response.gameCode if (code) { setCreatedGameCode(code) setShowSuccess(true) } - + // Creator needs to join their own game to get a gameToken // This allows the WebSocket to recognize them as the gamemaster try { - const username = localStorage.getItem('username') + const username = localStorage.getItem("username") const joinResponse = await joinGame({ gameCode: code, - playerName: username + playerName: username, }) - + if (joinResponse.gameToken) { - localStorage.setItem('gameToken', joinResponse.gameToken) - console.log('Creator joined game as gamemaster, token stored') + localStorage.setItem("gameToken", joinResponse.gameToken) + console.log("Creator joined game as gamemaster, token stored") } } catch (joinError) { - console.error('Failed to join game as creator:', joinError) + console.error("Failed to join game as creator:", joinError) // Continue anyway - the creator can still try to join manually } - - // Wait 3 seconds to show code, then navigate to lobby - setTimeout(() => { - console.log('Navigating to lobby with code:', code) - goLobby({ gameCode: code }) - }, 3000) + + // Azonnali navigáció a lobbyhoz, amint létrejött a játék + console.log("Navigating to lobby with code:", code) + goLobby({ gameCode: code }) } catch (err) { - console.error('Create game error:', err) - console.error('Error response:', err.response?.data) - console.error('Error status:', err.response?.status) - setError(err.response?.data?.message || err.response?.data?.error || 'Nem sikerült létrehozni a játékot') + console.error("Create game error:", err) + console.error("Error response:", err.response?.data) + console.error("Error status:", err.response?.status) + setError( + err.response?.data?.message || err.response?.data?.error || "Nem sikerült létrehozni a játékot" + ) } finally { setLoading(false) } @@ -132,26 +132,9 @@ const GameLobbySetup = () => { {deckIds.length} pakli kiválasztva. Add meg a játék részleteit. - {error && ( -
- {error} -
- )} + {error &&
{error}
} - {createdGameCode && ( -
-

Játék Létrehozva! 🎉

-

- {createdGameCode} -

-

- Oszd meg ezt a kódot más játékosokkal, hogy csatlakozhassanak! -

-

- Átirányítás a lobby-hoz 3 másodperc múlva... -

-
- )} + {/* ...a kód kiírása törölve, lobbyban jelenik meg... */}
{/* Max Players */} @@ -206,9 +189,9 @@ const GameLobbySetup = () => { className="bg-gray-600 hover:bg-gray-700" disabled={loading} /> -