Add Neighbor Sum Avoidance interactive

This commit is contained in:
gpt-engineer-app[bot] 2025-09-30 19:14:06 +00:00
parent e398e1e267
commit 10fec3a3f6
4 changed files with 495 additions and 5 deletions

View file

@ -0,0 +1,373 @@
import { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Timer, RotateCcw } from 'lucide-react';
import confetti from 'canvas-confetti';
import { toast } from 'sonner';
import SocialShare from '@/components/SocialShare';
interface NeighborSumAvoidanceProps {
showSocialShare?: boolean;
}
const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceProps) => {
const [mode, setMode] = useState<'default' | 'guided'>('default');
const [isActive, setIsActive] = useState(false);
const [slots, setSlots] = useState<(number | null)[]>(Array(9).fill(null));
const [availableNumbers, setAvailableNumbers] = useState<number[]>([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const [draggedNumber, setDraggedNumber] = useState<number | null>(null);
const [draggedFrom, setDraggedFrom] = useState<number | null>(null);
const [draggedSlot, setDraggedSlot] = useState<number | null>(null);
const [time, setTime] = useState(0);
const [swaps, setSwaps] = useState(0);
const [isComplete, setIsComplete] = useState(false);
const timerRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (isActive && !isComplete) {
timerRef.current = setInterval(() => {
setTime(t => t + 1);
}, 1000);
} else if (timerRef.current) {
clearInterval(timerRef.current);
}
return () => {
if (timerRef.current) clearInterval(timerRef.current);
};
}, [isActive, isComplete]);
const isDivisible = (a: number, b: number) => {
const sum = a + b;
return sum % 3 === 0 || sum % 5 === 0 || sum % 7 === 0;
};
const getViolations = () => {
const violations: number[] = [];
for (let i = 0; i < 9; i++) {
const current = slots[i];
const next = slots[(i + 1) % 9];
if (current !== null && next !== null && isDivisible(current, next)) {
violations.push(i);
}
}
return violations;
};
const checkWin = () => {
if (slots.every(s => s !== null) && getViolations().length === 0) {
setIsComplete(true);
confetti({
particleCount: 100,
spread: 70,
origin: { y: 0.6 }
});
toast.success(`Congratulations! Completed in ${formatTime(time)}${mode === 'guided' ? ` with ${swaps} swaps` : ''}!`);
}
};
useEffect(() => {
if (isActive) {
checkWin();
}
}, [slots, isActive]);
const formatTime = (seconds: number) => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs.toString().padStart(2, '0')}`;
};
const startGame = (selectedMode: 'default' | 'guided') => {
setMode(selectedMode);
setIsActive(true);
setTime(0);
setSwaps(0);
setIsComplete(false);
if (selectedMode === 'default') {
setSlots(Array(9).fill(null));
setAvailableNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9]);
} else {
// Guided mode: random arrangement
const shuffled = [...Array(9)].map((_, i) => i + 1).sort(() => Math.random() - 0.5);
setSlots(shuffled);
setAvailableNumbers([]);
}
};
const restart = () => {
setIsActive(false);
setIsComplete(false);
setSlots(Array(9).fill(null));
setAvailableNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9]);
setTime(0);
setSwaps(0);
};
const handleDragStart = (num: number, fromSlot: number | null) => {
setDraggedNumber(num);
setDraggedFrom(fromSlot);
};
const handleDrop = (toSlot: number) => {
if (draggedNumber === null) return;
if (mode === 'default') {
// Default mode: place number in slot
const newSlots = [...slots];
newSlots[toSlot] = draggedNumber;
setSlots(newSlots);
setAvailableNumbers(availableNumbers.filter(n => n !== draggedNumber));
} else {
// Guided mode: swap numbers
if (draggedFrom !== null && draggedFrom !== toSlot) {
const newSlots = [...slots];
const temp = newSlots[toSlot];
newSlots[toSlot] = newSlots[draggedFrom];
newSlots[draggedFrom] = temp;
setSlots(newSlots);
setSwaps(s => s + 1);
}
}
setDraggedNumber(null);
setDraggedFrom(null);
};
const handleSlotClick = (slotIndex: number) => {
if (mode === 'default') {
// Remove from slot in default mode
if (slots[slotIndex] !== null) {
setAvailableNumbers([...availableNumbers, slots[slotIndex]!].sort((a, b) => a - b));
const newSlots = [...slots];
newSlots[slotIndex] = null;
setSlots(newSlots);
}
} else if (mode === 'guided') {
// Swap in guided mode
if (draggedSlot === null) {
setDraggedSlot(slotIndex);
} else if (draggedSlot !== slotIndex) {
const newSlots = [...slots];
const temp = newSlots[slotIndex];
newSlots[slotIndex] = newSlots[draggedSlot];
newSlots[draggedSlot] = temp;
setSlots(newSlots);
setSwaps(s => s + 1);
setDraggedSlot(null);
} else {
setDraggedSlot(null);
}
}
};
const renderCircle = () => {
const radius = 150;
const centerX = 200;
const centerY = 200;
const violations = getViolations();
return (
<svg width="400" height="400" className="mx-auto">
{/* Draw circle */}
<circle cx={centerX} cy={centerY} r={radius} fill="none" stroke="hsl(var(--border))" strokeWidth="2" />
{/* Draw violation arcs */}
{violations.map(i => {
const angle1 = (i * 360 / 9 - 90) * Math.PI / 180;
const angle2 = ((i + 1) * 360 / 9 - 90) * Math.PI / 180;
const x1 = centerX + radius * Math.cos(angle1);
const y1 = centerY + radius * Math.sin(angle1);
const x2 = centerX + radius * Math.cos(angle2);
const y2 = centerY + radius * Math.sin(angle2);
return (
<path
key={i}
d={`M ${x1} ${y1} A ${radius} ${radius} 0 0 1 ${x2} ${y2}`}
fill="none"
stroke="hsl(var(--destructive))"
strokeWidth="4"
/>
);
})}
{/* Draw edges in guided mode */}
{mode === 'guided' && slots.every(s => s !== null) && slots.map((num1, i) => {
return slots.slice(i + 1).map((num2, j) => {
const idx2 = i + j + 1;
if (num1 !== null && num2 !== null && !isDivisible(num1, num2)) {
const angle1 = (i * 360 / 9 - 90) * Math.PI / 180;
const angle2 = (idx2 * 360 / 9 - 90) * Math.PI / 180;
const x1 = centerX + radius * Math.cos(angle1);
const y1 = centerY + radius * Math.sin(angle1);
const x2 = centerX + radius * Math.cos(angle2);
const y2 = centerY + radius * Math.sin(angle2);
// Check if this forms part of the cycle (adjacent positions on circle)
const isAdjacentOnCircle = Math.abs(i - idx2) === 1 || Math.abs(i - idx2) === 8;
return (
<line
key={`${i}-${idx2}`}
x1={x1}
y1={y1}
x2={x2}
y2={y2}
stroke={isAdjacentOnCircle ? "hsl(var(--primary))" : "hsl(var(--muted-foreground))"}
strokeWidth={isAdjacentOnCircle ? "2" : "1"}
opacity={isAdjacentOnCircle ? "0.8" : "0.3"}
/>
);
}
return null;
});
})}
{/* Draw slots */}
{slots.map((num, i) => {
const angle = (i * 360 / 9 - 90) * Math.PI / 180;
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
const isSelected = mode === 'guided' && draggedSlot === i;
return (
<g key={i}>
<circle
cx={x}
cy={y}
r="25"
fill={isSelected ? "hsl(var(--primary))" : "hsl(var(--background))"}
stroke={isSelected ? "hsl(var(--primary))" : "hsl(var(--border))"}
strokeWidth="2"
onDragOver={(e) => e.preventDefault()}
onDrop={() => handleDrop(i)}
onClick={() => handleSlotClick(i)}
className="cursor-pointer"
/>
{num !== null && (
<text
x={x}
y={y}
textAnchor="middle"
dominantBaseline="middle"
className="text-xl font-bold select-none pointer-events-none"
fill={isSelected ? "hsl(var(--primary-foreground))" : "hsl(var(--foreground))"}
>
{num}
</text>
)}
</g>
);
})}
</svg>
);
};
return (
<div className="container mx-auto px-4 py-8">
<Card>
<CardHeader>
<CardTitle>Neighbor Sum Avoidance</CardTitle>
<CardDescription>
Can you arrange the numbers 1-9 in a circle so that the sum of two neighbors is never divisible by 3, 5, or 7?
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{!isActive ? (
<div className="space-y-6">
<div className="flex items-center justify-center gap-4">
<Label htmlFor="mode-switch">Default Mode</Label>
<Switch
id="mode-switch"
checked={mode === 'guided'}
onCheckedChange={(checked) => setMode(checked ? 'guided' : 'default')}
/>
<Label htmlFor="mode-switch">Guided Mode</Label>
</div>
<div className="space-y-4 text-center">
<div className="text-sm text-muted-foreground space-y-2">
{mode === 'default' ? (
<>
<p>Drag numbers from below into the circle slots.</p>
<p>Adjacent numbers that sum to a multiple of 3, 5, or 7 will show a red arc.</p>
<p>Click a filled slot to remove the number.</p>
</>
) : (
<>
<p>Numbers are connected by edges if their sum is NOT divisible by 3, 5, or 7.</p>
<p>Click two slots to swap their numbers and form a cycle on the circle's edge.</p>
</>
)}
</div>
<Button onClick={() => startGame(mode)} size="lg">
Start {mode === 'default' ? 'Default' : 'Guided'} Mode
</Button>
</div>
</div>
) : (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Timer className="w-4 h-4" />
<span className="font-mono">{formatTime(time)}</span>
</div>
{mode === 'guided' && (
<div className="text-sm text-muted-foreground">
Swaps: {swaps}
</div>
)}
<Button variant="outline" size="sm" onClick={restart}>
<RotateCcw className="w-4 h-4 mr-2" />
Restart
</Button>
</div>
{renderCircle()}
{mode === 'default' && availableNumbers.length > 0 && (
<div className="flex flex-wrap justify-center gap-4">
{availableNumbers.map(num => (
<div
key={num}
draggable
onDragStart={() => handleDragStart(num, null)}
className="w-12 h-12 rounded-full border-2 border-primary bg-background flex items-center justify-center text-lg font-bold cursor-move hover:scale-110 transition-transform"
>
{num}
</div>
))}
</div>
)}
{isComplete && (
<div className="text-center space-y-4">
<p className="text-lg font-semibold text-primary">
🎉 Congratulations! You solved it in {formatTime(time)}
{mode === 'guided' && ` with ${swaps} swaps`}!
</p>
<Button onClick={restart}>Play Again</Button>
</div>
)}
</div>
)}
</CardContent>
</Card>
{showSocialShare && (
<div className="mt-8">
<SocialShare
url={window.location.href}
title="Neighbor Sum Avoidance - Interactive Graph Puzzle"
description="Can you arrange numbers 1-9 in a circle avoiding forbidden sums?"
/>
</div>
)}
</div>
);
};
export default NeighborSumAvoidance;