Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

'use client'; import React, { useEffect, useRef, useState } from 'react'; import {…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. User

    'use client';

    import React, { useEffect, useRef, useState } from 'react'; import { motion, useAnimation } from 'framer-motion'; import cardsData from '@/data/cardData.json'; import Image from 'next/image';

    const CARD_WIDTH = 100; const CARD_MARGIN = 10; const STEP = CARD_WIDTH + CARD_MARGIN; const VISIBLE_CARDS = 11; const BUFFER = 3;

    type Card = { id: number; img: string; chance: number };

    function pickWinnerCardIndex(cards: Card[]): number { const totalChance = cards.reduce((sum, card) => sum + card.chance, 0); const rand = Math.random() * totalChance;

    let accum = 0; for (let i = 0; i < cards.length; i++) { accum += cards[i].chance; if (rand <= accum) return i; }

    return cards.length - 1; // на випадок точності }

    export default function Roulette() { const controls = useAnimation();

    const [cards] = useState<Card[]>(cardsData.cards.map((card, i) => ({ ...card, id: i })));

    const [activeIndex, setActiveIndex] = useState<number | null>(null);

    // Подвійний масив для плавної циклічності const cardsToRender = [...cards, ...cards];

    const positionRef = useRef(0); const speedRef = useRef(0); const isRunningRef = useRef(false); const containerRef = useRef(null);

    const totalLength = cards.length * STEP;

    const centerNearestCard = async () => { if (!containerRef.current) return;

    const containerCenter = containerRef.current.offsetWidth / 2;
    let pos = positionRef.current % totalLength; // нормалізуємо позицію в межах одного циклу
    
    if (pos < 0) pos += totalLength; // якщо від'ємна, поправляємо
    
    // Позиції центрів карток в cardsToRender (подвійний масив)
    const cardCenters = cardsToRender.map((_, i) => i * STEP - pos + CARD_WIDTH / 2);
    
    let nearestIndex = 0;
    let minDistance = Infinity;
    
    for (let i = 0; i < cardCenters.length; i++) {
      const dist = Math.abs(cardCenters[i] - containerCenter);
      if (dist < minDistance) {
        minDistance = dist;
        nearestIndex = i;
      }
    }
    
    const desiredCenter = nearestIndex * STEP;
    const newPosition = desiredCenter - (containerCenter - CARD_WIDTH / 2);
    
    await controls.start({
      x: -newPosition,
      transition: { type: 'spring', stiffness: 120, damping: 20, mass: 1 },
    });
    
    positionRef.current = newPosition;
    
    setActiveIndex(nearestIndex);
    
    const winnerCard = cardsToRender[nearestIndex % cards.length];
    console.log('Фактична Виграшна картка:', winnerCard);
    
    setTimeout(() => setActiveIndex(null), 1500);
    

    };

    const accelerate = () => new Promise(res => { let start: number | null = null; const anim = (time: number) => { if (!start) start = time; const elapsed = (time - start) / 1000; speedRef.current = elapsed < 3 ? 2500 * (elapsed / 3) : 2500; if (elapsed < 3) requestAnimationFrame(anim); else res(); }; requestAnimationFrame(anim); });

    const decelerate = () => new Promise(res => { let start: number | null = null; const anim = (time: number) => { if (!start) start = time; const elapsed = (time - start) / 1000; speedRef.current = elapsed < 5 ? 1500 * (1 - elapsed / 5) : 0; if (elapsed < 5) requestAnimationFrame(anim); else { isRunningRef.current = false; res(); } }; requestAnimationFrame(anim); });

    const startLoop = async () => { isRunningRef.current = true;

    const winnerIndex = pickWinnerCardIndex(cards);
    console.log('Обрана виграшна картка:', cards[winnerIndex]);
    
    await accelerate();
    await new Promise(r => setTimeout(r, 2000));
    await decelerate();
    await centerNearestCard();
    await new Promise(r => setTimeout(r, 5000));
    startLoop();
    

    };

    useEffect(() => { let lastTimestamp: number | null = null;

    const animate = (timestamp: number) => {
      if (!lastTimestamp) lastTimestamp = timestamp;
      const delta = (timestamp - lastTimestamp) / 1000;
    
      if (isRunningRef.current) {
        positionRef.current += speedRef.current * delta;
    
        // Якщо позиція пройшла більше половини довжини (одного повного набору карт),
        // безшовно скидати позицію назад
        if (positionRef.current >= totalLength) {
          positionRef.current -= totalLength;
        }
    
        controls.set({ x: -positionRef.current });
      }
    
      lastTimestamp = timestamp;
      requestAnimationFrame(animate);
    };
    
    requestAnimationFrame(animate);
    startLoop();
    
    return () => {
      isRunningRef.current = false;
    };
    

    }, [controls]);

    return ( <div ref={containerRef} className="roulette-container mx-auto w-[1280px] relative overflow-hidden" style={{ height: 200, }} > <motion.div animate={controls} className="flex mt-[50px] gap-[10px]"> {cardsToRender.map((card, index) => ( <motion.div key={index} animate={{ scale: activeIndex === index ? 1.5 : 1 }} transition={{ type: 'spring', stiffness: 200, damping: 15 }} className="min-w-[100px] h-[100px] rounded-xl flex items-center justify-center shadow-[0_0_8px_#1c7ed6] select-none" > <Image src={card.img} alt={Card ${card.id}} width={100} height={100} className="w-[100px] h-[100px]" /> </motion.div> ))} </motion.div> ); } це рулетка. в нас є виграшна картка, необхідно щоб при кожному новому обертанні вибирадась вибрана картка і анімація обертання зупинялась на цій картці коли вона буде по центру контейнера

  2. Claude Assistant

    Проблема в тому, що ваша поточна логіка не враховує заздалегідь обрану виграшну картку при зупинці. Ось виправлений код:

    'use client';
    
    import React, { useEffect, useRef, useState } from 'react';
    import { motion, useAnimation } from 'framer-motion';
    import cardsData from '@/data/cardData.json';
    import Image from 'next/image';
    
    const CARD_WIDTH = 100;
    const CARD_MARGIN = 10;
    const STEP = CARD_WIDTH + CARD_MARGIN;
    const VISIBLE_CARDS = 11;
    const BUFFER = 3;
    
    type Card = { id: number; img: string; chance: number };
    
    function pickWinnerCardIndex(cards: Card[]): number {
      const totalChance = cards.reduce((sum, card) => sum + card.chance, 0);
      const rand = Math.random() * totalChance;
    
      let accum = 0;
      for (let i = 0; i < cards.length; i++) {
        accum += cards[i].chance;
        if (rand <= accum) return i;
      }
    
      return cards.length - 1;
    }
    
    export default function Roulette() {
      const controls = useAnimation();
    
      const [cards] = useState<Card[]>(cardsData.cards.map((card, i) => ({ ...card, id: i })));
      const [activeIndex, setActiveIndex] = useState<number | null>(null);
    
      const cardsToRender = [...cards, ...cards];
    
      const positionRef = useRef(0);
      const speedRef = useRef(0);
      const isRunningRef = useRef(false);
      const containerRef = useRef<HTMLDivElement>(null);
      const targetWinnerIndexRef = useRef<number | null>(null);
    
      const totalLength = cards.length * STEP;
    
      const centerWinnerCard = async (winnerIndex: number) => {
        if (!containerRef.current) return;
    
        const containerCenter = containerRef.current.offsetWidth / 2;
        
        // Знаходимо найближчу позицію виграшної картки в подвійному масиві
        let bestTargetIndex = winnerIndex;
        let bestDistance = Infinity;
        
        // Перевіряємо обидві позиції виграшної картки в подвійному масиві
        for (let offset = 0; offset < 2; offset++) {
          const candidateIndex = winnerIndex + offset * cards.length;
          const cardCenter = candidateIndex * STEP + CARD_WIDTH / 2;
          const currentPos = positionRef.current;
          const targetPos = cardCenter - (containerCenter - CARD_WIDTH / 2);
          const distance = Math.abs(targetPos - currentPos);
          
          if (distance < bestDistance) {
            bestDistance = distance;
            bestTargetIndex = candidateIndex;
          }
        }
    
        const targetCenter = bestTargetIndex * STEP + CARD_WIDTH / 2;
        const newPosition = targetCenter - (containerCenter - CARD_WIDTH / 2);
    
        await controls.start({
          x: -newPosition,
          transition: { type: 'spring', stiffness: 120, damping: 20, mass: 1 },
        });
    
        positionRef.current = newPosition;
        setActiveIndex(bestTargetIndex);
    
        const actualWinnerCard = cards[winnerIndex];
        console.log('Виграшна картка:', actualWinnerCard);
    
        setTimeout(() => setActiveIndex(null), 1500);
      };
    
      const accelerate = () =>
        new Promise<void>(res => {
          let start: number | null = null;
          const anim = (time: number) => {
            if (!start) start = time;
            const elapsed = (time - start) / 1000;
            speedRef.current = elapsed < 3 ? 2500 * (elapsed / 3) : 2500;
            if (elapsed < 3) requestAnimationFrame(anim);
            else res();
          };
          requestAnimationFrame(anim);
        });
    
      const decelerate = (targetWinnerIndex: number) =>
        new Promise<void>(res => {
          let start: number | null = null;
          const containerCenter = containerRef.current?.offsetWidth / 2 || 0;
          
          // Розраховуємо цільову позицію для виграшної картки
          let bestTargetIndex = targetWinnerIndex;
          let bestDistance = Infinity;
          
          for (let offset = 0; offset < 2; offset++) {
            const candidateIndex = targetWinnerIndex + offset * cards.length;
            const cardCenter = candidateIndex * STEP + CARD_WIDTH / 2;
            const targetPos = cardCenter - (containerCenter - CARD_WIDTH / 2);
            const currentPos = positionRef.current;
            const distance = Math.abs(targetPos - currentPos);
            
            if (distance < bestDistance) {
              bestDistance = distance;
              bestTargetIndex = candidateIndex;
            }
          }
          
          const targetCenter = bestTargetIndex * STEP + CARD_WIDTH / 2;
          const finalTargetPosition = targetCenter - (containerCenter - CARD_WIDTH / 2);
          
          const anim = (time: number) => {
            if (!start) start = time;
            const elapsed = (time - start) / 1000;
            const progress = Math.min(elapsed / 3, 1); // 3 секунди на уповільнення
            
            // Плавне уповільнення з наближенням до цільової позиції
            const easeOut = 1 - Math.pow(1 - progress, 3);
            const currentTargetPos = positionRef.current + (finalTargetPosition - positionRef.current) * easeOut;
            
            if (progress < 1) {
              speedRef.current = Math.max(0, 1500 * (1 - progress));
              requestAnimationFrame(anim);
            } else {
              speedRef.current = 0;
              isRunningRef.current = false;
              positionRef.current = finalTargetPosition;
              setActiveIndex(bestTargetIndex);
              res();
            }
          };
          requestAnimationFrame(anim);
        });
    
      const startLoop = async () => {
        isRunningRef.current = true;
        setActiveIndex(null);
    
        const winnerIndex = pickWinnerCardIndex(cards);
        targetWinnerIndexRef.current = winnerIndex;
        console.log('Обрана виграшна картка:', cards[winnerIndex]);
    
        await accelerate();
        await new Promise(r => setTimeout(r, 1000)); // Час на максимальній швидкості
        await decelerate(winnerIndex);
        
        // Фінальне центрування (якщо потрібно)
        await controls.start({
          x: -positionRef.current,
          transition: { type: 'spring', stiffness: 200, damping: 25, mass: 0.8 },
        });
    
        await new Promise(r => setTimeout(r, 3000)); // Пауза перед наступним обертанням
        startLoop();
      };
    
      useEffect(() => {
        let lastTimestamp: number | null = null;
    
        const animate = (timestamp: number) => {
          if (!lastTimestamp) lastTimestamp = timestamp;
          const delta = (timestamp - lastTimestamp) / 1000;
    
          if (isRunningRef.current && speedRef.current > 0) {
            positionRef.current += speedRef.current * delta;
    
            // Безшовний перехід
            if (positionRef.current >= totalLength) {
              positionRef.current -= totalLength;
            }
    
            controls.set({ x: -positionRef.current });
          }
    
          lastTimestamp = timestamp;
          requestAnimationFrame(animate);
        };
    
        requestAnimationFrame(animate);
        startLoop();
    
        return () => {
          isRunningRef.current = false;
        };
      }, [controls]);
    
      return (
        <div
          ref={containerRef}
          className="roulette-container mx-auto w-[1280px] relative overflow-hidden"
          style={{
            height: 200,
          }}
        >
          <motion.div animate={controls} className="flex mt-[50px] gap-[10px]">
            {cardsToRender.map((card, index) => (
              <motion.div
                key={index}
                animate={{ scale: activeIndex === index ? 1.5 : 1 }}
                transition={{ type: 'spring', stiffness: 200, damping: 15 }}
                className="min-w-[100px] h-[100px] rounded-xl flex items-center justify-center shadow-[0_0_8px_#1c7ed6] select-none"
              >
                <Image
                  src={card.img}
                  alt={`Card ${card.id}`}
                  width={100}
                  height={100}
                  className="w-[100px] h-[100px]"
                />
              </motion.div>
            ))}
          </motion.div>
        </div>
      );
    }
    

    Основні зміни:

    1. Додано targetWinnerIndexRef - зберігає індекс виграшної картки для поточного обертання

    2. Змінено функцію decelerate - тепер вона приймає індекс виграшної картки і розраховує точну позицію зупинки так, щоб виграшна картка опинилась по центру

    3. Видалено centerNearestCard - замість неї логіка центрування виграшної картки інтегрована в decelerate

    4. Покращено розрахунок цільової позиції - враховується подвійний масив карток і вибирається найближча позиція виграшної картки

    Тепер рулетка буде гарантовано зупинятися на заздалегідь обраній виграшній картці, розміщуючи її точно по центру контейнера.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.