Skip to content

Commit

Permalink
Reflect time in Frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
Airbornharsh committed Apr 21, 2024
1 parent 7dc5d19 commit 9ca3894
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions apps/frontend/src/screens/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const GAME_JOINED = "game_joined"
export const GAME_ALERT = "game_alert"
export const GAME_ADDED = "game_added"
export const USER_TIMEOUT = "user_timeout"
export const GAME_TIME = "game_time";

export interface IMove {
from: Square; to: Square
Expand All @@ -44,6 +45,8 @@ export const Game = () => {
const [gameMetadata, setGameMetadata] = useState<Metadata | null>(null)
const [result, setResult] = useState<"WHITE_WINS" | "BLACK_WINS" | "DRAW" | typeof OPPONENT_DISCONNECTED | typeof USER_TIMEOUT | null>(null);
const [moves, setMoves] = useState<IMove[]>([]);
const [myTimer, setMyTimer] = useState(10 * 60 * 1000);
const [opponentTimer, setOppotentTimer] = useState(10 * 60 * 1000);

useEffect(() => {
if (!socket) {
Expand Down Expand Up @@ -111,6 +114,16 @@ export const Game = () => {
setBoard(chess.board());
break;

case GAME_TIME:
if (message.payload.player2UserId === user.id) {
setMyTimer(message.payload.player2Time)
setOppotentTimer(message.payload.player1Time)
}else{
setMyTimer(message.payload.player1Time)
setOppotentTimer(message.payload.player2Time)
}
break;

default:
alert(message.payload.message);
break;
Expand All @@ -127,6 +140,21 @@ export const Game = () => {
}
}, [chess, socket]);

const getTimer = (tempTime: number) => {
const minutes = Math.floor(tempTime / (1000 * 60));
const remainingSeconds = Math.floor((tempTime % (1000 * 60)) / 1000);
const remainingMilliseconds = tempTime % 1000;

return (
<div className="text-white">
Time Left: {minutes < 10 ? '0' : ''}
{minutes}:{remainingSeconds < 10 ? '0' : ''}
{remainingSeconds}.{remainingMilliseconds < 100 ? '0' : ''}
{remainingMilliseconds}
</div>
);
}

if (!socket) return <div>Connecting...</div>

return <div className="">
Expand All @@ -145,6 +173,7 @@ export const Game = () => {
<div>
<div className="mb-4 flex justify-between">
<UserAvatar name={gameMetadata?.blackPlayer?.name ?? ""} />
{getTimer(opponentTimer)}
</div>
<div>
<div className={`col-span-4 w-full flex justify-center text-white ${(result === OPPONENT_DISCONNECTED || result === USER_TIMEOUT ) && "pointer-events-none"}`} >
Expand All @@ -165,6 +194,7 @@ export const Game = () => {
</div>
<div className="mt-4 flex justify-between">
<UserAvatar name={gameMetadata?.blackPlayer?.name ?? ""} />
{getTimer(myTimer)}
</div>
</div>
</div>
Expand Down

0 comments on commit 9ca3894

Please sign in to comment.