From 770f117731e3b00d51f1b62d6ba36f5e9a970f0a Mon Sep 17 00:00:00 2001 From: jbock Date: Mon, 7 Oct 2024 20:54:07 +0200 Subject: [PATCH] accept challenge to start game --- src/main/client/src/feature/lobby/Lobby.jsx | 48 ++++++++++++------- .../client/src/feature/lobby/OpenGames.jsx | 44 ++++++++--------- .../client/src/feature/lobby/Requests.jsx | 44 ++++++++--------- src/main/java/com/bernd/GameController.java | 38 +++++++++++---- src/main/java/com/bernd/OpenGames.java | 22 ++++++++- src/main/java/com/bernd/model/OpenGame.java | 14 ++++-- 6 files changed, 131 insertions(+), 79 deletions(-) diff --git a/src/main/client/src/feature/lobby/Lobby.jsx b/src/main/client/src/feature/lobby/Lobby.jsx index ee1ebdc..7453c8b 100644 --- a/src/main/client/src/feature/lobby/Lobby.jsx +++ b/src/main/client/src/feature/lobby/Lobby.jsx @@ -1,6 +1,7 @@ import { useRef, useState, + useEffect, useContext, useCallback, } from "react" @@ -38,6 +39,7 @@ import { import { getZindex, setNewGameOpen, + setOpenGameId, handleLobbyClick, closeLobbyPopup, initialState, @@ -59,26 +61,26 @@ export function Lobby() { let [lobbyState, setLobbyState] = useState(initialState()) let zNewGame = getZindex(lobbyState, "newgame") let [detail, setDetail] = useState("open") - let stompClient = useContext(StompContext) let navigate = useNavigate() let auth = useAuthStore(state => state.auth) let newGameRef = useRef() - let onNewGame = useCallback((d) => doTry(async () => { - let response = await tfetch("/api/create", { - method: "POST", - headers: { - "Authorization": "Bearer " + auth.token, - "Content-Type": "application/json", - }, - body: JSON.stringify(d), + let stompClient = useContext(StompContext) + let initialized = useRef() + useEffect(() => { + if (initialized.current) { + return + } + initialized.current = true + let sub = stompClient.subscribe("/topic/gamestart", (message) => { + let r = JSON.parse(message.body) + if (r.opponent === auth.name) { + navigate(base + "/game/" + r.id) + } }) - let sub = stompClient.subscribe("/topic/game/" + response.id, (message) => { - let game = JSON.parse(message.body) - navigate(base + "/game/" + game.id) + return () => { sub.unsubscribe() - }) - setLobbyState(closeLobbyPopup(lobbyState)) - }), [auth.token, navigate, stompClient, lobbyState]) + } + }, [auth, initialized, stompClient, navigate]) let onStartEdit = useCallback((d) => doTry(async () => { let response = await tfetch("/api/start_edit", { method: "POST", @@ -100,7 +102,6 @@ export function Lobby() { lobbyState={lobbyState} setLobbyState={setLobbyState} newGameRef={newGameRef} - onNewGame={onNewGame} onStartEdit={onStartEdit} />