bug fixes and first try of github docker

This commit is contained in:
Stefan
2025-11-23 16:43:47 +01:00
parent 74016f08c6
commit 0aa4370f64
12 changed files with 695 additions and 350 deletions
+38
View File
@@ -0,0 +1,38 @@
name: Build and publish Docker image to GHCR
on:
push:
branches: [ "main" ]
tags:
- "v*"
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: |
ghcr.io/${{ github.repository_owner }}/chess-tutor:latest
ghcr.io/${{ github.repository_owner }}/chess-tutor:${{ github.sha }}
# Ensure API key is not baked into the image
build-args: |
NEXT_PUBLIC_GEMINI_API_KEY=
+6
View File
@@ -9,6 +9,7 @@ WORKDIR /app
COPY package.json package-lock.json ./
# Install all dependencies (including dev dependencies needed for build)
ENV NODE_ENV=development
RUN npm ci
# Stage 2: Builder
@@ -34,6 +35,11 @@ WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
# Optional: OCI-Labels für GHCR
LABEL org.opencontainers.image.source="https://github.com/stefan-kp/chess_tutor"
LABEL org.opencontainers.image.title="Chess Tutor"
LABEL org.opencontainers.image.description="AI-based chess tutor using Stockfish and Gemini"
# Create non-root user for security
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
+8 -13
View File
@@ -2,31 +2,26 @@ version: '3.8'
services:
chess-tutor:
build:
context: .
dockerfile: Dockerfile
# Optional: Uncomment to set API key at build time (not recommended for security)
# args:
# NEXT_PUBLIC_GEMINI_API_KEY: ${NEXT_PUBLIC_GEMINI_API_KEY}
image: chess-tutor:latest
image: ghcr.io/stefan-kp/chess-tutor:latest
container_name: chess-tutor
restart: unless-stopped
ports:
- "3050:3050"
env_file:
- .env
environment:
# Optional: Set API key at runtime (recommended approach)
# Users can still use browser-based API key if this is not set
- NEXT_PUBLIC_GEMINI_API_KEY=${NEXT_PUBLIC_GEMINI_API_KEY:-}
- NODE_ENV=production
healthcheck:
test: ["CMD", "node", "-e", "require('http').get('http://localhost:3050', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# Optional: Add volumes for persistent data if needed
# volumes:
# - ./data:/app/data
networks:
- chess-tutor-network
+102 -1
View File
@@ -1,5 +1,106 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import ChessGame from "@/components/ChessGame";
import StartScreen from "@/components/StartScreen";
import { Personality } from "@/lib/personalities";
type ViewState = 'start' | 'game';
export default function Home() {
return <ChessGame />;
const router = useRouter();
const [view, setView] = useState<ViewState>('start');
const [mounted, setMounted] = useState(false);
// Game Initialization State
const [gameProps, setGameProps] = useState<{
initialFen?: string;
initialPersonality: Personality;
initialColor: 'white' | 'black';
} | null>(null);
const [hasSavedGame, setHasSavedGame] = useState(false);
useEffect(() => {
// Check for API Key
const apiKey = localStorage.getItem("gemini_api_key");
if (!apiKey) {
router.push("/settings");
return;
}
// Check for saved game
const savedGame = localStorage.getItem("chess_tutor_save");
if (savedGame) {
setHasSavedGame(true);
}
setMounted(true);
}, [router]);
const handleStartGame = (options: {
personality: Personality;
color: 'white' | 'black' | 'random';
fen?: string;
}) => {
const color = options.color === 'random'
? (Math.random() < 0.5 ? 'white' : 'black')
: options.color;
setGameProps({
initialFen: options.fen,
initialPersonality: options.personality,
initialColor: color
});
setView('game');
};
const handleResumeGame = () => {
const savedGame = localStorage.getItem("chess_tutor_save");
if (savedGame) {
try {
const data = JSON.parse(savedGame);
if (data.fen && data.selectedPersonality) {
setGameProps({
initialFen: data.fen,
initialPersonality: data.selectedPersonality,
initialColor: data.playerColor || 'white'
});
setView('game');
}
} catch (e) {
console.error("Failed to resume game:", e);
}
}
};
const handleBackToMenu = () => {
setView('start');
// Re-check saved game status as it might have changed
const savedGame = localStorage.getItem("chess_tutor_save");
setHasSavedGame(!!savedGame);
};
if (!mounted) return null;
return (
<main>
{view === 'start' && (
<StartScreen
onStartGame={handleStartGame}
onResumeGame={handleResumeGame}
hasSavedGame={hasSavedGame}
/>
)}
{view === 'game' && gameProps && (
<ChessGame
initialFen={gameProps.initialFen}
initialPersonality={gameProps.initialPersonality}
initialColor={gameProps.initialColor}
onBack={handleBackToMenu}
/>
)}
</main>
);
}
+118
View File
@@ -0,0 +1,118 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Header from "@/components/Header";
import { useTranslation } from "@/lib/i18n/useTranslation";
import { SupportedLanguage } from "@/lib/i18n/translations";
import { ArrowLeft, Save } from "lucide-react";
export default function SettingsPage() {
const router = useRouter();
const [apiKey, setApiKey] = useState("");
const [language, setLanguage] = useState<SupportedLanguage>('en');
const [mounted, setMounted] = useState(false);
// Load settings on mount
useEffect(() => {
const storedKey = localStorage.getItem("gemini_api_key");
const storedLang = localStorage.getItem("chess_tutor_language");
if (storedKey) setApiKey(storedKey);
if (storedLang) setLanguage(storedLang as SupportedLanguage);
setMounted(true);
}, []);
const t = useTranslation(language);
const handleSave = () => {
if (apiKey.trim()) {
localStorage.setItem("gemini_api_key", apiKey.trim());
} else {
localStorage.removeItem("gemini_api_key");
}
localStorage.setItem("chess_tutor_language", language);
// Go back to home
router.push("/");
};
if (!mounted) return null;
return (
<>
<Header language={language} />
<div className="min-h-screen bg-gray-100 dark:bg-gray-900 p-4">
<div className="max-w-2xl mx-auto pt-8">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-8 space-y-8">
<div className="flex items-center gap-4 border-b border-gray-200 dark:border-gray-700 pb-6">
<button
onClick={() => router.push("/")}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-colors"
>
<ArrowLeft size={24} className="text-gray-600 dark:text-gray-300" />
</button>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
{t.start.settings}
</h1>
</div>
<div className="space-y-6">
{/* Language Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t.start.language}
</label>
<div className="flex gap-3">
{(['en', 'de', 'fr', 'it'] as SupportedLanguage[]).map((lang) => (
<button
key={lang}
onClick={() => setLanguage(lang)}
className={`px-4 py-2 rounded-lg border text-sm font-medium transition-all ${language === lang
? 'bg-blue-600 text-white border-blue-600 shadow-md'
: 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200'
}`}
>
{lang.toUpperCase()}
</button>
))}
</div>
</div>
{/* API Key Input */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t.start.apiKey}
</label>
<div className="space-y-2">
<input
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder={t.start.apiKeyPlaceholder}
className="w-full p-3 border rounded-lg dark:bg-gray-700 dark:border-gray-600 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none transition-all"
/>
<p className="text-xs text-gray-500 dark:text-gray-400">
{t.start.apiKeyRequired} <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noreferrer" className="text-blue-600 hover:underline">{t.start.getApiKey}</a>
</p>
</div>
</div>
</div>
<div className="pt-6 border-t border-gray-200 dark:border-gray-700 flex justify-end">
<button
onClick={handleSave}
className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium shadow-md transition-transform transform hover:scale-[1.02]"
>
<Save size={20} />
{t.common?.save || "Save Settings"}
</button>
</div>
</div>
</div>
</div>
</>
);
}
+39
View File
@@ -0,0 +1,39 @@
import React from 'react';
interface CapturedPiecesProps {
captured: string[]; // Array of piece types, e.g., ['p', 'n', 'q']
color: 'w' | 'b'; // The color of the pieces (to display the correct icon)
score?: number | null; // Material advantage, e.g., +2
}
const PIECE_ICONS: Record<string, string> = {
'p': '♟',
'n': '♞',
'b': '♝',
'r': '♜',
'q': '♛',
'k': '♚', // King is never captured, but for completeness
};
export const CapturedPieces: React.FC<CapturedPiecesProps> = ({ captured, color, score }) => {
// Sort pieces by value for better display: Q, R, B, N, P
const sortOrder = ['q', 'r', 'b', 'n', 'p'];
const sortedPieces = [...captured].sort((a, b) => sortOrder.indexOf(a) - sortOrder.indexOf(b));
return (
<div className="flex items-center h-8 gap-2 text-gray-600 dark:text-gray-300">
<div className="flex -space-x-1 text-2xl leading-none select-none">
{sortedPieces.map((piece, index) => (
<span key={index} className={color === 'w' ? "text-white drop-shadow-[0_1px_1px_rgba(0,0,0,0.8)]" : "text-black"}>
{PIECE_ICONS[piece.toLowerCase()] || piece}
</span>
))}
</div>
{score && score > 0 && (
<span className="text-xs font-semibold bg-gray-200 dark:bg-gray-700 px-1.5 py-0.5 rounded text-gray-700 dark:text-gray-300">
+{score}
</span>
)}
</div>
);
};
+147 -311
View File
@@ -5,28 +5,40 @@ import { Chess, Move } from "chess.js";
import { Chessboard } from "react-chessboard";
import { Stockfish, StockfishEvaluation } from "@/lib/stockfish";
import { Tutor } from "./Tutor";
import { APIKeyInput } from "./APIKeyInput";
import { EvaluationBar } from "./EvaluationBar";
import { Personality, PERSONALITIES } from "@/lib/personalities";
import { Personality } from "@/lib/personalities";
import Header from "./Header";
import { useTranslation } from "@/lib/i18n/useTranslation";
import { SupportedLanguage } from "@/lib/i18n/translations";
import { lookupOpening, OpeningMetadata } from "@/lib/openings";
import { GameAnalysisModal } from "./GameAnalysisModal";
import { GameOverModal, MoveHistoryItem } from "./GameOverModal";
import { Brain } from "lucide-react";
import { CapturedPieces } from "./CapturedPieces";
export default function ChessGame() {
const gameRef = useRef(new Chess());
interface ChessGameProps {
initialFen?: string;
initialPersonality: Personality;
initialColor: 'white' | 'black';
onBack: () => void;
}
const PIECE_VALUES: Record<string, number> = {
'p': 1,
'n': 3,
'b': 3,
'r': 5,
'q': 9,
'k': 0
};
export default function ChessGame({ initialFen, initialPersonality, initialColor, onBack }: ChessGameProps) {
const gameRef = useRef(new Chess(initialFen || "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"));
const [fen, setFen] = useState(gameRef.current.fen());
const [stockfish, setStockfish] = useState<Stockfish | null>(null);
// Analysis States
// evalP0: Evaluation of position BEFORE user move
const [evalP0, setEvalP0] = useState<StockfishEvaluation | null>(null);
// evalP2: Evaluation of position AFTER bot move
const [evalP2, setEvalP2] = useState<StockfishEvaluation | null>(null);
// Opening Data
@@ -38,66 +50,77 @@ export default function ChessGame() {
const [apiKey, setApiKey] = useState<string | null>(null);
const [stockfishDepth, setStockfishDepth] = useState(15);
// New States
// Settings
const [language, setLanguage] = useState<SupportedLanguage>('en');
const [gameStarted, setGameStarted] = useState(false);
const [showNewGameOptions, setShowNewGameOptions] = useState(false);
// Game State
const [playerColor, setPlayerColor] = useState<'white' | 'black'>(initialColor);
const [showAnalysisModal, setShowAnalysisModal] = useState(false);
const [customFen, setCustomFen] = useState("");
// Color Selection State
const [colorSelection, setColorSelection] = useState<'white' | 'black' | 'random'>('white');
const [playerColor, setPlayerColor] = useState<'white' | 'black'>('white');
// Game Over & History State
const [gameOverState, setGameOverState] = useState<{ result: string, winner: "White" | "Black" | "Draw" } | null>(null);
const [moveHistory, setMoveHistory] = useState<MoveHistoryItem[]>([]);
const [selectedPersonality, setSelectedPersonality] = useState<Personality>(initialPersonality);
// Personality State
const [selectedPersonality, setSelectedPersonality] = useState<Personality | null>(null);
// Captured Pieces State
const [capturedWhitePieces, setCapturedWhitePieces] = useState<string[]>([]);
const [capturedBlackPieces, setCapturedBlackPieces] = useState<string[]>([]);
const [materialScore, setMaterialScore] = useState<{ white: number, black: number }>({ white: 0, black: 0 });
// Translation
const t = useTranslation(language);
// Initialize Stockfish
useEffect(() => {
const sf = new Stockfish();
setStockfish(sf);
return () => sf.terminate();
}, []);
// Load Game State on Mount
// Load Settings & Initial State
useEffect(() => {
const savedGame = localStorage.getItem("chess_tutor_save");
if (savedGame) {
try {
const data = JSON.parse(savedGame);
if (data.fen) {
// Don't set gameRef here yet, wait for user action
// But we can preload state to show "Resume" option
setFen(data.fen);
}
if (data.language) setLanguage(data.language);
if (data.selectedPersonality) setSelectedPersonality(data.selectedPersonality);
if (data.apiKey) setApiKey(data.apiKey);
// Note: We don't persist full move history yet for simplicity,
// but we could add it to localStorage if needed.
} catch (e) {
console.error("Failed to load game:", e);
}
const storedKey = localStorage.getItem("gemini_api_key");
const storedLang = localStorage.getItem("chess_tutor_language");
if (storedKey) setApiKey(storedKey);
if (storedLang) setLanguage(storedLang as SupportedLanguage);
// If initialFen is provided, ensure gameRef is synced
if (initialFen && initialFen !== gameRef.current.fen()) {
gameRef.current = new Chess(initialFen);
setFen(initialFen);
updateCapturedPieces(); // Update captured pieces for loaded game
}
}, []);
// If computer is white (player is black) and it's the start of the game, make a move
// But only if we are at the start position
if (initialColor === 'black' &&
gameRef.current.fen() === "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" &&
stockfish) {
// Small delay to ensure stockfish is ready
setTimeout(() => {
stockfish.evaluate(gameRef.current.fen(), 10).then(evalResult => {
const computerMoveData = {
from: evalResult.bestMove.substring(0, 2),
to: evalResult.bestMove.substring(2, 4),
promotion: evalResult.bestMove.length > 4 ? evalResult.bestMove.substring(4, 5) : "q"
};
makeAMove(computerMoveData);
});
}, 1000);
}
}, [initialFen, initialColor, stockfish]); // Run when these change
// Save Game State on Change
useEffect(() => {
if (!gameStarted) return;
const saveData = {
fen,
language,
selectedPersonality,
apiKey
apiKey,
playerColor // Save player color too
};
localStorage.setItem("chess_tutor_save", JSON.stringify(saveData));
}, [fen, language, selectedPersonality, apiKey, gameStarted]);
}, [fen, language, selectedPersonality, apiKey, playerColor]);
// Game Over Detection
useEffect(() => {
@@ -126,7 +149,7 @@ export default function ChessGame() {
}
}, [fen]);
// Pre-Analysis (P0): Run whenever it's White's turn (User) and we are waiting for a move
// Pre-Analysis (P0)
useEffect(() => {
if (stockfish && gameRef.current.turn() === 'w' && !isAnalyzing && !gameOverState) {
stockfish.evaluate(gameRef.current.fen(), stockfishDepth).then(evalResult => {
@@ -135,6 +158,30 @@ export default function ChessGame() {
}
}, [fen, stockfish, stockfishDepth, isAnalyzing, gameOverState]);
const updateCapturedPieces = useCallback(() => {
const history = gameRef.current.history({ verbose: true });
const whitePiecesLost: string[] = [];
const blackPiecesLost: string[] = [];
let whiteLostScore = 0;
let blackLostScore = 0;
history.forEach(move => {
if (move.captured) {
if (move.color === 'w') { // White moved, captured a black piece. So a black piece was lost.
blackPiecesLost.push(move.captured);
blackLostScore += PIECE_VALUES[move.captured] || 0;
} else { // Black moved, captured a white piece. So a white piece was lost.
whitePiecesLost.push(move.captured);
whiteLostScore += PIECE_VALUES[move.captured] || 0;
}
}
});
setCapturedWhitePieces(whitePiecesLost);
setCapturedBlackPieces(blackPiecesLost);
setMaterialScore({ white: whiteLostScore, black: blackLostScore });
}, []);
const makeAMove = useCallback(
(move: { from: string; to: string; promotion?: string }) => {
try {
@@ -144,6 +191,13 @@ export default function ChessGame() {
if (result) {
const newFen = game.fen();
setFen(newFen);
updateCapturedPieces();
// If it was computer's move, update state
if (game.turn() === 'w') { // Computer just moved (assuming computer is Black? No, wait)
// Logic below handles turns
}
return { result, newFen };
}
} catch (e) {
@@ -151,7 +205,7 @@ export default function ChessGame() {
}
return null;
},
[]
[updateCapturedPieces]
);
function onDrop({ sourceSquare, targetSquare }: { sourceSquare: string; targetSquare: string | null }) {
@@ -160,7 +214,7 @@ export default function ChessGame() {
const move = {
from: sourceSquare,
to: targetSquare,
promotion: "q", // always promote to queen for simplicity
promotion: "q",
};
// 1. User Move (P0 -> P1)
@@ -170,7 +224,7 @@ export default function ChessGame() {
setUserMove(moveResult.result);
// Reset Computer State immediately to prevent "Hallucination" / Double Chat
// Reset Computer State
setComputerMove(null);
setEvalP2(null);
setOpeningData(null);
@@ -179,27 +233,9 @@ export default function ChessGame() {
const { newFen: fenP1 } = moveResult;
// 2. Bot Move (P1 -> P2)
// We need to find the best move for Black from P1
stockfish.evaluate(fenP1, stockfishDepth).then(p1Eval => {
// We don't store p1Eval for the Tutor, but we use it to decide the move
// Record User Move History (P0 -> P1)
// We compare evalP0 (Before) vs p1Eval (After)
// Note: p1Eval is from Black's perspective usually in engines, but our wrapper might normalize.
// Let's assume our wrapper returns CP relative to side to move or absolute?
// Standard Stockfish returns relative to side to move.
// So if White is winning +100:
// P0 (White to move): +100
// P1 (Black to move): -100 (Black is losing)
// So we need to negate p1Eval.score to compare with evalP0.score (if evalP0 is White's perspective).
// Actually, let's check our Stockfish wrapper. It usually returns absolute or relative.
// Assuming relative:
// P0 (White): +1.0
// P1 (Black): -1.0 (Black is down 1.0)
// So evalAfter = -p1Eval.score
if (evalP0) {
const evalAfter = -p1Eval.score; // Convert back to White's perspective
const evalAfter = -p1Eval.score;
const historyItem: MoveHistoryItem = {
moveNumber: gameRef.current.moveNumber(),
move: moveResult.result.san,
@@ -247,249 +283,36 @@ export default function ChessGame() {
return true;
}
const handleResume = () => {
// gameRef needs to be synced with state fen
gameRef.current = new Chess(fen);
setGameStarted(true);
const handleNewGame = () => {
// Reset game to initial props or just reload?
// For now, let's just reset the board
const newGame = new Chess();
gameRef.current = newGame;
setFen(newGame.fen());
setGameOverState(null);
setMoveHistory([]);
setUserMove(null);
setComputerMove(null);
setEvalP0(null);
setEvalP2(null);
setOpeningData(null);
updateCapturedPieces();
};
const handleNewGame = (personality: Personality) => {
const startFen = customFen.trim() || "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
try {
const newGame = new Chess(startFen);
gameRef.current = newGame;
setFen(startFen);
setSelectedPersonality(personality);
// Determine player color (resolve random)
let finalPlayerColor: 'white' | 'black' = colorSelection === 'random'
? (Math.random() < 0.5 ? 'white' : 'black')
: colorSelection;
setPlayerColor(finalPlayerColor);
// Reset Analysis State
setUserMove(null);
setComputerMove(null);
setEvalP0(null);
setEvalP2(null);
setOpeningData(null);
setGameOverState(null);
setMoveHistory([]);
setGameStarted(true);
setCustomFen(""); // Clear input
// If player is Black, computer moves first
if (finalPlayerColor === 'black' && stockfish) {
setTimeout(() => {
stockfish.evaluate(startFen, stockfishDepth).then(evalResult => {
const computerMoveData = {
from: evalResult.bestMove.substring(0, 2),
to: evalResult.bestMove.substring(2, 4),
promotion: evalResult.bestMove.length > 4 ? evalResult.bestMove.substring(4, 5) : "q"
};
const compResult = makeAMove(computerMoveData);
if (compResult) {
setComputerMove(compResult.result);
const { newFen: fenAfterComp } = compResult;
setFen(fenAfterComp);
// Evaluate position after computer's first move
stockfish.evaluate(fenAfterComp, stockfishDepth).then(p0Eval => {
setEvalP0(p0Eval);
}).catch(err => console.error("Initial eval failed:", err));
}
}).catch(err => console.error("Computer first move failed:", err));
}, 500);
}
} catch (e) {
alert("Invalid FEN string");
}
};
const handleBackToMenu = () => {
setGameStarted(false);
setShowNewGameOptions(false);
};
if (!gameStarted) {
const hasSavedGame = fen !== "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
return (
<>
<Header language={language} />
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900 p-4">
<h1 className="text-4xl font-bold mb-8 text-gray-800 dark:text-white">{t.start.title}</h1>
<div className="bg-white dark:bg-gray-800 p-8 rounded-xl shadow-lg max-w-2xl w-full space-y-8">
{/* Step 1: Language & API Key */}
<div className="space-y-4">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t.start.settings}</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t.start.language}</label>
<div className="flex gap-2">
{(['en', 'de', 'fr', 'it'] as SupportedLanguage[]).map((lang) => (
<button
key={lang}
onClick={() => setLanguage(lang)}
className={`px-3 py-2 rounded-lg border text-sm ${language === lang ? 'bg-blue-600 text-white border-blue-600' : 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600'}`}
>
{lang.toUpperCase()}
</button>
))}
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t.start.apiKey}</label>
<input
type="password"
placeholder={t.start.apiKeyPlaceholder}
value={apiKey || ""}
onChange={(e) => setApiKey(e.target.value)}
className="w-full p-2 border rounded dark:bg-gray-700 dark:border-gray-600"
/>
<p className="text-xs text-gray-500 mt-1">
<a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noreferrer" className="text-blue-600 hover:underline">{t.start.getApiKey}</a>
</p>
</div>
</div>
</div>
{/* Step 2: Game Actions */}
<div className="space-y-4">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t.start.startGame}</h2>
{!apiKey ? (
<div className="p-4 bg-yellow-50 text-yellow-800 rounded-lg text-sm">
{t.start.apiKeyRequired}
</div>
) : (
<div className="space-y-4">
{/* Resume Option */}
{hasSavedGame && !showNewGameOptions && (
<div className="space-y-3">
<button
onClick={handleResume}
className="w-full py-4 bg-green-600 text-white rounded-xl hover:bg-green-700 font-bold text-lg shadow-md transition-transform transform hover:scale-[1.02]"
>
{t.start.resumeGame}
</button>
<button
onClick={() => setShowNewGameOptions(true)}
className="w-full py-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white text-sm"
>
{t.start.startNewGame}
</button>
</div>
)}
{/* New Game Options */}
{(!hasSavedGame || showNewGameOptions) && (
<div className="space-y-6 animate-in fade-in slide-in-from-top-4 duration-300">
{/* Color Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
{t.start.colorSelection}
</label>
<div className="grid grid-cols-3 gap-3">
<button
onClick={() => setColorSelection('white')}
className={`py-3 px-4 rounded-lg border text-sm font-medium transition-all ${colorSelection === 'white'
? 'bg-blue-600 text-white border-blue-600 shadow-md'
: 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
>
<span className="text-2xl"></span> {t.start.playAsWhite}
</button>
<button
onClick={() => setColorSelection('black')}
className={`py-3 px-4 rounded-lg border text-sm font-medium transition-all ${colorSelection === 'black'
? 'bg-blue-600 text-white border-blue-600 shadow-md'
: 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
>
<span className="text-2xl"></span> {t.start.playAsBlack}
</button>
<button
onClick={() => setColorSelection('random')}
className={`py-3 px-4 rounded-lg border text-sm font-medium transition-all ${colorSelection === 'random'
? 'bg-blue-600 text-white border-blue-600 shadow-md'
: 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
>
<span className="text-2xl">🎲</span> {t.start.randomColor}
</button>
</div>
</div>
{/* FEN Import */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t.start.importPosition}
</label>
<input
type="text"
placeholder={t.start.importPositionPlaceholder}
value={customFen}
onChange={(e) => setCustomFen(e.target.value)}
className="w-full p-2 border rounded dark:bg-gray-700 dark:border-gray-600 font-mono text-sm"
/>
</div>
{/* Personality Grid */}
<div>
<p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{t.start.chooseCoach}</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{PERSONALITIES.map(p => (
<button
key={p.id}
onClick={() => handleNewGame(p)}
className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors border border-gray-200 dark:border-gray-600 flex flex-col items-center text-center"
>
<div className="text-4xl mb-2">{p.image}</div>
<h3 className="font-bold text-gray-900 dark:text-white">{p.name}</h3>
<p className="text-xs text-gray-500 dark:text-gray-400">{p.description}</p>
</button>
))}
</div>
</div>
{hasSavedGame && (
<button
onClick={() => setShowNewGameOptions(false)}
className="text-sm text-gray-500 hover:text-gray-700"
>
{t.common.cancel}
</button>
)}
</div>
)}
</div>
)}
</div>
</div>
</div>
</>
);
}
// Determine material advantage
// If Black lost more value, White has advantage
const whiteAdvantage = materialScore.black - materialScore.white;
const blackAdvantage = materialScore.white - materialScore.black;
return (
<>
<Header language={language} />
<div className="flex flex-col md:flex-row gap-8 w-full max-w-6xl mx-auto p-4">
{/* API Key Input is now handled in start screen, but we keep the button for updates */}
{/* <APIKeyInput onKeySubmit={setApiKey} /> */}
<div className="w-full md:w-2/3 flex flex-col gap-4">
{/* Header with Back Button */}
<div className="flex justify-between items-center">
<button
onClick={handleBackToMenu}
onClick={onBack}
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 text-sm font-medium transition-colors"
>
{t.game.backToMenu}
@@ -500,13 +323,23 @@ export default function ChessGame() {
</div>
<div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow-lg flex gap-4">
<div className="h-[560px]"> {/* Match board height roughly */}
<div className="h-[560px]">
<EvaluationBar
score={isAnalyzing ? null : evalP0?.score} // Show P0 score while waiting, or maybe P2 after move? Let's show current board eval.
score={isAnalyzing ? null : evalP0?.score}
mate={isAnalyzing ? null : evalP0?.mate}
isPlayerWhite={playerColor === 'white'}
/>
</div>
<div className="flex-1">
<div className="flex-1 flex flex-col justify-center">
{/* Opponent's Captured Pieces (Top) */}
<div className="mb-2 h-8">
<CapturedPieces
captured={playerColor === 'white' ? capturedWhitePieces : capturedBlackPieces}
color={playerColor === 'white' ? 'w' : 'b'} // If player is white, opponent is black. Show White's lost pieces (capturedWhitePieces)
score={playerColor === 'white' ? (blackAdvantage > 0 ? blackAdvantage : null) : (whiteAdvantage > 0 ? whiteAdvantage : null)}
/>
</div>
<Chessboard
options={{
position: fen,
@@ -514,9 +347,18 @@ export default function ChessGame() {
darkSquareStyle: { backgroundColor: '#779954' },
lightSquareStyle: { backgroundColor: '#e9edcc' },
animationDurationInMs: 200,
boardOrientation: playerColor // Set board orientation based on player color
boardOrientation: playerColor
}}
/>
{/* Player's Captured Pieces (Bottom) */}
<div className="mt-2 h-8">
<CapturedPieces
captured={playerColor === 'white' ? capturedBlackPieces : capturedWhitePieces}
color={playerColor === 'white' ? 'b' : 'w'} // If player is white, show Black's lost pieces (capturedBlackPieces)
score={playerColor === 'white' ? (whiteAdvantage > 0 ? whiteAdvantage : null) : (blackAdvantage > 0 ? blackAdvantage : null)}
/>
</div>
</div>
</div>
@@ -528,16 +370,15 @@ export default function ChessGame() {
<button
onClick={() => {
const game = gameRef.current;
// Undo twice: once for computer, once for user
game.undo();
game.undo();
setFen(game.fen());
// Reset moves to prevent re-analysis of old moves
setUserMove(null);
setComputerMove(null);
setEvalP0(null);
setEvalP2(null);
setOpeningData(null);
updateCapturedPieces();
}}
className="px-3 py-1 text-sm bg-red-100 text-red-700 rounded hover:bg-red-200 dark:bg-red-900 dark:text-red-200 transition-colors"
>
@@ -554,8 +395,6 @@ export default function ChessGame() {
/>
</div>
{/* PGN Display */}
{/* Game History (Scrollable List) */}
<div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow-lg flex-1 min-h-0 flex flex-col">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Game History</h3>
@@ -601,7 +440,6 @@ export default function ChessGame() {
})()}
</tbody>
</table>
{/* Auto-scroll anchor */}
<div ref={(el) => el?.scrollIntoView({ behavior: "smooth" })} />
</div>
</div>
@@ -618,13 +456,12 @@ export default function ChessGame() {
openingData={openingData}
onAnalysisComplete={() => { }}
apiKey={apiKey}
personality={selectedPersonality!}
personality={selectedPersonality}
language={language}
playerColor={playerColor}
/>
</div>
{/* Analysis Modal */}
{showAnalysisModal && (
<GameAnalysisModal
fen={fen}
@@ -635,7 +472,6 @@ export default function ChessGame() {
/>
)}
{/* Game Over Modal */}
{gameOverState && (
<GameOverModal
result={gameOverState.result}
@@ -644,7 +480,7 @@ export default function ChessGame() {
apiKey={apiKey}
language={language}
onClose={() => setGameOverState(null)}
onNewGame={() => handleNewGame(selectedPersonality!)}
onNewGame={handleNewGame}
/>
)}
</div>
+20 -22
View File
@@ -5,9 +5,10 @@ import clsx from "clsx";
interface EvaluationBarProps {
score?: number | null; // centipawns
mate?: number | null; // moves to mate
isPlayerWhite: boolean;
}
export function EvaluationBar({ score, mate }: EvaluationBarProps) {
export function EvaluationBar({ score, mate, isPlayerWhite }: EvaluationBarProps) {
// Calculate white's percentage height
// Using sigmoid-like function for score: P = 1 / (1 + 10^(-score/400))
// This is a standard way to visualize CP advantage.
@@ -18,7 +19,7 @@ export function EvaluationBar({ score, mate }: EvaluationBarProps) {
// Mate detected
if (mate > 0) {
whiteHeightPercent = 100;
label = `M${mate}`;
label = `M${Math.abs(mate)}`;
} else {
whiteHeightPercent = 0;
label = `M${Math.abs(mate)}`;
@@ -30,37 +31,34 @@ export function EvaluationBar({ score, mate }: EvaluationBarProps) {
whiteHeightPercent = winChance * 100;
// Format label: +1.5 or -0.3
const pawnScore = score / 100;
label = pawnScore > 0 ? `+${pawnScore.toFixed(1)}` : pawnScore.toFixed(1);
// If player is NOT white, we invert the score for display (so + means Player advantage)
let displayScore = score / 100;
if (!isPlayerWhite) {
displayScore = -displayScore;
}
label = displayScore > 0 ? `+${displayScore.toFixed(1)}` : displayScore.toFixed(1);
if (score === 0) label = "0.0";
}
// Invert label color based on background
// If whiteHeightPercent is high, top is white, text should be black if it's at the top?
// Actually, usually the text is placed based on who is winning or fixed.
// Let's place text at top for White advantage and bottom for Black?
// Or just center it? Standard is usually top/bottom or floating.
// Let's keep it simple: Text always visible, color contrasting with the bar it's on.
// We'll put the text in a small badge that floats?
// Or just inside the bar.
return (
<div className="w-8 h-full bg-gray-800 border border-gray-400 flex flex-col-reverse relative overflow-hidden rounded shadow-inner">
<div className="w-8 h-full bg-gray-800 border border-gray-400 relative overflow-hidden rounded shadow-inner">
{/* Black background is the container (h-full) */}
{/* White bar grows from bottom (flex-col-reverse) */}
{/* White bar grows from bottom if player is white, from top if player is black */}
<div
className="w-full bg-white transition-all duration-500 ease-in-out"
className={clsx(
"absolute w-full bg-white transition-all duration-500 ease-in-out",
isPlayerWhite ? "bottom-0" : "top-0"
)}
style={{ height: `${whiteHeightPercent}%` }}
/>
{/* Score Label */}
<div className={clsx(
"absolute w-full text-center text-xs font-bold py-1 select-none",
whiteHeightPercent > 50 ? "top-0 text-gray-800" : "bottom-0 text-white"
)}>
{label}
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-xs font-bold text-white mix-blend-difference select-none">
{label}
</span>
</div>
</div>
);
+199
View File
@@ -0,0 +1,199 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Settings, ChevronDown, ChevronUp } from "lucide-react";
import { Personality, PERSONALITIES } from "@/lib/personalities";
import { useTranslation } from "@/lib/i18n/useTranslation";
import { SupportedLanguage } from "@/lib/i18n/translations";
import Header from "./Header";
interface StartScreenProps {
onStartGame: (options: {
personality: Personality;
color: 'white' | 'black' | 'random';
fen?: string;
}) => void;
onResumeGame: () => void;
hasSavedGame: boolean;
}
export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }: StartScreenProps) {
const router = useRouter();
const [language, setLanguage] = useState<SupportedLanguage>('en');
const [showNewGameOptions, setShowNewGameOptions] = useState(false);
const [customFen, setCustomFen] = useState("");
const [colorSelection, setColorSelection] = useState<'white' | 'black' | 'random'>('white');
const [showAdvanced, setShowAdvanced] = useState(false);
const [mounted, setMounted] = useState(false);
useEffect(() => {
const storedLang = localStorage.getItem("chess_tutor_language");
if (storedLang) setLanguage(storedLang as SupportedLanguage);
setMounted(true);
}, []);
const t = useTranslation(language);
const handleNewGame = (personality: Personality) => {
onStartGame({
personality,
color: colorSelection,
fen: customFen.trim() || undefined
});
};
if (!mounted) return null;
return (
<>
<Header language={language} />
<div className="min-h-screen bg-gray-100 dark:bg-gray-900 p-4 flex flex-col items-center justify-center">
<div className="absolute top-4 right-4 md:top-8 md:right-8">
<button
onClick={() => router.push("/settings")}
className="p-3 bg-white dark:bg-gray-800 rounded-full shadow-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-all text-gray-700 dark:text-gray-200"
title={t.start.settings}
>
<Settings size={24} />
</button>
</div>
<h1 className="text-5xl font-bold mb-12 text-gray-800 dark:text-white tracking-tight">
{t.start.title}
</h1>
<div className="bg-white dark:bg-gray-800 p-8 rounded-2xl shadow-xl max-w-3xl w-full space-y-8">
<div className="space-y-6">
<h2 className="text-2xl font-bold text-gray-900 dark:text-white border-b border-gray-100 dark:border-gray-700 pb-4">
{t.start.startGame}
</h2>
<div className="space-y-4">
{/* Resume Option */}
{hasSavedGame && !showNewGameOptions && (
<div className="space-y-4">
<button
onClick={onResumeGame}
className="w-full py-5 bg-green-600 text-white rounded-xl hover:bg-green-700 font-bold text-xl shadow-lg transition-transform transform hover:scale-[1.02] flex items-center justify-center gap-3"
>
<span></span> {t.start.resumeGame}
</button>
<div className="relative flex py-2 items-center">
<div className="flex-grow border-t border-gray-200 dark:border-gray-700"></div>
<span className="flex-shrink-0 mx-4 text-gray-400 text-sm">OR</span>
<div className="flex-grow border-t border-gray-200 dark:border-gray-700"></div>
</div>
<button
onClick={() => setShowNewGameOptions(true)}
className="w-full py-3 bg-white dark:bg-gray-700 border-2 border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-200 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-600 font-semibold transition-colors"
>
{t.start.startNewGame}
</button>
</div>
)}
{/* New Game Options */}
{(!hasSavedGame || showNewGameOptions) && (
<div className="space-y-8 animate-in fade-in slide-in-from-top-4 duration-300">
{/* Color Selection */}
<div>
<label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-3 uppercase tracking-wide">
{t.start.colorSelection}
</label>
<div className="grid grid-cols-3 gap-4">
<button
onClick={() => setColorSelection('white')}
className={`py-4 px-4 rounded-xl border-2 text-sm font-bold transition-all flex flex-col items-center gap-2 ${colorSelection === 'white'
? 'bg-blue-50 border-blue-600 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400'
: 'bg-white dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:border-blue-300 dark:hover:border-blue-500'
}`}
>
<span className="text-3xl"></span> {t.start.playAsWhite}
</button>
<button
onClick={() => setColorSelection('black')}
className={`py-4 px-4 rounded-xl border-2 text-sm font-bold transition-all flex flex-col items-center gap-2 ${colorSelection === 'black'
? 'bg-blue-50 border-blue-600 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400'
: 'bg-white dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:border-blue-300 dark:hover:border-blue-500'
}`}
>
<span className="text-3xl"></span> {t.start.playAsBlack}
</button>
<button
onClick={() => setColorSelection('random')}
className={`py-4 px-4 rounded-xl border-2 text-sm font-bold transition-all flex flex-col items-center gap-2 ${colorSelection === 'random'
? 'bg-blue-50 border-blue-600 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400'
: 'bg-white dark:bg-gray-700 border-gray-200 dark:border-gray-600 hover:border-blue-300 dark:hover:border-blue-500'
}`}
>
<span className="text-3xl">🎲</span> {t.start.randomColor}
</button>
</div>
</div>
{/* Personality Grid */}
<div>
<p className="text-sm font-bold text-gray-700 dark:text-gray-300 mb-3 uppercase tracking-wide">
{t.start.chooseCoach}
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{PERSONALITIES.map(p => (
<button
key={p.id}
onClick={() => handleNewGame(p)}
className="group relative bg-gray-50 dark:bg-gray-700 p-5 rounded-xl hover:bg-white dark:hover:bg-gray-600 transition-all border-2 border-transparent hover:border-blue-500 dark:hover:border-blue-400 shadow-sm hover:shadow-md text-left flex items-start gap-4"
>
<div className="text-4xl shrink-0 group-hover:scale-110 transition-transform">{p.image}</div>
<div>
<h3 className="font-bold text-gray-900 dark:text-white text-lg">{p.name}</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1 leading-relaxed">{p.description}</p>
</div>
</button>
))}
</div>
</div>
{/* Advanced Options (Accordion) */}
<div className="border-t border-gray-200 dark:border-gray-700 pt-4">
<button
onClick={() => setShowAdvanced(!showAdvanced)}
className="flex items-center gap-2 text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
>
{showAdvanced ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
Advanced Options
</button>
{showAdvanced && (
<div className="mt-4 animate-in fade-in slide-in-from-top-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
{t.start.importPosition}
</label>
<input
type="text"
placeholder={t.start.importPositionPlaceholder}
value={customFen}
onChange={(e) => setCustomFen(e.target.value)}
className="w-full p-3 border rounded-lg dark:bg-gray-700 dark:border-gray-600 font-mono text-sm focus:ring-2 focus:ring-blue-500 outline-none"
/>
</div>
)}
</div>
{hasSavedGame && (
<button
onClick={() => setShowNewGameOptions(false)}
className="w-full py-3 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
>
{t.common.cancel}
</button>
)}
</div>
)}
</div>
</div>
</div>
</div>
</>
);
}
+3 -2
View File
@@ -170,13 +170,14 @@ You can use this metadata to explain the position:
const prompt = `
[SYSTEM TRIGGER: move_exchange]
User (White) Move: ${userMove.san}
My (Black) Reply: ${computerMove.san}
User (${playerColorName}) Move: ${userMove.san}
My (${tutorColorName}) Reply: ${computerMove.san}
My Internal Thoughts (Data):
- Pre-Eval (Before User Move): ${preScore} cp
- Post-Eval (After My Reply): ${postScore} cp
- Delta: ${delta} cp
(Note: Scores are from White's perspective. Positive = White advantage, Negative = Black advantage.)
INSTRUCTIONS:
1. ${evalInstruction}
+5
View File
@@ -8,6 +8,7 @@ export interface Translations {
confirm: string;
loading: string;
error: string;
save: string;
};
// Header
@@ -104,6 +105,7 @@ const en: Translations = {
confirm: 'Confirm',
loading: 'Loading...',
error: 'Error',
save: 'Save',
},
header: {
tagline: 'with Gemini & Stockfish',
@@ -186,6 +188,7 @@ const de: Translations = {
confirm: 'Bestätigen',
loading: 'Lädt...',
error: 'Fehler',
save: 'Speichern',
},
header: {
tagline: 'mit Gemini & Stockfish',
@@ -268,6 +271,7 @@ const fr: Translations = {
confirm: 'Confirmer',
loading: 'Chargement...',
error: 'Erreur',
save: 'Enregistrer',
},
header: {
tagline: 'avec Gemini & Stockfish',
@@ -350,6 +354,7 @@ const it: Translations = {
confirm: 'Conferma',
loading: 'Caricamento...',
error: 'Errore',
save: 'Salva',
},
header: {
tagline: 'con Gemini & Stockfish',
+10 -1
View File
@@ -27,7 +27,7 @@ export class Stockfish {
}
async evaluate(fen: string, depth: number = 15, multiPV: number = 1): Promise<StockfishEvaluation> {
return new Promise((resolve, reject) => {
return new Promise<StockfishEvaluation>((resolve, reject) => {
if (!this.worker) {
reject("Stockfish worker not initialized");
return;
@@ -81,6 +81,15 @@ export class Stockfish {
this.worker.addEventListener("message", handler);
this.worker.postMessage(`position fen ${fen}`);
this.worker.postMessage(`go depth ${depth}`);
}).then((evalResult: StockfishEvaluation) => {
// Normalize score to be from White's perspective
// Stockfish returns score relative to side to move
const sideToMove = fen.split(" ")[1]; // 'w' or 'b'
if (sideToMove === 'b') {
if (evalResult.score !== 0) evalResult.score = -evalResult.score;
if (evalResult.mate !== null && evalResult.mate !== 0) evalResult.mate = -evalResult.mate;
}
return evalResult;
});
}