-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/chess game time #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e055d43
moved chess logic to a separate custom hook
MohamedSayed0573 e403a34
Implemented fully working timer system on the client for multiplayer
MohamedSayed0573 5690b78
Implemented Timers for playing against the computer
MohamedSayed0573 e123ec0
Oragnize the hooks folder
MohamedSayed0573 3c4234c
Fixed computer timer stalling when the window is not focused.
MohamedSayed0573 d456e62
fix game:move ack doesn't return the time info to the player making t…
MohamedSayed0573 9f62d8c
small fixes
MohamedSayed0573 e48bb3c
multiple fixes
MohamedSayed0573 8ffa38f
Removed timeout on the game:move event
MohamedSayed0573 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
2 changes: 1 addition & 1 deletion
2
apps/client/src/hooks/useAuthForm.ts → apps/client/src/hooks/auth/useAuthForm.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| import type { | ||
| GameMoveAck, | ||
| GameStartedEvent, | ||
| GameStateEvent, | ||
| GameSync, | ||
| MoveMadeEvent, | ||
| PlayerColor, | ||
| PlayerJoinedEvent, | ||
| TimeInfo, | ||
| } from "@chesslab/shared/types"; | ||
| import { Chess } from "chess.js"; | ||
| import { useCallback, useEffect, useState } from "react"; | ||
| import { useSocket } from "../useSocket"; | ||
| import type { ChessboardOptions, PieceDropHandlerArgs } from "react-chessboard"; | ||
| import useTimer from "./useTimer"; | ||
|
|
||
| export function useChessGame(gameId?: string) { | ||
| const { socket } = useSocket(); | ||
|
|
||
| const [chessGame] = useState(() => new Chess()); | ||
| const [chessPosition, setChessPosition] = useState(() => chessGame.fen()); | ||
| const [gameOverInfo, setGameOverInfo] = useState<GameStateEvent | undefined>(); | ||
| const [opponentId, setOpponentId] = useState<string | undefined>(); | ||
| const [color, setColor] = useState<PlayerColor>("w"); | ||
| const [turn, setTurn] = useState<PlayerColor>("w"); | ||
| const [isGameStarted, setGameStarted] = useState(false); | ||
| const [timeInfo, setTimeInfo] = useState<TimeInfo>(); | ||
|
|
||
| const { whiteTimeMs, blackTimeMs } = useTimer({ | ||
| turn, | ||
| gameOverInfo, | ||
| timeInfo, | ||
| }); | ||
|
|
||
| const handleMove = useCallback( | ||
| ({ fen, turn, timeInfo }: MoveMadeEvent) => { | ||
| chessGame.load(fen); | ||
| setChessPosition(fen); | ||
| setTurn(turn); | ||
| setTimeInfo(timeInfo); | ||
| }, | ||
| [chessGame], | ||
| ); | ||
|
|
||
| useEffect(() => { | ||
| if (!gameId) return; | ||
|
|
||
|
MohamedSayed0573 marked this conversation as resolved.
|
||
| function handleGameOver(gameOverInfo: GameStateEvent) { | ||
| setGameOverInfo(gameOverInfo); | ||
| } | ||
|
MohamedSayed0573 marked this conversation as resolved.
|
||
|
|
||
| function handleOpponentJoined({ opponentId }: PlayerJoinedEvent) { | ||
| setOpponentId(opponentId); | ||
| } | ||
|
|
||
| function handleGameStarted({ timeInfo }: GameStartedEvent) { | ||
| setGameStarted(true); | ||
| setTimeInfo(timeInfo); | ||
| } | ||
|
|
||
| socket.on("game:game-over", handleGameOver); | ||
| socket.on("game:move-made", handleMove); | ||
| socket.on("game:game-started", handleGameStarted); | ||
| socket.on("game:player-joined", handleOpponentJoined); | ||
| socket.emit("game:sync", (res: GameSync) => { | ||
| if (!res.ok) { | ||
| console.error("game:sync failed:", res.error); | ||
| return; | ||
| } | ||
| setColor(res.color); | ||
| setOpponentId(res.opponentId); | ||
|
|
||
| handleMove(res); | ||
| if (res.opponentId) { | ||
| setGameStarted(true); | ||
| } | ||
| }); | ||
|
MohamedSayed0573 marked this conversation as resolved.
|
||
|
|
||
| return () => { | ||
| socket.off("game:move-made", handleMove); | ||
| socket.off("game:game-over", handleGameOver); | ||
| socket.off("game:game-started", handleGameStarted); | ||
| socket.off("game:player-joined", handleOpponentJoined); | ||
| }; | ||
| }, [socket, chessGame, gameId, handleMove]); | ||
|
|
||
| function onPieceDrop({ sourceSquare, targetSquare }: PieceDropHandlerArgs) { | ||
| if (!targetSquare || gameOverInfo?.gameOver || !isGameStarted) { | ||
| return false; | ||
| } | ||
|
|
||
| const chess = chessGame; | ||
|
|
||
| // Local turn check — avoid emitting when it's not our turn | ||
| if (chess.turn() !== color) { | ||
| return false; | ||
| } | ||
|
|
||
| const previousFen = chess.fen(); | ||
|
|
||
| try { | ||
| const move = chess.move({ | ||
| from: sourceSquare, | ||
| to: targetSquare, | ||
| promotion: "q", | ||
| }); | ||
| if (!move) return false; | ||
| } catch { | ||
| // chess.js throws on illegal moves | ||
| return false; | ||
| } | ||
|
|
||
| // Optimistic UI: show the move immediately | ||
| setChessPosition(chess.fen()); | ||
| setTurn(chess.turn()); | ||
|
|
||
| function fallbackMove() { | ||
| chess.load(previousFen); | ||
| setChessPosition(previousFen); | ||
| setTurn(chess.turn()); | ||
| } | ||
|
|
||
| socket.emit( | ||
| "game:move", | ||
| { | ||
| promotion: "q", | ||
| from: sourceSquare, | ||
| to: targetSquare, | ||
| }, | ||
| (data: GameMoveAck) => { | ||
| if (!data?.ok) { | ||
| fallbackMove(); | ||
| return; | ||
| } | ||
| handleMove(data); | ||
| }, | ||
| ); | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| const chessboardOptions: ChessboardOptions = { | ||
| position: chessPosition, | ||
| onPieceDrop, | ||
| id: gameId ? `board-${gameId}` : "board", | ||
| boardOrientation: color === "w" ? "white" : "black", | ||
| }; | ||
|
|
||
| return { | ||
| color, | ||
| opponentId, | ||
| gameOverInfo, | ||
| whiteTimeMs, | ||
| blackTimeMs, | ||
| turn, | ||
| chessboardOptions, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import { useEffect, useState } from "react"; | ||
|
|
||
| export const START_TIME_MS = 60 * 10 * 1000; // 10 minutes, 600_000 ms | ||
|
|
||
| interface UseCompTimerProps { | ||
| turn: "w" | "b"; | ||
| side: "w" | "b"; | ||
| isGameOver: boolean; | ||
| } | ||
|
|
||
| export function useCompTimer({ turn, side, isGameOver }: UseCompTimerProps) { | ||
| const [timeMs, setTimeMs] = useState(START_TIME_MS); | ||
| useEffect(() => { | ||
|
macroscopeapp[bot] marked this conversation as resolved.
|
||
| if (isGameOver || turn !== side) return; | ||
|
|
||
| let previousTime = Date.now(); | ||
|
|
||
| const interval = setInterval(() => { | ||
| const now = Date.now(); | ||
| const elapsed = now - previousTime; | ||
| previousTime = now; | ||
|
|
||
| setTimeMs((prev) => Math.max(0, prev - elapsed)); | ||
| }, 100); | ||
|
|
||
| return () => clearInterval(interval); | ||
| }, [side, turn, isGameOver]); | ||
|
macroscopeapp[bot] marked this conversation as resolved.
|
||
|
|
||
| return { timeMs, isTimeUp: timeMs <= 0 }; | ||
| } | ||
|
MohamedSayed0573 marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import type { ChessboardOptions, PieceDropHandlerArgs } from "react-chessboard"; | ||
| import useStockfish from "./useStockfish"; | ||
| import { Chess } from "chess.js"; | ||
| import { useState } from "react"; | ||
| import { getGameOverInfo } from "@chesslab/shared/utils"; | ||
| import { useCompTimer } from "./useCompTimer"; | ||
|
|
||
| export function useComputerGame() { | ||
| const [chessGame] = useState(() => new Chess()); | ||
| const [chessPosition, setChessPosition] = useState(() => new Chess().fen()); | ||
|
MohamedSayed0573 marked this conversation as resolved.
|
||
| const [turn, setTurn] = useState<"w" | "b">("w"); | ||
| const [gameHistory, setGameHistory] = useState<string[]>([]); | ||
| const [side] = useState<"w" | "b">(() => (Math.random() < 0.5 ? "w" : "b")); | ||
|
|
||
| let gameOverInfo = getGameOverInfo(chessGame); | ||
|
|
||
| const { timeMs, isTimeUp } = useCompTimer({ | ||
| turn, | ||
| side, | ||
| isGameOver: !!gameOverInfo, | ||
| }); | ||
|
|
||
| if (isTimeUp && !gameOverInfo) { | ||
| gameOverInfo = { | ||
| gameOver: true, | ||
| winnerColor: turn === "w" ? "b" : "w", | ||
| reason: "Timeout", | ||
| }; | ||
| } | ||
|
|
||
| useStockfish({ | ||
| chessGame, | ||
| turn, | ||
| stockfishSide: side === "w" ? "b" : "w", | ||
| isGameOver: !!gameOverInfo, | ||
| onMove: () => { | ||
| setChessPosition(chessGame.fen()); | ||
| setTurn(chessGame.turn()); | ||
| setGameHistory(chessGame.history()); | ||
| }, | ||
| }); | ||
|
|
||
| function onPieceDrop({ sourceSquare, targetSquare }: PieceDropHandlerArgs) { | ||
| if (turn !== side || !targetSquare || gameOverInfo) return false; | ||
|
|
||
| try { | ||
| const move = chessGame.move({ | ||
| from: sourceSquare, | ||
| to: targetSquare, | ||
| promotion: "q", | ||
| }); | ||
|
|
||
| if (!move) return false; | ||
|
|
||
| setChessPosition(chessGame.fen()); | ||
| setTurn(chessGame.turn()); | ||
| setGameHistory(chessGame.history()); | ||
|
|
||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| const chessboardOptions: ChessboardOptions = { | ||
| position: chessPosition, | ||
| onPieceDrop, | ||
| boardOrientation: side === "w" ? "white" : "black", | ||
| }; | ||
|
|
||
| return { | ||
| turn, | ||
| side, | ||
| timeMs, | ||
| gameHistory, | ||
| gameOverInfo, | ||
| chessboardOptions, | ||
| }; | ||
| } | ||
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.