Chess_Engine / web /src /components /ChessTimer.tsx
electro-sb's picture
first commit
100a6dd
import * as React from 'react';
import { useState, useEffect } from 'react';
interface ChessTimerProps {
isWhiteTurn: boolean;
gameActive: boolean;
}
const ChessTimer: React.FC<ChessTimerProps> = ({ isWhiteTurn, gameActive }) => {
const [whiteTime, setWhiteTime] = useState<number>(600); // 10 minutes in seconds
const [blackTime, setBlackTime] = useState<number>(600); // 10 minutes in seconds
useEffect(() => {
let interval: NodeJS.Timeout | null = null;
if (gameActive) {
interval = setInterval(() => {
if (isWhiteTurn) {
setWhiteTime(prev => Math.max(0, prev - 1));
} else {
setBlackTime(prev => Math.max(0, prev - 1));
}
}, 1000);
}
return () => {
if (interval) clearInterval(interval);
};
}, [isWhiteTurn, gameActive]);
// Format time as mm:ss
const formatTime = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};
return (
<div className="mb-4">
<h3 className="text-lg font-medium mb-2">Time Control</h3>
<div className="flex justify-between">
<div className={`p-2 rounded ${isWhiteTurn && gameActive ? 'bg-blue-100 border-l-4 border-blue-500' : ''}`}>
<div className="flex items-center">
<div className="w-4 h-4 bg-white border border-gray-300 rounded-full mr-2"></div>
<span className="font-medium">White:</span>
<span className={`ml-2 ${whiteTime < 60 ? 'text-red-600' : ''}`}>
{formatTime(whiteTime)}
</span>
</div>
</div>
<div className={`p-2 rounded ${!isWhiteTurn && gameActive ? 'bg-blue-100 border-l-4 border-blue-500' : ''}`}>
<div className="flex items-center">
<div className="w-4 h-4 bg-black rounded-full mr-2"></div>
<span className="font-medium">Black:</span>
<span className={`ml-2 ${blackTime < 60 ? 'text-red-600' : ''}`}>
{formatTime(blackTime)}
</span>
</div>
</div>
</div>
</div>
);
};
export default ChessTimer;