Add Bulgarian Solitaire interactive

Create a new interactive component for Bulgarian Solitaire. This component will allow users to select a number `n` (2-6), visualize a container with `1+2+...+n` boxes, and arrange these boxes into `1+2+...+n` columns. Users can drag and drop boxes between columns and return them to the container by double-clicking. A "Play" button will initiate the simulation of the Bulgarian Solitaire process until a steady state is reached. This interactive will be added to the Puzzles section.
This commit is contained in:
gpt-engineer-app[bot] 2025-08-21 11:16:49 +00:00
parent dcdfa9e5f5
commit cb484c418e
4 changed files with 348 additions and 0 deletions

View file

@ -51,6 +51,7 @@ import SikiniaParliamentPuzzlePage from './pages/SikiniaParliamentPuzzlePage';
import NQueensPuzzlePage from './pages/NQueensPuzzlePage'; import NQueensPuzzlePage from './pages/NQueensPuzzlePage';
import RulesOfInferencePlaygroundPage from './pages/RulesOfInferencePlaygroundPage'; import RulesOfInferencePlaygroundPage from './pages/RulesOfInferencePlaygroundPage';
import PebblePlacementGamePage from './pages/PebblePlacementGamePage'; import PebblePlacementGamePage from './pages/PebblePlacementGamePage';
import BulgarianSolitairePage from './pages/BulgarianSolitairePage';
const queryClient = new QueryClient(); const queryClient = new QueryClient();
@ -104,6 +105,7 @@ const App = () => (
<Route path="/games/assisted-nim" element={<AssistedNimGamePage />} /> <Route path="/games/assisted-nim" element={<AssistedNimGamePage />} />
<Route path="/games/gold-coin" element={<GoldCoinGamePage />} /> <Route path="/games/gold-coin" element={<GoldCoinGamePage />} />
<Route path="/puzzles/pebble-placement" element={<PebblePlacementGamePage />} /> <Route path="/puzzles/pebble-placement" element={<PebblePlacementGamePage />} />
<Route path="/puzzles/bulgarian-solitaire" element={<BulgarianSolitairePage />} />
<Route path="/puzzles/sikinia-parliament" element={<SikiniaParliamentPuzzlePage />} /> <Route path="/puzzles/sikinia-parliament" element={<SikiniaParliamentPuzzlePage />} />
<Route path="/puzzles/plate-swap" element={<PlateSwapPuzzlePage />} /> <Route path="/puzzles/plate-swap" element={<PlateSwapPuzzlePage />} />
<Route path="/puzzles/chessboard-repaint" element={<ChessboardRepaintPuzzlePage />} /> <Route path="/puzzles/chessboard-repaint" element={<ChessboardRepaintPuzzlePage />} />

View file

@ -0,0 +1,307 @@
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import SocialShare from '@/components/SocialShare';
import { toast } from 'sonner';
interface BulgarianSolitaireProps {
showSocialShare?: boolean;
}
interface Box {
id: number;
columnIndex: number | null; // null means it's in the container
}
const BulgarianSolitaire: React.FC<BulgarianSolitaireProps> = ({ showSocialShare }) => {
const [n, setN] = useState(3);
const [boxes, setBoxes] = useState<Box[]>([]);
const [columns, setColumns] = useState<number[][]>([]);
const [isPlaying, setIsPlaying] = useState(false);
const [draggedBox, setDraggedBox] = useState<number | null>(null);
const [step, setStep] = useState(0);
const [isComplete, setIsComplete] = useState(false);
const totalBoxes = (n * (n + 1)) / 2;
// Initialize boxes and columns when n changes
useEffect(() => {
const newBoxes: Box[] = [];
for (let i = 0; i < totalBoxes; i++) {
newBoxes.push({ id: i, columnIndex: null });
}
setBoxes(newBoxes);
setColumns(Array.from({ length: totalBoxes }, () => []));
setStep(0);
setIsComplete(false);
}, [n, totalBoxes]);
const handleDragStart = (e: React.DragEvent, boxId: number) => {
setDraggedBox(boxId);
e.dataTransfer.effectAllowed = 'move';
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
const handleDrop = (e: React.DragEvent, columnIndex: number) => {
e.preventDefault();
if (draggedBox === null) return;
const box = boxes.find(b => b.id === draggedBox);
if (!box || box.columnIndex === columnIndex) return;
// Remove from previous location
if (box.columnIndex !== null) {
setColumns(prev => prev.map((col, idx) =>
idx === box.columnIndex ? col.filter(id => id !== draggedBox) : col
));
}
// Add to new column
setColumns(prev => prev.map((col, idx) =>
idx === columnIndex ? [...col, draggedBox] : col
));
// Update box location
setBoxes(prev => prev.map(b =>
b.id === draggedBox ? { ...b, columnIndex } : b
));
setDraggedBox(null);
};
const handleDoubleClick = (boxId: number) => {
const box = boxes.find(b => b.id === boxId);
if (!box || box.columnIndex === null) return;
// Remove from column
setColumns(prev => prev.map((col, idx) =>
idx === box.columnIndex ? col.filter(id => id !== boxId) : col
));
// Return to container
setBoxes(prev => prev.map(b =>
b.id === boxId ? { ...b, columnIndex: null } : b
));
};
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const isTriangularConfiguration = (cols: number[][]) => {
const nonEmptyCols = cols.filter(col => col.length > 0).sort((a, b) => a.length - b.length);
if (nonEmptyCols.length !== n) return false;
for (let i = 0; i < n; i++) {
if (nonEmptyCols[i].length !== i + 1) return false;
}
return true;
};
const simulateBulgarianSolitaire = async () => {
if (boxes.filter(b => b.columnIndex === null).length > 0) {
toast.error("Please place all boxes in columns before playing!");
return;
}
setIsPlaying(true);
setStep(0);
let currentColumns = [...columns];
let stepCount = 0;
while (!isTriangularConfiguration(currentColumns) && stepCount < 50) {
stepCount++;
setStep(stepCount);
// Create new pile from non-empty columns
const newPile: number[] = [];
const updatedColumns = currentColumns.map(col => {
if (col.length > 0) {
const boxToMove = col[col.length - 1]; // Take from top
newPile.push(boxToMove);
return col.slice(0, -1); // Remove from column
}
return col;
});
// Add the new pile
const emptyColumnIndex = updatedColumns.findIndex(col => col.length === 0);
if (emptyColumnIndex !== -1) {
updatedColumns[emptyColumnIndex] = newPile;
} else {
// This shouldn't happen in a properly configured game
console.error("No empty column found for new pile");
break;
}
currentColumns = updatedColumns;
setColumns(currentColumns);
// Update box positions
setBoxes(prev => prev.map(box => {
for (let i = 0; i < currentColumns.length; i++) {
if (currentColumns[i].includes(box.id)) {
return { ...box, columnIndex: i };
}
}
return box;
}));
await sleep(1000); // Wait 1 second between steps
}
setIsComplete(isTriangularConfiguration(currentColumns));
setIsPlaying(false);
if (isTriangularConfiguration(currentColumns)) {
toast.success(`Reached triangular configuration in ${stepCount} steps!`);
} else {
toast.error("Maximum steps reached without convergence");
}
};
const reset = () => {
const newBoxes: Box[] = [];
for (let i = 0; i < totalBoxes; i++) {
newBoxes.push({ id: i, columnIndex: null });
}
setBoxes(newBoxes);
setColumns(Array.from({ length: totalBoxes }, () => []));
setStep(0);
setIsComplete(false);
setIsPlaying(false);
};
const containerBoxes = boxes.filter(box => box.columnIndex === null);
return (
<div className="max-w-6xl mx-auto p-6 space-y-8">
<div className="text-center space-y-4">
<h1 className="text-4xl font-bold text-foreground">Bulgarian Solitaire</h1>
<p className="text-muted-foreground text-lg max-w-3xl mx-auto">
Choose a number n, then drag the {totalBoxes} boxes into columns.
Click "Play" to simulate the Bulgarian Solitaire process where one box is taken from each non-empty column to form a new column, continuing until reaching the triangular configuration (1, 2, 3, ..., n).
</p>
</div>
{/* Controls */}
<div className="flex items-center justify-center gap-8">
<div className="flex items-center gap-4">
<label className="text-sm font-medium">n = {n}</label>
<Slider
value={[n]}
onValueChange={(value) => setN(value[0])}
min={2}
max={6}
step={1}
className="w-32"
disabled={isPlaying}
/>
</div>
<Button onClick={reset} variant="outline" disabled={isPlaying}>
Reset
</Button>
</div>
{/* Container */}
<div className="flex justify-center">
<div className="border-2 border-dashed border-muted-foreground rounded-lg p-4 min-h-[120px] bg-muted/20">
<div className="text-center text-sm text-muted-foreground mb-2">Container</div>
<div className="flex flex-wrap gap-2 justify-center max-w-md">
{containerBoxes.map((box) => (
<div
key={box.id}
draggable={!isPlaying}
onDragStart={(e) => handleDragStart(e, box.id)}
className="w-8 h-8 bg-primary rounded cursor-move hover:bg-primary/80 transition-colors flex items-center justify-center text-primary-foreground text-xs font-medium"
>
{box.id + 1}
</div>
))}
</div>
</div>
</div>
{/* Columns */}
<div className="space-y-4">
<div className="text-center">
<h3 className="text-lg font-semibold">Columns</h3>
{step > 0 && (
<p className="text-sm text-muted-foreground">Step: {step}</p>
)}
</div>
<div className="grid grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2 max-w-4xl mx-auto">
{columns.map((column, index) => (
<div
key={index}
onDragOver={handleDragOver}
onDrop={(e) => handleDrop(e, index)}
className="border border-muted-foreground rounded-lg min-h-[100px] p-2 bg-background/50 flex flex-col-reverse gap-1"
>
<div className="text-xs text-center text-muted-foreground mb-2">
{index + 1}
</div>
{column.map((boxId, boxIndex) => (
<div
key={boxId}
onDoubleClick={() => handleDoubleClick(boxId)}
className="w-6 h-6 bg-primary rounded cursor-pointer hover:bg-primary/80 transition-colors flex items-center justify-center text-primary-foreground text-xs font-medium mx-auto"
title="Double-click to return to container"
>
{boxId + 1}
</div>
))}
</div>
))}
</div>
</div>
{/* Play Button */}
<div className="flex justify-center">
<Button
onClick={simulateBulgarianSolitaire}
disabled={isPlaying || containerBoxes.length > 0}
size="lg"
className="px-12"
>
{isPlaying ? 'Playing...' : 'Play'}
</Button>
</div>
{/* Status */}
{isComplete && (
<div className="text-center p-4 bg-success/10 border border-success/20 rounded-lg">
<h3 className="text-lg font-semibold text-success">Triangular Configuration Reached! 🎉</h3>
<p className="text-sm text-muted-foreground">
The Bulgarian Solitaire process converged to the stable triangular configuration in {step} steps.
</p>
</div>
)}
{/* Instructions */}
<div className="bg-muted/30 rounded-lg p-6 space-y-4">
<h3 className="text-lg font-semibold">How to Play:</h3>
<ul className="list-disc list-inside space-y-2 text-sm text-muted-foreground">
<li>Choose a value for n (2-6) using the slider</li>
<li>Drag the {totalBoxes} numbered boxes from the container into any of the columns</li>
<li>Double-click any box in a column to return it to the container</li>
<li>Once all boxes are placed in columns, click "Play" to start the simulation</li>
<li>Watch as the algorithm takes one box from each non-empty column to form a new column</li>
<li>The process continues until reaching the triangular configuration: columns of sizes 1, 2, 3, ..., n</li>
</ul>
</div>
{showSocialShare && (
<SocialShare
title="Bulgarian Solitaire - Interactive Mathematical Puzzle"
description={`Try this fascinating Bulgarian Solitaire puzzle! Watch as ${totalBoxes} boxes rearrange themselves into the perfect triangular configuration through mathematical iteration.`}
/>
)}
</div>
);
};
export default BulgarianSolitaire;

View file

@ -0,0 +1,29 @@
import BulgarianSolitaire from "@/components/BulgarianSolitaire";
import { useSearchParams } from "react-router-dom";
const BulgarianSolitairePage = () => {
const [searchParams] = useSearchParams();
const from = searchParams.get('from');
if (from === 'puzzles') {
return (
<div className="min-h-screen bg-background">
<div className="container mx-auto px-4 py-8 space-y-6">
<div className="flex items-center gap-4">
<button
onClick={() => window.location.href = '/themes/puzzles'}
className="text-primary hover:text-primary/80 font-medium"
>
Back to Puzzles
</button>
</div>
<BulgarianSolitaire showSocialShare={true} />
</div>
</div>
);
}
return <BulgarianSolitaire showSocialShare={true} />;
};
export default BulgarianSolitairePage;

View file

@ -16,6 +16,16 @@ const Puzzles = () => {
duration: "5-15 min", duration: "5-15 min",
participants: "1 player" participants: "1 player"
}, },
{
id: "bulgarian-solitaire",
title: "Bulgarian Solitaire",
description: "Explore this fascinating mathematical puzzle where boxes rearrange themselves into a triangular configuration through iterative processes.",
path: "/puzzles/bulgarian-solitaire",
tags: ["Mathematical", "Solitaire", "Algorithm", "Convergence"],
difficulty: "Intermediate" as const,
duration: "5-10 min",
participants: "1 player"
},
{ {
id: "sikinia-parliament", id: "sikinia-parliament",
title: "Parliament of Sikinia Puzzle", title: "Parliament of Sikinia Puzzle",