mastermind/web/app/single-player/page.js

79 lines
2.7 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import NumberFinder from './NumberFinder';
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
export default function SinglePlayerPage() {
const router = useRouter();
const [digitInput, setDigitInput] = useState('');
const [game, setGame] = useState(null); // {digitNumber, attempts}
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleStart = async () => {
const num = parseInt(digitInput, 10);
if (isNaN(num) || num <= 0) return;
setLoading(true);
setError('');
try {
const res = await fetch(
`${apiURL}/start?digitNumber=${num}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
}
);
if (!res.ok) throw new Error(`Sunucu hatası (HTTP ${res.status})`);
const data = await res.json();
if (typeof data.attempts !== 'number') throw new Error('Geçersiz yanıt');
setGame({ digitNumber: num, attempts: data.attempts });
} catch (err) {
setError(err.message);
console.error(err);
setTimeout(() => router.push('/'), 2500);
} finally {
setLoading(false);
}
};
return (
<main className="h-screen w-full flex flex-col relative">
<header className="p-3 sm:p-4 text-center text-2xl sm:text-3xl font-bold bg-neutral-800 shadow-lg">
Single Player Mode
</header>
{game ? (
<NumberFinder digitNumber={game.digitNumber} initialAttempts={game.attempts} />
) : (
<div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 px-2">
<div className="bg-neutral-800 rounded-xl p-4 sm:p-8 w-full max-w-xs sm:max-w-sm text-center">
<h2 className="text-lg sm:text-xl font-semibold mb-4">Digit Number [3-10]</h2>
<input
type="number"
className="w-full rounded p-2 bg-neutral-700 mb-4 focus:outline-none text-base sm:text-lg"
value={digitInput}
min={1}
onChange={(e) => setDigitInput(e.target.value)}
/>
<button
onClick={handleStart}
disabled={!digitInput || loading}
className="w-full py-2 rounded bg-blue-600 hover:bg-blue-700 disabled:opacity-40 text-base sm:text-lg"
>
{loading ? '...' : 'OK'}
</button>
{error && (
<p className="mt-4 text-rose-400 text-sm animate-pulse">{error}</p>
)}
</div>
</div>
)}
</main>
);
}