fix: games physics

This commit is contained in:
Pc
2025-12-30 19:33:28 +01:00
parent bca5fc03a8
commit 502543d6ac
2 changed files with 124 additions and 116 deletions

View File

@@ -2,9 +2,14 @@
import { ArrowLeft, Trophy, Sparkles } from 'lucide-react';
import { DetailedKitty } from './DetailedKitty';
const GAP_SIZE = 170; // Przerwa między drapakami
// --- STAŁE KONFIGURACYJNE (Wartości na sekundę) ---
const GAP_SIZE = 170;
const PIPE_WIDTH = 70;
const PIPE_SPAWN_RATE = 1500; // Nowy drapak co 1.5 sekundy
const PIPE_SPEED = 250; // px/s
const PIPE_SPAWN_RATE = 1.5; // Sekundy
const GRAVITY = 1600; // px/s^2
const FLAP_STRENGTH = -450; // px/s
const CANVAS_HEIGHT = 450;
export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
const [isPlaying, setIsPlaying] = useState(false);
@@ -15,20 +20,28 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
return saved ? parseInt(saved, 10) : 0;
});
// Stany pozycji do renderowania
const [displayKittyY, setDisplayKittyY] = useState(150);
const [displayPipes, setDisplayPipes] = useState<{ x: number; topHeight: number; id: number }[]>([]);
const [rotation, setRotation] = useState(0);
// Referencje do fizyki (obliczenia poza Reactem dla płynności)
// Referencje do fizyki i czasu
const kittyYRef = useRef(150);
const velocityRef = useRef(0);
const pipesRef = useRef<{ x: number; topHeight: number; id: number }[]>([]);
const pipesRef = useRef<{ x: number; topHeight: number; id: number; passed?: boolean }[]>([]);
const scoreRef = useRef(0);
const requestRef = useRef<number>(0);
const lastTimeRef = useRef<number>(0);
const spawnTimerRef = useRef<number>(0);
const GRAVITY = 0.35;
const JUMP_STRENGTH = -7;
const endGame = useCallback(() => {
setGameOver(true);
setIsPlaying(false);
const currentHS = parseInt(localStorage.getItem('flappyKittyHighScore') || '0', 10);
if (scoreRef.current > currentHS) {
setHighScore(scoreRef.current);
localStorage.setItem('flappyKittyHighScore', scoreRef.current.toString());
}
}, []);
const startGame = useCallback(() => {
setIsPlaying(true);
@@ -38,90 +51,92 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
kittyYRef.current = 150;
velocityRef.current = 0;
pipesRef.current = [];
spawnTimerRef.current = 0;
lastTimeRef.current = performance.now();
setDisplayKittyY(150);
setDisplayPipes([]);
}, []);
const flap = useCallback(() => {
if (isPlaying && !gameOver) {
velocityRef.current = JUMP_STRENGTH;
velocityRef.current = FLAP_STRENGTH;
}
}, [isPlaying, gameOver]);
useEffect(() => {
const update = () => {
const update = (currentTime: number) => {
if (gameOver || !isPlaying) return;
// 1. Fizyka lotu
velocityRef.current += GRAVITY;
kittyYRef.current += velocityRef.current;
// 1. Obliczanie Delta Time
const dt = (currentTime - lastTimeRef.current) / 1000;
lastTimeRef.current = currentTime;
// Obrót kota zależnie od prędkości
setRotation(Math.min(Math.max(velocityRef.current * 4, -20), 90));
// Zabezpieczenie przed "skokami" przy lagach (max 100ms)
const frameTime = Math.min(dt, 0.1);
// 2. Kolizja z sufitem i podłogą
if (kittyYRef.current > 380 || kittyYRef.current < -50) {
// 2. Fizyka Kota
velocityRef.current += GRAVITY * frameTime;
kittyYRef.current += velocityRef.current * frameTime;
// Wizualny obrót (od -20 stopni przy locie w górę do 90 przy spadaniu)
const targetRotation = Math.min(Math.max(velocityRef.current * 0.15, -20), 90);
setRotation(targetRotation);
// 3. Kolizja z granicami ekranu
if (kittyYRef.current > CANVAS_HEIGHT - 40 || kittyYRef.current < -20) {
endGame();
return;
}
// 3. Ruch drapaków (rur)
pipesRef.current = pipesRef.current
.map(p => ({ ...p, x: p.x - 4 })) // Prędkość rur
.filter(p => p.x > -100);
// 4. Zarządzanie Rurami (Spawning)
spawnTimerRef.current += frameTime;
if (spawnTimerRef.current >= PIPE_SPAWN_RATE) {
const topHeight = Math.random() * (220 - 70) + 70;
pipesRef.current.push({ x: 650, topHeight, id: Date.now() });
spawnTimerRef.current = 0;
}
// 4. Wykrywanie kolizji z drapakami
pipesRef.current.forEach(p => {
// Kot jest na stałej pozycji X (ok. 50-100px)
if (p.x < 110 && p.x + PIPE_WIDTH > 40) {
// Sprawdzanie czy kot uderzył w górny lub dolny drapak
if (kittyYRef.current < p.topHeight || kittyYRef.current > p.topHeight + GAP_SIZE - 40) {
// 5. Ruch rur i Kolizje
const updatedPipes = [];
for (let p of pipesRef.current) {
p.x -= PIPE_SPEED * frameTime;
// Sprawdzanie kolizji
// Kitty X jest stałe na ok. 50-90px. Kot ma szerokość ok. 40px w uproszczeniu kolizyjnym.
if (p.x < 100 && p.x + PIPE_WIDTH > 50) {
if (kittyYRef.current < p.topHeight || kittyYRef.current > p.topHeight + GAP_SIZE - 45) {
endGame();
return;
}
}
// Dodawanie punktów
if (p.x < 40 && !p.hasOwnProperty('passed')) {
(p as any).passed = true;
// Punktacja
if (p.x < 50 && !p.passed) {
p.passed = true;
scoreRef.current += 1;
setScore(scoreRef.current);
}
});
// 5. Synchronizacja z widokiem
// Usuwanie rur poza ekranem
if (p.x > -PIPE_WIDTH) {
updatedPipes.push(p);
}
}
pipesRef.current = updatedPipes;
// 6. Sync UI
setDisplayKittyY(kittyYRef.current);
setDisplayPipes([...pipesRef.current]);
requestRef.current = requestAnimationFrame(update);
};
const endGame = () => {
setGameOver(true);
setIsPlaying(false);
const currentHS = parseInt(localStorage.getItem('flappyKittyHighScore') || '0', 10);
if (scoreRef.current > currentHS) {
setHighScore(scoreRef.current);
localStorage.setItem('flappyKittyHighScore', scoreRef.current.toString());
}
};
if (isPlaying && !gameOver) {
requestRef.current = requestAnimationFrame(update);
}
return () => cancelAnimationFrame(requestRef.current);
}, [isPlaying, gameOver]);
}, [isPlaying, gameOver, endGame]);
// Generator nowych drapaków
useEffect(() => {
if (!isPlaying || gameOver) return;
const interval = setInterval(() => {
const topHeight = Math.random() * (220 - 50) + 50;
pipesRef.current.push({ x: 650, topHeight, id: Date.now() });
}, PIPE_SPAWN_RATE);
return () => clearInterval(interval);
}, [isPlaying, gameOver]);
// Obsługa klawiszy
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.code === 'Space') {
@@ -134,65 +149,55 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
}, [isPlaying, gameOver, startGame, flap]);
return (
<div className="flex flex-col items-center justify-center min-h-[75vh] p-4">
<div className="flex flex-col items-center justify-center min-h-[75vh] p-4 font-sans">
<button onClick={onBack} className="mb-6 flex items-center gap-2 text-pink-500 font-bold hover:scale-105 transition-all outline-none">
<ArrowLeft size={20} /> Back to Menu
</button>
{/* OKNO GRY */}
<div
className="relative w-full max-w-[600px] h-[450px] bg-sky-100 rounded-[3rem] shadow-2xl border-4 border-white overflow-hidden cursor-pointer select-none"
onClick={() => { if (!isPlaying || gameOver) startGame(); else flap(); }}
>
{/* Dekoracje tła */}
<div className="absolute top-10 left-10 text-white/40"><Sparkles size={40} /></div>
<div className="absolute top-40 right-20 text-white/30"><Sparkles size={60} /></div>
{/* Punkty */}
<div className="absolute top-6 right-8 text-right z-30 font-black">
<div className="text-pink-500 text-4xl drop-shadow-sm">Score: {score}</div>
<div className="text-pink-300 text-sm flex items-center justify-end gap-1"><Trophy size={14} /> Record: {highScore}</div>
<div className="text-pink-300 text-sm flex items-center justify-end gap-1">
<Trophy size={14} /> Record: {highScore}
</div>
</div>
{/* KOTEK */}
<div
className="absolute left-10 z-20 transition-transform duration-75"
className="absolute left-10 z-20"
style={{
top: `${displayKittyY}px`,
transform: `rotate(${rotation}deg)`
transform: `rotate(${rotation}deg)`,
transition: 'transform 0.1s ease-out' // Lekkie wygładzenie obrotu
}}
>
<DetailedKitty isJumping={true} isNight={false} isGameOver={gameOver} />
</div>
{/* DRAPAKI (Rury) */}
{/* DRAPAKI */}
{displayPipes.map(p => (
<React.Fragment key={p.id}>
{/* Górny Drapak */}
<div
className="absolute bg-[#e5c29f] border-x-4 border-b-8 border-[#d4ac87] rounded-b-3xl shadow-sm"
style={{ left: p.x, top: 0, width: PIPE_WIDTH, height: p.topHeight }}
>
<div className="absolute bottom-4 w-full h-2 bg-white/20" />
<div className="absolute bottom-8 w-full h-2 bg-white/20" />
</div>
{/* Dolny Drapak */}
/>
<div
className="absolute bg-[#e5c29f] border-x-4 border-t-8 border-[#d4ac87] rounded-t-3xl shadow-sm"
style={{ left: p.x, top: p.topHeight + GAP_SIZE, width: PIPE_WIDTH, height: 450 - (p.topHeight + GAP_SIZE) }}
>
<div className="absolute top-4 w-full h-2 bg-white/20" />
<div className="absolute top-8 w-full h-2 bg-white/20" />
</div>
style={{ left: p.x, top: p.topHeight + GAP_SIZE, width: PIPE_WIDTH, height: CANVAS_HEIGHT - (p.topHeight + GAP_SIZE) }}
/>
</React.Fragment>
))}
{/* Ekran Startowy */}
{/* Ekrany informacyjne */}
{!isPlaying && !gameOver && (
<div className="absolute inset-0 bg-white/40 backdrop-blur-sm flex items-center justify-center z-40">
<div className="bg-white p-10 rounded-[3rem] shadow-2xl text-center border-4 border-pink-100 max-w-xs w-full">
<p className="text-3xl font-black text-pink-500 mb-6 tracking-tighter">Flappy Cat 🎈</p>
<button className="bg-pink-500 text-white px-10 py-4 rounded-2xl font-black animate-bounce shadow-lg shadow-pink-200 text-xl">
<button className="bg-pink-500 text-white px-10 py-4 rounded-2xl font-black animate-bounce shadow-lg text-xl">
MEOW TO FLY
</button>
<p className="text-pink-300 text-xs mt-4 font-bold uppercase">Click or Space</p>
@@ -200,12 +205,11 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
</div>
)}
{/* Ekran Koniec Gry */}
{gameOver && (
<div className="absolute inset-0 bg-pink-50/90 backdrop-blur-md flex flex-col items-center justify-center z-40">
<h3 className="text-5xl font-black text-pink-600 mb-2">Oops! 😿</h3>
<p className="font-bold text-3xl text-pink-400 mb-8">Score: {score}</p>
<button className="bg-pink-500 text-white px-12 py-4 rounded-2xl font-black text-xl shadow-xl hover:scale-110 transition-all active:scale-95">
<button className="bg-pink-500 text-white px-12 py-4 rounded-2xl font-black text-xl shadow-xl hover:scale-110 transition-all">
TRY AGAIN
</button>
</div>