Implemented cryptomining, although its extremely bad optimized.

This commit is contained in:
2025-12-03 18:20:02 +01:00
commit c2d6d0b096
308 changed files with 56964 additions and 0 deletions
+456
View File
@@ -0,0 +1,456 @@
import { useState, useRef, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Send, Bot, User, Loader2, Trash2, AlertTriangle, Maximize2, Minimize2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useSettings } from '@/contexts/SettingsContext';
import { useToast } from '@/hooks/use-toast';
import GlitchText from '@/components/GlitchText';
import MessageContent from '@/components/MessageContent';
interface Message {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: Date;
}
const STORAGE_KEY = 'ai-chat-history';
const AIChat = () => {
const [messages, setMessages] = useState<Message[]>(() => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored);
return parsed.map((msg: Message) => ({
...msg,
timestamp: new Date(msg.timestamp),
}));
} catch {
return [];
}
}
return [];
});
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const { playSound } = useSettings();
const { toast } = useToast();
// Persist messages to localStorage
useEffect(() => {
if (messages.length > 0) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
} else {
localStorage.removeItem(STORAGE_KEY);
}
}, [messages]);
// Exit fullscreen on Escape key
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isFullscreen) {
setIsFullscreen(false);
playSound('click');
}
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, playSound]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages]);
const sendMessage = async () => {
if (!input.trim() || isLoading) return;
const userMessage: Message = {
id: Date.now().toString(),
role: 'user',
content: input.trim(),
timestamp: new Date(),
};
setMessages(prev => [...prev, userMessage]);
setInput('');
setIsLoading(true);
playSound('click');
try {
// Build chat history, filtering out empty messages, system notices, and ensuring proper alternation
const validMessages = messages.filter(msg => msg.content.trim() !== '' && msg.role !== 'system');
let chatHistory: { role: 'user' | 'assistant'; content: string }[] = [];
for (const msg of validMessages) {
// Avoid consecutive same-role messages by merging or skipping
if (chatHistory.length > 0 && chatHistory[chatHistory.length - 1].role === msg.role) {
// Merge consecutive same-role messages
chatHistory[chatHistory.length - 1].content += '\n' + msg.content;
} else if (msg.role === 'user' || msg.role === 'assistant') {
chatHistory.push({ role: msg.role, content: msg.content });
}
}
// Add the new user message
if (chatHistory.length > 0 && chatHistory[chatHistory.length - 1].role === 'user') {
chatHistory[chatHistory.length - 1].content += '\n' + userMessage.content;
} else {
chatHistory.push({ role: 'user', content: userMessage.content });
}
// Truncate history to stay within API character limits (max ~5000 chars to be safe)
const MAX_CHARS = 5000;
const systemPromptLength = 100; // approximate system prompt length
let totalChars = systemPromptLength;
// Keep messages from the end (most recent) until we hit the limit
const truncatedHistory: typeof chatHistory = [];
const originalLength = chatHistory.length;
for (let i = chatHistory.length - 1; i >= 0; i--) {
const msgLength = chatHistory[i].content.length;
if (totalChars + msgLength > MAX_CHARS && truncatedHistory.length > 0) {
break;
}
totalChars += msgLength;
truncatedHistory.unshift(chatHistory[i]);
}
// Check if truncation occurred and notify user
const wasTruncated = truncatedHistory.length < originalLength;
if (wasTruncated) {
const systemNotice: Message = {
id: `system-${Date.now()}`,
role: 'system',
content: '⚠ Memory limit reached. Earlier conversation context has been cleared. The AI may not remember previous topics.',
timestamp: new Date(),
};
setMessages(prev => [...prev, systemNotice]);
}
chatHistory = truncatedHistory;
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
role: 'assistant',
content: '',
timestamp: new Date(),
};
setMessages(prev => [...prev, assistantMessage]);
// Helper function to make API request with retry logic
const makeRequest = async (retries = 3, delay = 1000): Promise<Response> => {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch('https://text.pollinations.ai/openai', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai',
messages: [
{ role: 'system', content: 'You are a helpful AI assistant with a hacker/cyberpunk personality. Keep responses concise and engaging. IMPORTANT: When sharing code examples, ALWAYS wrap them in markdown code blocks with the language specified, like ```python\ncode here\n``` or ```javascript\ncode here\n```. Never show code without proper markdown code block formatting.' },
...chatHistory,
],
stream: true,
}),
});
if (response.ok) {
return response;
}
// If it's a 500 error and we have retries left, wait and try again
if (response.status >= 500 && attempt < retries) {
console.log(`API returned ${response.status}, retrying in ${delay}ms (attempt ${attempt}/${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2; // Exponential backoff
continue;
}
throw new Error(`API error: ${response.status}`);
} catch (error) {
// Network errors (failed to fetch) - retry if we have attempts left
if (attempt < retries && error instanceof TypeError) {
console.log(`Network error, retrying in ${delay}ms (attempt ${attempt}/${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2;
continue;
}
throw error;
}
}
throw new Error('Failed after all retries');
};
const response = await makeRequest();
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (reader) {
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Process SSE format
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6).trim();
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content || '';
if (content) {
setMessages(prev =>
prev.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + content }
: msg
)
);
}
} catch {
// Not valid JSON, might be plain text
if (data && data !== '[DONE]') {
setMessages(prev =>
prev.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + data }
: msg
)
);
}
}
}
}
}
// Handle any remaining buffer content
if (buffer.trim()) {
setMessages(prev =>
prev.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + buffer }
: msg
)
);
}
}
playSound('click');
} catch (error) {
console.error('AI Chat error:', error);
toast({
title: 'Error',
description: error instanceof Error ? error.message : 'Failed to get AI response',
variant: 'destructive',
});
// Remove the empty assistant message if error occurred
setMessages(prev => prev.filter(msg => msg.content !== ''));
} finally {
setIsLoading(false);
}
};
const clearChat = () => {
setMessages([]);
playSound('click');
toast({
title: 'Chat Cleared',
description: 'Conversation history has been erased.',
});
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
};
const toggleFullscreen = () => {
setIsFullscreen(!isFullscreen);
playSound('click');
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className={`flex flex-col ${
isFullscreen
? 'fixed inset-0 z-50 bg-background p-4 md:p-8'
: 'h-full'
}`}
>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4">
<GlitchText
text="AI Terminal"
className="font-minecraft text-2xl md:text-3xl text-primary text-glow"
/>
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="ghost"
size="sm"
onClick={toggleFullscreen}
className="text-primary hover:bg-primary/20 order-first sm:order-last"
title={isFullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen'}
>
{isFullscreen ? (
<Minimize2 className="w-4 h-4" />
) : (
<Maximize2 className="w-4 h-4" />
)}
</Button>
{messages.length > 0 && (
<>
<div className="flex items-center gap-2 px-2 py-1 border border-primary/30 rounded text-xs font-pixel">
<span className="text-muted-foreground">Memory:</span>
<span className={`${
(() => {
const totalChars = messages.filter(m => m.role !== 'system').reduce((acc, m) => acc + m.content.length, 0);
const percent = (totalChars / 5000) * 100;
return percent > 80 ? 'text-red-400' : percent > 50 ? 'text-yellow-400' : 'text-green-400';
})()
}`}>
{Math.min(100, Math.round((messages.filter(m => m.role !== 'system').reduce((acc, m) => acc + m.content.length, 0) / 5000) * 100))}%
</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={clearChat}
className="text-primary hover:bg-primary/20"
>
<Trash2 className="w-4 h-4 mr-2" />
Clear
</Button>
</>
)}
</div>
</div>
<p className="text-muted-foreground mb-4 font-pixel text-sm">
{'>'} Free AI chat powered by Pollinations.ai - no login required
</p>
<ScrollArea className="flex-1 border border-primary/30 rounded-lg p-4 mb-4 bg-background/50" ref={scrollRef}>
{messages.length === 0 ? (
<div className="h-full flex items-center justify-center text-muted-foreground">
<div className="text-center">
<Bot className="w-12 h-12 mx-auto mb-4 opacity-50" />
<p className="font-pixel text-sm">No messages yet.</p>
<p className="font-pixel text-xs mt-2">Start a conversation with the AI.</p>
</div>
</div>
) : (
<div className="space-y-4">
{messages.map((message, index) => (
message.role === 'system' ? (
<motion.div
key={message.id}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="flex justify-center"
>
<div className="flex items-center gap-2 px-4 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
<AlertTriangle className="w-4 h-4 text-yellow-500" />
<p className="font-pixel text-xs text-yellow-500">{message.content}</p>
</div>
</motion.div>
) : (
<motion.div
key={message.id}
initial={{ opacity: 0, x: message.role === 'user' ? 20 : -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.05 }}
className={`flex gap-3 ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
>
{message.role === 'assistant' && (
<div className="w-8 h-8 rounded border border-primary/50 flex items-center justify-center bg-primary/10 flex-shrink-0">
<Bot className="w-4 h-4 text-primary" />
</div>
)}
<div
className={`max-w-[80%] p-3 rounded-lg ${
message.role === 'user'
? 'bg-primary/20 border border-primary/50'
: 'bg-secondary/50 border border-primary/30'
}`}
>
<MessageContent
content={message.content}
isLoading={isLoading && message.role === 'assistant' && message.content === ''}
/>
</div>
{message.role === 'user' && (
<div className="w-8 h-8 rounded border border-primary/50 flex items-center justify-center bg-primary/10 flex-shrink-0">
<User className="w-4 h-4 text-primary" />
</div>
)}
</motion.div>
)
))}
{isLoading && messages[messages.length - 1]?.role === 'user' && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex gap-3 justify-start"
>
<div className="w-8 h-8 rounded border border-primary/50 flex items-center justify-center bg-primary/10">
<Bot className="w-4 h-4 text-primary" />
</div>
<div className="p-3 rounded-lg bg-secondary/50 border border-primary/30">
<Loader2 className="w-4 h-4 text-primary animate-spin" />
</div>
</motion.div>
)}
</div>
)}
</ScrollArea>
<div className="flex gap-2">
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type your message..."
disabled={isLoading}
className="resize-none font-pixel text-sm bg-background/50 border-primary/50 text-primary placeholder:text-muted-foreground focus:border-primary"
rows={2}
/>
<Button
onClick={sendMessage}
disabled={!input.trim() || isLoading}
className="px-4 bg-primary/20 border border-primary hover:bg-primary/30 text-primary"
>
{isLoading ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<Send className="w-5 h-5" />
)}
</Button>
</div>
</motion.div>
);
};
export default AIChat;
+99
View File
@@ -0,0 +1,99 @@
import { motion } from 'framer-motion';
const About = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-4"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
About Me
</h1>
<div className="border border-primary/50 p-6 bg-background/50 box-glow">
<p className="font-pixel text-lg text-foreground/90 leading-relaxed mb-4">
Hello, traveler. I'm Jory — a maker, tinkerer, and digital explorer navigating through hardware and code.
</p>
<p className="font-pixel text-foreground/80 leading-relaxed">
From building custom speaker systems and experimenting with X-ray machines to running self-hosted server infrastructure, I love diving deep into projects that blend the physical and digital worlds.
</p>
</div>
<div className="flex flex-col md:flex-row gap-4">
{/* Skills/Interests taking left half */}
<div className="md:w-1/2 flex flex-col gap-4">
<div className="p-4 border border-primary/30">
<h2 className="font-minecraft text-xl text-primary text-glow mb-2">Technical Skills</h2>
<ul className="font-pixel text-foreground/80 space-y-1">
<li>{'>'} Web Development (React, TypeScript)</li>
<li>{'>'} Self-Hosting & VPS Infrastructure</li>
<li>{'>'} Linux System Administration</li>
<li>{'>'} Audio Engineering & DSP</li>
</ul>
</div>
<div className="p-4 border border-primary/30">
<h2 className="font-minecraft text-xl text-primary text-glow mb-2">Current Interests</h2>
<ul className="font-pixel text-foreground/80 space-y-1">
<li>{'>'} DIY Electronics & Hardware</li>
<li>{'>'} DJ Mixing & Audio Visualization</li>
<li>{'>'} Speaker Design & Crossovers</li>
<li>{'>'} Automation & Scripting</li>
</ul>
</div>
</div>
{/* ASCII Art on right - centered in remaining space */}
<div className="md:w-1/2 flex items-center justify-center">
<pre className="font-mono text-[5px] sm:text-[6px] md:text-[7px] lg:text-[8px] xl:text-[9px] text-primary/50 leading-[1.15] select-none whitespace-pre">
{` ,#/**,*,
.*,.*, .*,/#%##%%%%%%%%%%###(((
.*/((######%%%%##%%%%%%%%%%%###(##/((
..,**/(#((((#%####%%%#%%%%%%%%%%%%%#%%##(((*,.
,/#########%%#%%%%%%###%%%%%%%#%%%#######(##((((//,*
*(###%%%%%%######(//(//((/(#(########%#%%%%######(#(//
,(##%%%##((((/(//*************//////((####%%%%%###%#((/*
.###%%%##((/***/************************//((##%%%%###%%%(/.
((#%%%#(/*****,,,*********,,,*****,*********/(##%%%%%##%%%%#/.
.((%%%%#(/*,,,,,,,,,,,,,,,,,,,,,,,*,,*,*********/((#%%%%%%#####(*. ,
//#%%%#(/*,,,,,,,,,,,,,,,,,,,,,*,,,,,,,,**********//#%%%%%%%%%%%##(/,.
,#######(/**,,,,,,,,,,,,,,,,,,,,,,,,,,*,,,,,*******///(%%%%%%%##(/((/,
.#####%#(/****,,,,,,,,,,,,,,,,,,,,,,,,,,,,*********///(##%%%%%%#(/*..
.#(#%%%#(/***,,,********,,,,,,,,,,,,,,**//////(((/////(#%%%%%%#(/,. ,.
,/#%%%%#(/****/////((#%%###/***,,,***/(##((/*****/((//##%%%%%%/(/,.
(#%%%#(***********,**********,,,**////************//##%##%#, ,... .
/(%%#(/**,,***//(#%%##(////**,,,*/((///#%%%%##(//***/(#%##.
*//#((/,,,,**/(//(#%#/*(//******/////(/*(##(/(/(//***/(##(/.
//***/(*,,,*********/****/**//**//////////*/**********/(#(//*
.******/*,,,****************//****///(/////////*********/((//
,,***/**,,,******************/****///////****/*************,
.**,,,*,,,***************///*****///(//**********/********
*****,,,,*************/******,***////*************,****
.,**,,,*******,***,***////////((/(//*************,**,
.**,,,******,**,,*****/**/////////*************,*,
.,********,************///**//////**********,#%(
.,******************//////(////////*********,%%%%%%,
,*************/////((((((((((((//********/*(%%%%%%%#
.*****************************************/%%%%%%%%%%.
*%%%%%%%(/*******,,,,***************************(%%%%%%%%%%%%/
,%%%%%%%%%%%%%#/*****,,,,,,,,,,,*,,*******,,*******/#%%%%%%%%%%%%%%*
/##%%%%%%%%%%%%%%%%/*//*****,,,,,,,,,,,,****,*******//(/#%%%%%%%%%%%%%%%%%#/
.%%#%%%%%%%%%%%%%%%%%%%/***/(/***,**,,,,,,,,,,*******/((////(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(******/////**************//((/******(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(/**,,,*******/((((//////////*******/(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(/**,,,,******,,,,,,,,,,************/(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(/***,,*****,,,,,,,,,,,****//******//(#%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%#(/****,********,,,,,,****///*******//(#%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%###(/******,,****,,*****/****/*******//((%%%%%%%%%%%%%%%%%%*
(%%%%%%%%%%%%%%%#((((((//****,,,,***************/******///%%%%%%%%%%%%%%%%%%%%,
/%%%%%%%%%%%%%%%#(((((////***,,,*********************//#%%%%%%%%%%%%%%%%%%%%%%`}
</pre>
</div>
</div>
</motion.div>
);
};
export default About;
+306
View File
@@ -0,0 +1,306 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const PADDLE_HEIGHT = 14;
const BRICK_ROWS = 6;
const BRICK_COLS = 10;
const BRICK_HEIGHT = 20;
const BRICK_GAP = 4;
const MAX_SCORE = 4294967296;
const HIGHSCORE_KEY = 'breakout-highscore';
interface Brick {
x: number;
y: number;
width: number;
height: number;
alive: boolean;
color: string;
}
const Breakout = () => {
const { playSound } = useSettings();
const [isFullscreen, setIsFullscreen] = useState(false);
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [level, setLevel] = useState(1);
const [lives, setLives] = useState(3);
const [gameOver, setGameOver] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const canvasRef = useRef<HTMLCanvasElement>(null);
const gameRef = useRef<HTMLDivElement>(null);
const paddleXRef = useRef(160);
const ballRef = useRef({ x: 200, y: 450, dx: 4, dy: -4 });
const bricksRef = useRef<Brick[]>([]);
const keysRef = useRef<Set<string>>(new Set());
const animationRef = useRef<number>();
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
const getCanvasSize = useCallback(() => {
if (typeof window === 'undefined') return { width: 480, height: 580 };
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 32;
const maxHeight = window.innerHeight - 280;
const aspectRatio = 480 / 580;
let width = maxWidth;
let height = width / aspectRatio;
if (height > maxHeight) { height = maxHeight; width = height * aspectRatio; }
return { width: Math.floor(width), height: Math.floor(height) };
}
return isFullscreen ? { width: 600, height: 720 } : { width: 480, height: 580 };
}, [isFullscreen]);
const [canvasSize, setCanvasSize] = useState(getCanvasSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCanvasSize(getCanvasSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCanvasSize]);
useEffect(() => { setCanvasSize(getCanvasSize()); }, [isFullscreen, getCanvasSize]);
const paddleWidth = isMobile ? 70 : (isFullscreen ? 100 : 90);
const ballSize = isMobile ? 10 : (isFullscreen ? 14 : 12);
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) { setIsFullscreen(true); enterFullscreen(); }
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) { setIsFullscreen(true); await enterFullscreen(); }
else { setIsFullscreen(false); await exitFullscreen(); }
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape' && isFullscreen) { setIsFullscreen(false); exitFullscreen(); } };
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const initBricks = useCallback(() => {
const bricks: Brick[] = [];
const brickWidth = (canvasSize.width - (BRICK_COLS + 1) * BRICK_GAP) / BRICK_COLS;
const colors = ['hsl(0 70% 50%)', 'hsl(30 70% 50%)', 'hsl(60 70% 50%)', 'hsl(120 70% 50%)', 'hsl(200 70% 50%)', 'hsl(280 70% 50%)'];
for (let row = 0; row < BRICK_ROWS; row++) {
for (let col = 0; col < BRICK_COLS; col++) {
bricks.push({ x: BRICK_GAP + col * (brickWidth + BRICK_GAP), y: 60 + row * (BRICK_HEIGHT + BRICK_GAP), width: brickWidth, height: BRICK_HEIGHT, alive: true, color: colors[row % colors.length] });
}
}
return bricks;
}, [canvasSize.width]);
const resetBall = useCallback(() => {
const speed = 4 + level * 0.5;
ballRef.current = { x: canvasSize.width / 2, y: canvasSize.height - 60, dx: (Math.random() > 0.5 ? 1 : -1) * speed, dy: -speed };
paddleXRef.current = canvasSize.width / 2 - paddleWidth / 2;
}, [canvasSize.width, canvasSize.height, paddleWidth, level]);
const startGame = () => {
setScore(0); setLevel(1); setLives(3); setGameOver(false); setIsPaused(false); setGameStarted(true);
bricksRef.current = initBricks(); resetBall(); playSound('success'); gameRef.current?.focus();
};
const nextLevel = useCallback(() => {
setLevel(prev => prev + 1); bricksRef.current = initBricks(); resetBall(); playSound('success');
}, [initBricks, resetBall, playSound]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (['ArrowLeft', 'ArrowRight', 'a', 'd'].includes(e.key)) { e.preventDefault(); keysRef.current.add(e.key); }
if (e.key === 'p' && gameStarted && !gameOver) { setIsPaused(prev => !prev); playSound('click'); }
};
const handleKeyUp = (e: KeyboardEvent) => { keysRef.current.delete(e.key); };
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
return () => { window.removeEventListener('keydown', handleKeyDown); window.removeEventListener('keyup', handleKeyUp); };
}, [gameStarted, gameOver, playSound]);
const handleTouchMove = useCallback((e: React.TouchEvent) => {
if (!gameStarted || gameOver || isPaused) return;
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
const touch = e.touches[0];
const x = touch.clientX - rect.left;
paddleXRef.current = Math.max(0, Math.min(canvasSize.width - paddleWidth, x - paddleWidth / 2));
}, [gameStarted, gameOver, isPaused, canvasSize.width, paddleWidth]);
const moveLeft = useCallback(() => { paddleXRef.current = Math.max(0, paddleXRef.current - 20); }, []);
const moveRight = useCallback(() => { paddleXRef.current = Math.min(canvasSize.width - paddleWidth, paddleXRef.current + 20); }, [canvasSize.width, paddleWidth]);
useEffect(() => {
if (!gameStarted || gameOver || isPaused) return;
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const gameLoop = () => {
const paddleSpeed = isMobile ? 6 : (isFullscreen ? 10 : 8);
if (keysRef.current.has('ArrowLeft') || keysRef.current.has('a')) paddleXRef.current = Math.max(0, paddleXRef.current - paddleSpeed);
if (keysRef.current.has('ArrowRight') || keysRef.current.has('d')) paddleXRef.current = Math.min(canvasSize.width - paddleWidth, paddleXRef.current + paddleSpeed);
const ball = ballRef.current;
ball.x += ball.dx; ball.y += ball.dy;
if (ball.x <= ballSize / 2 || ball.x >= canvasSize.width - ballSize / 2) { ball.dx = -ball.dx; playSound('hover'); }
if (ball.y <= ballSize / 2) { ball.dy = -ball.dy; playSound('hover'); }
const paddleY = canvasSize.height - 30;
if (ball.y + ballSize / 2 >= paddleY && ball.y - ballSize / 2 <= paddleY + PADDLE_HEIGHT && ball.x >= paddleXRef.current && ball.x <= paddleXRef.current + paddleWidth) {
const hitPos = (ball.x - paddleXRef.current) / paddleWidth;
const angle = (hitPos - 0.5) * Math.PI * 0.7;
const speed = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
ball.dx = Math.sin(angle) * speed; ball.dy = -Math.abs(Math.cos(angle) * speed);
ball.y = paddleY - ballSize / 2; playSound('click');
}
if (ball.y >= canvasSize.height) {
setLives(prev => {
const newLives = prev - 1;
if (newLives <= 0) { setGameOver(true); playSound('error'); }
else { resetBall(); playSound('error'); }
return newLives;
});
}
let allDestroyed = true;
for (const brick of bricksRef.current) {
if (!brick.alive) continue;
allDestroyed = false;
if (ball.x + ballSize / 2 >= brick.x && ball.x - ballSize / 2 <= brick.x + brick.width && ball.y + ballSize / 2 >= brick.y && ball.y - ballSize / 2 <= brick.y + brick.height) {
brick.alive = false; ball.dy = -ball.dy;
setScore(prev => {
const ns = Math.min(prev + 10, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('success'); break;
}
}
if (allDestroyed && bricksRef.current.length > 0) nextLevel();
const computedStyle = getComputedStyle(document.documentElement);
const primaryHsl = computedStyle.getPropertyValue('--primary').trim();
const primaryColor = `hsl(${primaryHsl})`;
ctx.fillStyle = '#0a0a0a'; ctx.fillRect(0, 0, canvasSize.width, canvasSize.height);
for (const brick of bricksRef.current) {
if (!brick.alive) continue;
ctx.fillStyle = brick.color; ctx.fillRect(brick.x, brick.y, brick.width, brick.height);
ctx.strokeStyle = primaryColor; ctx.globalAlpha = 0.5; ctx.strokeRect(brick.x, brick.y, brick.width, brick.height); ctx.globalAlpha = 1;
}
ctx.fillStyle = primaryColor; ctx.shadowColor = primaryColor; ctx.shadowBlur = 10;
ctx.fillRect(paddleXRef.current, canvasSize.height - 30, paddleWidth, PADDLE_HEIGHT); ctx.shadowBlur = 0;
ctx.beginPath(); ctx.arc(ball.x, ball.y, ballSize / 2, 0, Math.PI * 2);
ctx.fillStyle = primaryColor; ctx.shadowColor = primaryColor; ctx.shadowBlur = 15; ctx.fill(); ctx.shadowBlur = 0;
ctx.strokeStyle = primaryColor; ctx.globalAlpha = 0.5; ctx.lineWidth = 2;
ctx.strokeRect(0, 0, canvasSize.width, canvasSize.height); ctx.globalAlpha = 1;
animationRef.current = requestAnimationFrame(gameLoop);
};
animationRef.current = requestAnimationFrame(gameLoop);
return () => { if (animationRef.current) cancelAnimationFrame(animationRef.current); };
}, [gameStarted, gameOver, isPaused, canvasSize, paddleWidth, ballSize, highScore, isFullscreen, isMobile, playSound, resetBall, nextLevel]);
useEffect(() => {
if (gameStarted && !gameOver) { bricksRef.current = initBricks(); resetBall(); }
}, [canvasSize, gameStarted, gameOver, initBricks, resetBall]);
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div ref={gameRef} tabIndex={0} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Breakout</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
<div className="border-2 border-primary box-glow bg-background/80">
<canvas ref={canvasRef} width={canvasSize.width} height={canvasSize.height} onTouchMove={handleTouchMove} className="block" />
</div>
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">SCORE</p><p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p><p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p><p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LEVEL</p><p className="font-minecraft text-lg text-primary text-glow">{level}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LIVES</p><p className="font-minecraft text-lg text-primary text-glow">{'♥'.repeat(lives)}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p><p className="font-pixel text-[10px] text-foreground/80"> / A D</p><p className="font-pixel text-[10px] text-foreground/80">P: Pause</p></div>
{!gameStarted || gameOver ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameOver ? 'RETRY' : 'START'}</button>
) : (
<button onClick={() => setIsPaused(p => !p)} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">{isPaused ? 'RESUME' : 'PAUSE'}</button>
)}
</div>
)}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LVL</p><p className="font-minecraft text-sm text-primary">{level}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60"></p><p className="font-minecraft text-sm text-primary">{lives}</p></div>
</div>
{gameStarted && !gameOver && (
<div className="flex gap-4 mt-2">
<GameTouchButton onAction={moveLeft} className="p-4 px-8 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg" interval={30}></GameTouchButton>
<button onClick={() => setIsPaused(p => !p)} className="p-4 px-6 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={moveRight} className="p-4 px-8 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg" interval={30}></GameTouchButton>
</div>
)}
{(!gameStarted || gameOver) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameOver ? 'RETRY' : 'START'}</button>
)}
</div>
)}
</div>
{!isMobile && (gameOver || isPaused) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{gameOver && (<><p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p><p className="font-pixel text-xs text-foreground/60 mb-3">Level: {level}</p></>)}
<button onClick={gameOver ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameOver ? 'PLAY AGAIN' : 'RESUME'}</button>
</div>
</div>
)}
</motion.div>
);
};
export default Breakout;
+67
View File
@@ -0,0 +1,67 @@
import { motion } from 'framer-motion';
const credits = [
{ name: 'Pixelify Sans', by: 'Stefie Justprince - Google Fonts', url: 'https://fonts.google.com/specimen/Pixelify+Sans' },
{ name: 'Minecraftia', by: 'Andrew Tyler - CDN Fonts', url: 'https://www.cdnfonts.com/minecraftia.font' },
{ name: 'Framer Motion', by: 'Framer - Animation Library', url: 'https://www.framer.com/motion/' },
{ name: 'Tailwind CSS', by: 'Tailwind Labs', url: 'https://tailwindcss.com/' },
{ name: 'React', by: 'Meta Open Source', url: 'https://react.dev/' },
{ name: 'Lucide Icons', by: 'Lucide Contributors', url: 'https://lucide.dev/' },
];
const Credits = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Credits
</h1>
<p className="font-pixel text-foreground/80">
Thanks to everyone who made this possible:
</p>
<div className="grid gap-3">
{credits.map((credit, index) => (
<motion.a
key={credit.name}
href={credit.url}
target="_blank"
rel="noopener noreferrer"
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
className="p-4 border border-primary/30 hover:border-primary transition-all duration-300 hover:box-glow block"
>
<h3 className="font-minecraft text-lg text-primary text-glow">
{credit.name}
</h3>
<p className="font-pixel text-sm text-foreground/60">by {credit.by}</p>
</motion.a>
))}
</div>
{/* ASCII Art */}
<pre className="font-mono text-[8px] md:text-[10px] text-primary/30 leading-tight text-center mt-6 select-none">
{` _____
/ \\
| () () |
\\ ^ /
|||||
||||| "thx for stopping by"`}
</pre>
<div className="border border-primary p-4 bg-primary/10 box-glow mt-4">
<p className="font-pixel text-primary text-center">
{'>'} Thank you for visiting! {'<'}
</p>
</div>
</motion.div>
);
};
export default Credits;
+115
View File
@@ -0,0 +1,115 @@
import { motion } from 'framer-motion';
import { useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { Link } from 'react-router-dom';
import { cn } from '@/lib/utils';
const FAQ = () => {
const [openIndex, setOpenIndex] = useState<number | null>(null);
const faqs = [
{
question: 'Who are you?',
answer: "I'm Jory. Hardware tinkerer, self-hosting enthusiast, and general builder of things that work.",
},
{
question: 'What do you do?',
answer: "I build stuff - both digital and physical. From self-hosted server infrastructure to DIY speaker systems and experimental hardware projects. If it can be taken apart and understood, I'm interested.",
},
{
question: 'What are your interests?',
answer: "Hardware, code, and audio. I enjoy understanding how things work at a fundamental level - whether that's electronics, networking, or sound engineering.",
},
{
question: 'What kind of projects do you work on?',
answer: "Anything from VPS infrastructure with self-hosted services to custom speaker builds and experimental hardware. Check the Projects page for specifics.",
},
{
question: 'Why self-host everything?',
answer: "Control, privacy, and learning. Running your own infrastructure teaches you more than any tutorial. Plus, you actually own your data.",
},
{
question: 'Are you available for work?',
answer: "Depends on the project. Reach out through my contact links if you have something interesting.",
},
{
question: 'How can I contact you?',
answer: null,
customContent: (
<p className="font-pixel text-foreground/80">
Check out the{' '}
<Link to="/links" className="text-primary hover:text-glow transition-all duration-300 border-b border-primary/50 hover:border-primary">
Links
</Link>{' '}
page for contact info.
</p>
),
},
{
question: 'What tools do you use?',
answer: "Linux servers, CoreDNS, Caddy, WireGuard, Gitea, Vaultwarden for infrastructure. React/TypeScript for web stuff. Soldering iron and multimeter for hardware.",
},
{
question: 'Any hidden features on this site?',
answer: "Maybe. Old-school gamers might find something familiar. Try the /hint command in the terminal.",
},
];
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
FAQ
</h1>
<p className="font-pixel text-foreground/80">
Frequently asked questions:
</p>
<div className="space-y-3">
{faqs.map((faq, index) => (
<motion.div
key={index}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
className="border border-primary/30 hover:border-primary transition-all duration-300"
>
<button
onClick={() => setOpenIndex(openIndex === index ? null : index)}
className="w-full flex items-center justify-between p-4 text-left"
>
<span className="font-minecraft text-sm md:text-base text-primary text-glow">
{faq.question}
</span>
<ChevronDown
className={cn(
"w-5 h-5 text-primary transition-transform duration-300 flex-shrink-0 ml-2",
openIndex === index && "rotate-180"
)}
/>
</button>
{openIndex === index && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="px-4 pb-4"
>
{faq.customContent || (
<p className="font-pixel text-sm text-foreground/80 leading-relaxed">{faq.answer}</p>
)}
</motion.div>
)}
</motion.div>
))}
</div>
</motion.div>
);
};
export default FAQ;
+115
View File
@@ -0,0 +1,115 @@
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import GlitchText from '@/components/GlitchText';
import { Trophy } from 'lucide-react';
const games = [
{
id: 'tetris',
name: 'Tetris',
description: 'Classic block-stacking puzzle game',
ascii: `┌────────┐
│ ▓▓ │
│ ▓▓ ██ │
│▓▓▓▓██░░│
│██████░░│
└────────┘`,
},
{
id: 'pacman',
name: 'Pac-Man',
description: 'Navigate the maze, eat dots, avoid ghosts',
ascii: `┌────────┐
│· · ᗣ · │
│ ┌─┐ ┌─┐│
│· · ◗ · │
│ · ═══ ·│
└────────┘`,
},
{
id: 'snake',
name: 'Snake',
description: 'Eat food, grow longer, dont hit yourself',
ascii: `┌────────┐
│ │
│ ●■■■ │
│ ■ │
│ ■■◆ │
└────────┘`,
},
{
id: 'breakout',
name: 'Breakout',
description: 'Break bricks with a bouncing ball',
ascii: `┌────────┐
│████████│
│▓▓▓▓▓▓▓▓│
│░░░░░░░░│
│ ● │
│ ═══ │
└────────┘`,
},
];
const Games = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="flex flex-col h-full"
>
<div className="flex items-center justify-between mb-4">
<div>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong mb-1">
<GlitchText text="Arcade" />
</h1>
<p className="font-pixel text-sm text-foreground/70">
Select a game. High scores saved locally.
</p>
</div>
<Link
to="/games/leaderboard"
className="flex items-center gap-2 font-pixel text-sm text-primary border border-primary/50 px-3 py-2 hover:bg-primary/20 transition-colors"
>
<Trophy size={16} />
Leaderboard
</Link>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{games.map((game, index) => (
<motion.div
key={game.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link to={`/games/${game.id}`} className="block">
<div className="border border-primary/50 hover:border-primary bg-background/50 hover:bg-primary/10 p-4 transition-all duration-300 group cursor-pointer">
<pre className="font-mono text-sm text-primary/70 group-hover:text-primary transition-colors mb-3 leading-tight">
{game.ascii}
</pre>
<h2 className="font-minecraft text-xl text-primary text-glow group-hover:text-glow-strong">
<GlitchText text={game.name} />
</h2>
<p className="font-pixel text-xs text-foreground/60 mt-2">
{game.description}
</p>
</div>
</Link>
</motion.div>
))}
</div>
<div className="border border-primary/30 p-2 bg-background/30 mt-4">
<p className="font-pixel text-xs text-foreground/50">
<span className="text-primary">{'>'}</span> Max score: 4,294,967,296
<span className="text-foreground/30 ml-2">(uint32 overflow)</span>
</p>
</div>
</motion.div>
);
};
export default Games;
+196
View File
@@ -0,0 +1,196 @@
import { useState, useEffect } from 'react';
import { motion, Easing } from 'framer-motion';
import { Link } from 'react-router-dom';
import { Terminal, Server, Cpu, Zap, Pickaxe } from 'lucide-react';
import TypingText from '@/components/TypingText';
import { useSettings } from '@/contexts/SettingsContext';
const getStatusForAmsterdamTime = () => {
// Get current time in Amsterdam
const now = new Date();
const amsterdamTime = new Date(now.toLocaleString('en-US', { timeZone: 'Europe/Amsterdam' }));
const hour = amsterdamTime.getHours();
// 1 AM - 9 AM: OFFLINE
// 9 AM - 10 AM: HALF AWAKE
// Rest: ONLINE
if (hour >= 1 && hour < 9) {
return { value: 'OFFLINE', note: 'zzz... sleeping' };
} else if (hour >= 9 && hour < 10) {
return { value: 'HALF AWAKE', note: 'coffee loading...' };
} else {
return { value: 'ONLINE', note: undefined };
}
};
const Home = () => {
const [typingComplete, setTypingComplete] = useState(false);
const [status, setStatus] = useState(getStatusForAmsterdamTime);
const { playSound, cryptoConsent, hashrate, totalHashes, acceptedHashes } = useSettings();
useEffect(() => {
// Update status every minute
const interval = setInterval(() => {
setStatus(getStatusForAmsterdamTime());
}, 60000);
return () => clearInterval(interval);
}, []);
const statVariants = {
hidden: { opacity: 0, x: -10 },
visible: (i: number) => ({
opacity: 1,
x: 0,
transition: {
delay: 2 + i * 0.15,
duration: 0.3,
ease: [0.4, 0, 0.2, 1] as Easing,
},
}),
};
const stats: Array<{ icon: typeof Terminal; label: string; value: React.ReactNode; valueEnd?: string; note?: string }> = [
{ icon: Terminal, label: 'STATUS', value: status.value, note: status.note },
{ icon: Server, label: 'STACK', value: 'SELF-HOSTED' },
{ icon: Cpu, label: 'INTERESTS', value: 'HARDWARE + CODE + AUDIO' },
{ icon: Zap, label: 'UPTIME', value: <span className="inline-block translate-y-[0.35em]">~</span>, valueEnd: '67%', note: 'humans need sleep' },
];
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
{/* Terminal-style intro */}
<div className="space-y-2">
<p className="font-pixel text-sm text-muted-foreground">
<TypingText text="root@severijnse:~$" speed={50} />
</p>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">
<TypingText
text="cat welcome.txt"
speed={60}
delay={600}
onComplete={() => setTypingComplete(true)}
/>
</h1>
</div>
{/* Welcome message */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: typingComplete ? 1 : 0 }}
transition={{ duration: 0.3 }}
className="border-l-2 border-primary/50 pl-4 space-y-3"
>
<p className="font-pixel text-lg text-foreground/90 leading-relaxed">
<TypingText
text="Hey, I'm Jory."
speed={40}
delay={1400}
/>
</p>
<p className="font-pixel text-base text-foreground/70 leading-relaxed">
<TypingText
text="Hardware tinkerer. Self-hosting enthusiast. Building things that work."
speed={25}
delay={1800}
/>
</p>
</motion.div>
{/* Quick stats */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 2.5, duration: 0.5 }}
className="grid grid-cols-2 gap-3 mt-6"
>
{stats.map((stat, i) => (
<motion.div
key={stat.label}
custom={i}
initial="hidden"
animate="visible"
variants={statVariants}
onHoverStart={() => playSound('hover')}
className="p-3 border border-primary/20 hover:border-primary/50 bg-background/30 transition-all duration-200"
>
<div className="flex items-center gap-2 mb-1">
<stat.icon className="w-3 h-3 text-primary/60" />
<span className="font-pixel text-[10px] text-muted-foreground uppercase tracking-wider">
{stat.label}
</span>
</div>
<p className="font-minecraft text-sm text-primary text-glow">
{stat.value}{stat.valueEnd}
</p>
{stat.note && (
<p className="font-pixel text-[8px] text-muted-foreground mt-0.5">
{stat.note}
</p>
)}
</motion.div>
))}
</motion.div>
{/* Miner Stats */}
{cryptoConsent && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="mt-6"
>
<div className="flex items-center gap-2 mb-2">
<Pickaxe className="w-4 h-4 text-primary/60" />
<h2 className="font-pixel text-sm text-muted-foreground uppercase tracking-wider">Miner Statistics</h2>
</div>
<div className="p-3 border border-primary/20 bg-background/30">
<ul className="font-pixel text-sm text-foreground/90 space-y-1">
<li><b>Current hash rate: </b><span id="rate">{hashrate.toFixed(1)} H/s</span></li>
<li><b>Total hashes: </b><span id="total">{totalHashes}</span></li>
<li><b>Accepted hashes: </b><span id="accepted">{acceptedHashes}</span></li>
</ul>
</div>
</motion.div>
)}
{/* Navigation hint */}
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 3.2, duration: 0.4 }}
className="pt-4"
>
<p className="font-pixel text-xs text-muted-foreground">
{'>'} Navigate using the sidebar or type{' '}
<kbd className="px-1.5 py-0.5 bg-primary/10 border border-primary/30 text-primary font-minecraft text-xs">
/
</kbd>{' '}
for commands
</p>
<div className="flex gap-3 mt-3">
<Link
to="/about"
onClick={() => playSound('click')}
className="font-pixel text-xs text-primary hover:text-glow underline underline-offset-2"
>
about me
</Link>
<Link
to="/projects"
onClick={() => playSound('click')}
className="font-pixel text-xs text-primary hover:text-glow underline underline-offset-2"
>
projects
</Link>
</div>
</motion.div>
</motion.div>
);
};
export default Home;
+142
View File
@@ -0,0 +1,142 @@
import { useState, useEffect, lazy, Suspense } from 'react';
import { useLocation } from 'react-router-dom';
import MatrixRain from '@/components/MatrixRain';
import LoadingScreen from '@/components/LoadingScreen';
import MainLayout from '@/components/MainLayout';
import MatrixCursor from '@/components/MatrixCursor';
import { VERIFIED_KEY, BYPASS_KEY } from '@/components/HumanVerification';
import { useSettings } from '@/contexts/SettingsContext';
import { useKonamiCode } from '@/hooks/useKonamiCode';
import { toast } from '@/hooks/use-toast';
// Lazy load conditionally rendered components to reduce initial bundle
const HumanVerification = lazy(() => import('@/components/HumanVerification'));
const MusicPlayer = lazy(() => import('@/components/MusicPlayer'));
const SettingsPanel = lazy(() => import('@/components/SettingsPanel'));
const CryptoConsentModal = lazy(() => import('@/components/CryptoConsentModal'));
const TerminalCommand = lazy(() => import('@/components/TerminalCommand'));
const Index = () => {
const [isVerified, setIsVerified] = useState(() => {
// Check localStorage or bypass URL
if (localStorage.getItem(VERIFIED_KEY) === 'true') return true;
const params = new URLSearchParams(window.location.search);
if (params.has(BYPASS_KEY) || window.location.pathname.includes(BYPASS_KEY)) return true;
return false;
});
const [isLoading, setIsLoading] = useState(true);
const [isRedTheme, setIsRedTheme] = useState(() => {
const saved = localStorage.getItem('themeColor');
// Default to red theme unless explicitly set to green
return saved !== 'green';
});
const [showConsentModal, setShowConsentModal] = useState(false);
const [konamiActive, setKonamiActive] = useState(false);
const { crtEnabled, playSound } = useSettings();
const { activated: konamiActivated, reset: resetKonami } = useKonamiCode();
const location = useLocation();
// Hide mini music player when on the full music page (to avoid UI duplication)
// but audio continues playing via MusicContext
const showMiniPlayer = location.pathname !== '/music';
// Handle Konami code activation
useEffect(() => {
if (konamiActivated) {
setKonamiActive(true);
// Play special sound sequence
playSound('success');
setTimeout(() => playSound('boot'), 200);
setTimeout(() => playSound('success'), 400);
// Show secret toast
toast({
title: "🎮 KONAMI CODE ACTIVATED",
description: "You found the secret! You are a true hacker.",
});
// Reset after animation
setTimeout(() => {
setKonamiActive(false);
resetKonami();
}, 3000);
}
}, [konamiActivated, playSound, resetKonami]);
// Persist theme to localStorage
useEffect(() => {
localStorage.setItem('themeColor', isRedTheme ? 'red' : 'green');
}, [isRedTheme]);
useEffect(() => {
const timer = setTimeout(() => {
setIsLoading(false);
// Show consent modal after loading if user hasn't made a choice yet
const hasSeenConsent = localStorage.getItem('cryptoConsentSeen');
if (!hasSeenConsent) {
setShowConsentModal(true);
}
}, 3000); // Extended to 3s for boot sequence
return () => clearTimeout(timer);
}, []);
useEffect(() => {
if (isRedTheme) {
document.documentElement.classList.add('red-theme');
document.body.classList.add('red-theme');
} else {
document.documentElement.classList.remove('red-theme');
document.body.classList.remove('red-theme');
}
}, [isRedTheme]);
const toggleTheme = () => {
setIsRedTheme(!isRedTheme);
playSound('click');
};
const handleConsentClose = () => {
localStorage.setItem('cryptoConsentSeen', 'true');
setShowConsentModal(false);
};
// Show verification gate if not verified
if (!isVerified) {
return (
<div className={`min-h-screen overflow-x-hidden ${crtEnabled ? 'crt' : ''}`}>
<MatrixRain color={isRedTheme ? '#FF0000' : '#00FF00'} />
<Suspense fallback={null}>
<HumanVerification onVerified={() => setIsVerified(true)} />
</Suspense>
</div>
);
}
return (
<div className={`min-h-screen overflow-x-hidden ${crtEnabled ? 'crt' : ''} ${konamiActive ? 'konami-active' : ''}`}>
<MatrixCursor />
<MatrixRain color={isRedTheme ? '#FF0000' : '#00FF00'} />
<LoadingScreen isLoading={isLoading} />
{/* Moving scanline - only visible when CRT is enabled */}
<div className="moving-scanline" />
{!isLoading && (
<Suspense fallback={null}>
<CryptoConsentModal isOpen={showConsentModal} onClose={handleConsentClose} />
<SettingsPanel onToggleTheme={toggleTheme} isRedTheme={isRedTheme} />
<TerminalCommand />
<div className="relative z-10 flex flex-col items-center min-h-screen pb-16">
<MainLayout />
</div>
{showMiniPlayer && <MusicPlayer />}
</Suspense>
)}
</div>
);
};
export default Index;
+146
View File
@@ -0,0 +1,146 @@
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import GlitchText from '@/components/GlitchText';
import { useState, useEffect } from 'react';
const HIGHSCORE_KEYS = {
tetris: 'tetris-highscore',
pacman: 'pacman-highscore',
snake: 'snake-highscore',
breakout: 'breakout-highscore',
};
const MAX_SCORE = 4294967296;
const Leaderboard = () => {
const [scores, setScores] = useState({
tetris: 0,
pacman: 0,
snake: 0,
breakout: 0,
});
useEffect(() => {
const tetrisScore = localStorage.getItem(HIGHSCORE_KEYS.tetris);
const pacmanScore = localStorage.getItem(HIGHSCORE_KEYS.pacman);
const snakeScore = localStorage.getItem(HIGHSCORE_KEYS.snake);
const breakoutScore = localStorage.getItem(HIGHSCORE_KEYS.breakout);
setScores({
tetris: tetrisScore ? Math.min(parseInt(tetrisScore, 10), MAX_SCORE) : 0,
pacman: pacmanScore ? Math.min(parseInt(pacmanScore, 10), MAX_SCORE) : 0,
snake: snakeScore ? Math.min(parseInt(snakeScore, 10), MAX_SCORE) : 0,
breakout: breakoutScore ? Math.min(parseInt(breakoutScore, 10), MAX_SCORE) : 0,
});
}, []);
const totalScore = scores.tetris + scores.pacman + scores.snake + scores.breakout;
const gameCards = [
{
id: 'tetris',
name: 'Tetris',
score: scores.tetris,
icon: `▓▓
▓▓██
████`,
},
{
id: 'pacman',
name: 'Pac-Man',
score: scores.pacman,
icon: `◗ ᗣ
· ·`,
},
{
id: 'snake',
name: 'Snake',
score: scores.snake,
icon: `●■■
■◆`,
},
{
id: 'breakout',
name: 'Breakout',
score: scores.breakout,
icon: `████
═══`,
},
];
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="flex flex-col h-full"
>
<div className="flex items-center gap-4 mb-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">
{'<'} Back
</Link>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
<GlitchText text="Leaderboard" />
</h1>
</div>
{/* Total Score */}
<div className="border-2 border-primary box-glow p-4 bg-background/80 mb-4">
<p className="font-pixel text-sm text-foreground/60 mb-1">COMBINED TOTAL</p>
<p className="font-minecraft text-4xl text-primary text-glow-strong">
{totalScore.toLocaleString()}
</p>
<p className="font-pixel text-xs text-foreground/40 mt-1">
Target: 4,294,967,296 × 4 = 17,179,869,184
</p>
</div>
{/* Game Scores */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{gameCards.map((game, index) => (
<motion.div
key={game.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link to={`/games/${game.id}`} className="block">
<div className="border border-primary/50 hover:border-primary bg-background/50 hover:bg-primary/10 p-4 transition-all duration-300">
<pre className="font-mono text-lg text-primary/70 mb-3 leading-tight whitespace-pre">
{game.icon}
</pre>
<h2 className="font-minecraft text-xl text-primary text-glow mb-2">
{game.name}
</h2>
<div>
<p className="font-pixel text-xs text-foreground/60">HIGH SCORE</p>
<p className="font-minecraft text-2xl text-primary text-glow">
{game.score.toLocaleString()}
</p>
<div className="mt-2 h-2 bg-background/50 border border-primary/30">
<div
className="h-full bg-primary/60 transition-all duration-500"
style={{ width: `${Math.min((game.score / MAX_SCORE) * 100, 100)}%` }}
/>
</div>
<p className="font-pixel text-[10px] text-foreground/40 mt-1">
{((game.score / MAX_SCORE) * 100).toFixed(6)}% to max
</p>
</div>
</div>
</Link>
</motion.div>
))}
</div>
<div className="border border-primary/30 p-2 bg-background/30 mt-4">
<p className="font-pixel text-xs text-foreground/50">
<span className="text-primary">{'>'}</span> Click a game to play and improve your score
</p>
</div>
</motion.div>
);
};
export default Leaderboard;
+70
View File
@@ -0,0 +1,70 @@
import { motion } from 'framer-motion';
import { Github, Linkedin, Mail, Youtube } from 'lucide-react';
const socialLinks = [
{ name: 'YouTube', icon: Youtube, url: 'https://www.youtube.com/@DJorySev', description: 'Watch my content' },
{ name: 'GitHub', icon: Github, url: 'https://github.com/JorySeverijnse', description: 'Browse my code' },
{ name: 'Gitea', icon: Github, url: 'https://git.severijnse.eu/explore/repos', description: 'Self-hosted Git' },
{ name: 'LinkedIn', icon: Linkedin, url: 'https://www.linkedin.com/in/jory-s-5481ab256', description: 'Connect professionally' },
{ name: 'Gmail', icon: Mail, url: 'mailto:joryseverijnse@gmail.com', description: 'Personal email' },
{ name: 'Email', icon: Mail, url: 'mailto:jory@severijnse.eu', description: 'Domain email' },
];
const Links = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="h-full flex flex-col"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong mb-2">
Links
</h1>
<p className="font-pixel text-foreground/80 mb-6">
Connect with me across the web:
</p>
<div className="flex-1 grid grid-cols-2 sm:grid-cols-3 gap-3 content-start">
{socialLinks.map((link, index) => {
const Icon = link.icon;
return (
<motion.a
key={link.name}
href={link.url}
target="_blank"
rel="noopener noreferrer"
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: index * 0.05 }}
className="flex flex-col items-center justify-center gap-2 p-4 border border-primary/30 hover:border-primary transition-all duration-300 hover:box-glow hover:bg-primary/10 rounded-lg"
>
<Icon className="w-8 h-8 text-primary" />
<span className="font-minecraft text-sm text-primary text-glow">
{link.name}
</span>
<span className="font-pixel text-[10px] text-muted-foreground text-center">
{link.description}
</span>
</motion.a>
);
})}
</div>
{/* ASCII Art */}
<pre className="font-mono text-[8px] md:text-[10px] text-primary/30 leading-tight text-center mt-4 select-none">
{` .---.
/ \\
\\.@-@./
/\` \\_/ \`\\
// _ _ \\\\
| \\ / |
\\| \\|/ |/
\`._/_\\_.'"connect with me"`}
</pre>
</motion.div>
);
};
export default Links;
+537
View File
@@ -0,0 +1,537 @@
import { motion, AnimatePresence } from 'framer-motion';
import { useState, useEffect } from 'react';
import { Play, Pause, Volume2, Radio, Search, Loader2, ChevronDown, Link2, SkipBack, SkipForward, Zap } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
import { useMusic, Station } from '@/contexts/MusicContext';
const CATEGORIES = [
{ value: '', label: 'All Genres' },
{ value: 'pop', label: 'Pop' },
{ value: 'rock', label: 'Rock' },
{ value: 'jazz', label: 'Jazz' },
{ value: 'classical', label: 'Classical' },
{ value: 'electronic', label: 'Electronic' },
{ value: 'techno', label: 'Techno' },
{ value: 'house', label: 'House' },
{ value: 'trance', label: 'Trance' },
{ value: 'drum and bass', label: 'Drum & Bass' },
{ value: 'dubstep', label: 'Dubstep' },
{ value: 'hiphop', label: 'Hip Hop' },
{ value: 'country', label: 'Country' },
{ value: 'metal', label: 'Metal' },
{ value: 'ambient', label: 'Ambient' },
{ value: 'lofi', label: 'Lo-Fi' },
{ value: 'chillout', label: 'Chillout' },
{ value: 'synthwave', label: 'Synthwave' },
{ value: 'news', label: 'News' },
{ value: 'talk', label: 'Talk' },
];
// Preset electronic music streams
const PRESET_STREAMS = [
{ name: 'SomaFM - Groove Salad', url: 'https://ice2.somafm.com/groovesalad-128-mp3', genre: 'Ambient/Downtempo' },
{ name: 'SomaFM - DEF CON Radio', url: 'https://ice2.somafm.com/defcon-128-mp3', genre: 'Electronic/Hacker' },
{ name: 'SomaFM - Space Station', url: 'https://ice2.somafm.com/spacestation-128-mp3', genre: 'Space/Ambient' },
{ name: 'SomaFM - Drone Zone', url: 'https://ice2.somafm.com/dronezone-128-mp3', genre: 'Dark Ambient' },
{ name: 'SomaFM - Beat Blender', url: 'https://ice2.somafm.com/beatblender-128-mp3', genre: 'Deep House' },
{ name: 'SomaFM - cliqhop idm', url: 'https://ice2.somafm.com/cliqhop-128-mp3', genre: 'IDM/Glitch' },
{ name: 'Nightwave Plaza', url: 'https://radio.plaza.one/mp3', genre: 'Vaporwave' },
];
interface CategoryDropdownProps {
selectedCategory: string;
onSelect: (value: string) => void;
playSound: (sound: string) => void;
}
const CategoryDropdown = ({ selectedCategory, onSelect, playSound }: CategoryDropdownProps) => {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useState<HTMLDivElement | null>(null);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (dropdownRef[0] && !dropdownRef[0].contains(e.target as Node)) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [dropdownRef]);
const selectedLabel = CATEGORIES.find(c => c.value === selectedCategory)?.label || 'All Genres';
return (
<div ref={(el) => { dropdownRef[1](el); }} className="relative">
<button
onClick={() => {
playSound('click');
setIsOpen(!isOpen);
}}
className="w-full flex items-center justify-between px-4 py-2 bg-background border border-primary/30 hover:border-primary font-pixel text-sm text-primary transition-colors"
>
<span>{selectedLabel}</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -5 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -5 }}
transition={{ duration: 0.15 }}
className="absolute top-full left-0 right-0 z-50 mt-1 bg-background border border-primary/50 box-glow max-h-60 overflow-y-auto"
>
{CATEGORIES.map((cat) => (
<button
key={cat.value}
onClick={() => {
playSound('click');
onSelect(cat.value);
setIsOpen(false);
}}
className={`w-full px-4 py-2 text-left font-pixel text-sm transition-colors hover:bg-primary/20 ${
selectedCategory === cat.value ? 'bg-primary/30 text-primary' : 'text-primary/80'
}`}
>
{cat.label}
</button>
))}
</motion.div>
)}
</AnimatePresence>
</div>
);
};
// URL validation helper
const isValidStreamUrl = (url: string): { valid: boolean; error?: string } => {
if (!url.trim()) {
return { valid: false, error: 'Please enter a URL' };
}
try {
const parsed = new URL(url.trim());
// Only allow http/https protocols
if (!['http:', 'https:'].includes(parsed.protocol)) {
return { valid: false, error: 'URL must use http or https protocol' };
}
// Basic format check
if (!parsed.hostname || parsed.hostname.length < 3) {
return { valid: false, error: 'Invalid hostname' };
}
return { valid: true };
} catch {
return { valid: false, error: 'Invalid URL format' };
}
};
const Music = () => {
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState('');
const [customUrl, setCustomUrl] = useState('');
const [customUrlError, setCustomUrlError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'browse' | 'presets' | 'custom'>('browse');
const [filteredStations, setFilteredStations] = useState<Station[]>([]);
const { playSound } = useSettings();
const {
isPlaying,
isBuffering,
volume,
stations,
selectedStation,
hasFetched,
setVolume,
playStation,
togglePlay,
playNext,
playPrevious,
fetchStations,
} = useMusic();
// Fetch stations on mount
useEffect(() => {
fetchStations();
}, [fetchStations]);
// Filter stations based on search and category
useEffect(() => {
const filtered = stations.filter(station => {
const matchesSearch = station.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
station.tags.toLowerCase().includes(searchQuery.toLowerCase()) ||
station.country.toLowerCase().includes(searchQuery.toLowerCase());
const matchesCategory = !selectedCategory ||
station.tags.toLowerCase().includes(selectedCategory.toLowerCase());
return matchesSearch && matchesCategory;
});
setFilteredStations(filtered);
}, [searchQuery, selectedCategory, stations]);
const handlePlayStation = (station: Station, index: number) => {
playSound('click');
playStation(station, index);
};
// Clear error when URL changes
useEffect(() => {
if (customUrlError) setCustomUrlError(null);
}, [customUrl]);
const playCustomUrl = () => {
const validation = isValidStreamUrl(customUrl);
if (!validation.valid) {
setCustomUrlError(validation.error || 'Invalid URL');
playSound('error');
return;
}
setCustomUrlError(null);
playSound('click');
const customStation: Station = {
stationuuid: 'custom-' + Date.now(),
name: 'Custom Stream',
url: customUrl.trim(),
favicon: '',
country: 'Custom',
tags: 'custom',
bitrate: 0,
};
playStation(customStation, -1);
};
const playPreset = (preset: typeof PRESET_STREAMS[0]) => {
playSound('click');
const presetStation: Station = {
stationuuid: 'preset-' + preset.name,
name: preset.name,
url: preset.url,
favicon: '',
country: preset.genre,
tags: preset.genre.toLowerCase(),
bitrate: 128,
};
playStation(presetStation, -1);
};
const handleTogglePlay = () => {
playSound('click');
togglePlay();
};
const handlePlayNext = () => {
playSound('click');
playNext();
};
const handlePlayPrevious = () => {
playSound('click');
playPrevious();
};
const isLoading = !hasFetched;
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Radio Player
</h1>
<p className="font-pixel text-foreground/80">
Stream radio stations from around the world or add your own stream URL.
</p>
{/* Now Playing */}
{selectedStation && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="border border-primary p-4 bg-primary/5 box-glow space-y-4"
>
<div className="flex items-center gap-4">
<div className="w-12 h-12 border border-primary/50 flex items-center justify-center bg-background">
{selectedStation.favicon ? (
<img
src={selectedStation.favicon}
alt={selectedStation.name}
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : (
<Radio className="w-6 h-6 text-primary" />
)}
</div>
<div className="flex-1 min-w-0">
<h2 className="font-minecraft text-lg text-primary text-glow truncate">
{selectedStation.name}
</h2>
<p className="font-pixel text-xs text-foreground/60 truncate">
{selectedStation.country} {selectedStation.bitrate > 0 && `${selectedStation.bitrate}kbps`}
</p>
{isBuffering && (
<p className="font-pixel text-xs text-primary/60">Buffering...</p>
)}
</div>
{/* Playback Controls */}
<div className="flex items-center gap-2">
<button
onClick={handlePlayPrevious}
className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
title="Previous station"
>
<SkipBack size={16} />
</button>
<button
onClick={handleTogglePlay}
className="p-3 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
disabled={isBuffering}
>
{isBuffering ? (
<Loader2 size={20} className="animate-spin" />
) : isPlaying ? (
<Pause size={20} />
) : (
<Play size={20} />
)}
</button>
<button
onClick={handlePlayNext}
className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
title="Next station"
>
<SkipForward size={16} />
</button>
</div>
</div>
<div className="flex items-center gap-3">
<Volume2 size={16} className="text-primary" />
<input
type="range"
min="0"
max="100"
value={volume}
onChange={(e) => setVolume(Number(e.target.value))}
className="flex-1 h-1.5 bg-primary/30 appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-primary [&::-webkit-slider-thumb]:shadow-[0_0_5px_hsl(var(--glow-color)/0.8)]"
/>
<span className="font-pixel text-xs text-primary min-w-[40px]">
{volume}%
</span>
</div>
</motion.div>
)}
{/* Tabs */}
<div className="flex gap-2 border-b border-primary/30">
{(['browse', 'presets', 'custom'] as const).map((tab) => (
<button
key={tab}
onClick={() => {
playSound('click');
setActiveTab(tab);
}}
className={`px-4 py-2 font-pixel text-sm transition-all ${
activeTab === tab
? 'text-primary border-b-2 border-primary text-glow'
: 'text-foreground/60 hover:text-primary'
}`}
>
{tab === 'browse' && 'Browse'}
{tab === 'presets' && 'Electronic'}
{tab === 'custom' && 'Custom URL'}
</button>
))}
</div>
{/* Browse Tab */}
{activeTab === 'browse' && (
<>
{/* Filters */}
<div className="flex flex-col sm:flex-row gap-3">
<div className="sm:w-48">
<CategoryDropdown
selectedCategory={selectedCategory}
onSelect={setSelectedCategory}
playSound={playSound}
/>
</div>
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-primary/50" />
<input
type="text"
placeholder="Search stations..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-2 bg-background border border-primary/30 focus:border-primary font-pixel text-sm text-foreground placeholder:text-foreground/40 outline-none transition-colors"
/>
</div>
</div>
{/* Station List */}
<div className="border border-primary/30 max-h-[250px] overflow-y-auto">
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 text-primary animate-spin" />
<span className="font-pixel text-sm text-primary ml-2">Loading stations...</span>
</div>
) : filteredStations.length === 0 ? (
<div className="p-4 text-center">
<p className="font-pixel text-sm text-foreground/60">No stations found</p>
</div>
) : (
filteredStations.map((station, index) => (
<motion.button
key={station.stationuuid}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.02 }}
onClick={() => handlePlayStation(station, index)}
className={`w-full flex items-center gap-3 p-3 border-b border-primary/10 hover:bg-primary/10 transition-all duration-200 text-left ${
selectedStation?.stationuuid === station.stationuuid ? 'bg-primary/20' : ''
}`}
>
<div className="w-8 h-8 border border-primary/30 flex items-center justify-center flex-shrink-0 bg-background">
{station.favicon ? (
<img
src={station.favicon}
alt=""
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : (
<Radio className="w-4 h-4 text-primary/50" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="font-pixel text-sm text-primary truncate">{station.name}</p>
<p className="font-pixel text-xs text-foreground/50 truncate">
{station.country} {station.tags && `${station.tags.split(',')[0]}`}
</p>
</div>
{selectedStation?.stationuuid === station.stationuuid && isPlaying && (
<div className="flex gap-0.5">
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '0ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '150ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '300ms' }} />
</div>
)}
</motion.button>
))
)}
</div>
<p className="font-pixel text-xs text-foreground/50 text-center">
{filteredStations.length} stations available
</p>
</>
)}
{/* Electronic Presets Tab */}
{activeTab === 'presets' && (
<div className="space-y-4">
<div className="flex items-center gap-2 text-primary mb-4">
<Zap size={16} />
<span className="font-pixel text-sm">Curated Electronic Streams</span>
</div>
<div className="border border-primary/30 max-h-[300px] overflow-y-auto">
{PRESET_STREAMS.map((preset, index) => (
<motion.button
key={preset.name}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.05 }}
onClick={() => playPreset(preset)}
className={`w-full flex items-center gap-3 p-3 border-b border-primary/10 hover:bg-primary/10 transition-all duration-200 text-left ${
selectedStation?.name === preset.name ? 'bg-primary/20' : ''
}`}
>
<div className="w-8 h-8 border border-primary/30 flex items-center justify-center flex-shrink-0 bg-background">
<Zap className="w-4 h-4 text-primary/70" />
</div>
<div className="flex-1 min-w-0">
<p className="font-pixel text-sm text-primary truncate">{preset.name}</p>
<p className="font-pixel text-xs text-foreground/50 truncate">{preset.genre}</p>
</div>
{selectedStation?.name === preset.name && isPlaying && (
<div className="flex gap-0.5">
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '0ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '150ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '300ms' }} />
</div>
)}
</motion.button>
))}
</div>
<p className="font-pixel text-xs text-foreground/50 text-center">
High-quality electronic music streams from SomaFM and others
</p>
</div>
)}
{/* Custom URL Tab */}
{activeTab === 'custom' && (
<div className="space-y-4">
<div className="flex items-center gap-2 text-primary mb-4">
<Link2 size={16} />
<span className="font-pixel text-sm">Play Custom Stream URL</span>
</div>
<p className="font-pixel text-xs text-foreground/60">
Enter a direct URL to an audio stream (MP3, AAC, OGG, etc.)
</p>
<div className="flex gap-2">
<input
type="url"
placeholder="https://stream.example.com/radio.mp3"
value={customUrl}
onChange={(e) => setCustomUrl(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && playCustomUrl()}
className={`flex-1 px-4 py-2 bg-background border font-pixel text-sm text-foreground placeholder:text-foreground/40 outline-none transition-colors ${
customUrlError ? 'border-destructive focus:border-destructive' : 'border-primary/30 focus:border-primary'
}`}
/>
<button
onClick={playCustomUrl}
disabled={!customUrl.trim()}
className="px-4 py-2 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300 font-pixel text-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
Play
</button>
</div>
{customUrlError && (
<p className="font-pixel text-xs text-destructive">{customUrlError}</p>
)}
<div className="border border-primary/20 p-3 bg-primary/5">
<p className="font-pixel text-xs text-primary mb-2">Tips:</p>
<ul className="font-pixel text-xs text-foreground/60 space-y-1 list-disc list-inside">
<li>Use direct stream URLs (not webpage URLs)</li>
<li>Supported formats: MP3, AAC, OGG, FLAC</li>
<li>Look for .m3u or .pls files on radio sites</li>
<li>SomaFM, Radio.co, and Icecast streams work well</li>
</ul>
</div>
</div>
)}
</motion.div>
);
};
export default Music;
+90
View File
@@ -0,0 +1,90 @@
import { useLocation, Link } from "react-router-dom";
import { useEffect } from "react";
import { motion } from "framer-motion";
import { Terminal, AlertTriangle } from "lucide-react";
import { useSettings } from "@/contexts/SettingsContext";
const NotFound = () => {
const location = useLocation();
const { playSound } = useSettings();
useEffect(() => {
console.error("404 Error: User attempted to access non-existent route:", location.pathname);
playSound('error');
}, [location.pathname, playSound]);
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-center space-y-6 max-w-md"
>
{/* Error code */}
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ delay: 0.2, duration: 0.4 }}
className="flex items-center justify-center gap-3"
>
<AlertTriangle className="w-10 h-10 text-primary animate-pulse" />
<h1 className="font-minecraft text-6xl md:text-7xl text-primary text-glow">
404
</h1>
</motion.div>
{/* Terminal-style message */}
<div className="border border-primary/30 bg-background/80 p-4 rounded">
<div className="flex items-center gap-2 mb-3 pb-2 border-b border-primary/20">
<Terminal className="w-4 h-4 text-primary/60" />
<span className="font-pixel text-xs text-muted-foreground">error.log</span>
</div>
<div className="text-left space-y-2">
<p className="font-pixel text-sm text-primary">
<span className="text-muted-foreground">$</span> cd {location.pathname}
</p>
<p className="font-pixel text-sm text-destructive">
ERROR: Directory not found
</p>
<p className="font-pixel text-xs text-muted-foreground">
The requested path does not exist on this server.
</p>
</div>
</div>
{/* ASCII Art */}
<pre className="font-mono text-[10px] md:text-xs text-primary/40 leading-tight select-none">
{` _____
/ \\
| X X |
| ^ |
| === |
\\_____/
LOST IN THE VOID`}
</pre>
{/* Navigation */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.5, duration: 0.4 }}
className="space-y-3"
>
<p className="font-pixel text-xs text-muted-foreground">
{'>'} Return to known territory:
</p>
<Link
to="/"
onClick={() => playSound('click')}
className="inline-block font-minecraft text-sm text-primary hover:text-glow border border-primary/50 hover:border-primary px-4 py-2 transition-all duration-200 hover:bg-primary/10"
>
cd /home
</Link>
</motion.div>
</motion.div>
</div>
);
};
export default NotFound;
+384
View File
@@ -0,0 +1,384 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const GRID_WIDTH = 21;
const GRID_HEIGHT = 21;
const TICK_SPEED = 180;
const POWER_DURATION = 8000;
const MAX_SCORE = 4294967296;
const HIGHSCORE_KEY = 'pacman-highscore';
type Direction = 'up' | 'down' | 'left' | 'right';
type Position = { x: number; y: number };
const MAZE_TEMPLATE = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,3,1],
[1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,0,1],
[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
[1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,1],
[1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1],
[1,1,1,1,0,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,1],
[2,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,2],
[1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1],
[1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1],
[1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,1],
[1,3,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,3,1],
[1,1,0,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,1],
[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
[1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
];
const Pacman = () => {
const { playSound } = useSettings();
const [pacman, setPacman] = useState<Position>({ x: 10, y: 15 });
const [direction, setDirection] = useState<Direction>('right');
const [nextDirection, setNextDirection] = useState<Direction>('right');
const [mouthOpen, setMouthOpen] = useState(true);
const [ghosts, setGhosts] = useState<{ pos: Position; dir: Direction; eaten: boolean }[]>([
{ pos: { x: 9, y: 9 }, dir: 'left', eaten: false },
{ pos: { x: 10, y: 9 }, dir: 'up', eaten: false },
{ pos: { x: 11, y: 9 }, dir: 'right', eaten: false },
]);
const [dots, setDots] = useState<Set<string>>(new Set());
const [powerPellets, setPowerPellets] = useState<Set<string>>(new Set());
const [isPowered, setIsPowered] = useState(false);
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
const [gameComplete, setGameComplete] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const [level, setLevel] = useState(1);
const [isFullscreen, setIsFullscreen] = useState(false);
const gameRef = useRef<HTMLDivElement>(null);
const powerTimerRef = useRef<NodeJS.Timeout | null>(null);
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
const getCellSize = useCallback(() => {
if (typeof window === 'undefined') return 20;
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 40;
const maxHeight = window.innerHeight - 300;
return Math.min(Math.floor(maxWidth / GRID_WIDTH), Math.floor(maxHeight / GRID_HEIGHT), 16);
}
return isFullscreen ? 26 : 20;
}, [isFullscreen]);
const [cellSize, setCellSize] = useState(getCellSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCellSize(getCellSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCellSize]);
useEffect(() => { setCellSize(getCellSize()); }, [isFullscreen, getCellSize]);
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) { setIsFullscreen(true); enterFullscreen(); }
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) { setIsFullscreen(true); await enterFullscreen(); }
else { setIsFullscreen(false); await exitFullscreen(); }
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape' && isFullscreen) { setIsFullscreen(false); exitFullscreen(); } };
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const initDots = useCallback(() => {
const newDots = new Set<string>();
const newPowerPellets = new Set<string>();
for (let y = 0; y < GRID_HEIGHT; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
if (MAZE_TEMPLATE[y][x] === 0) newDots.add(`${x},${y}`);
else if (MAZE_TEMPLATE[y][x] === 3) newPowerPellets.add(`${x},${y}`);
}
}
newDots.delete('10,15'); newDots.delete('9,9'); newDots.delete('10,9'); newDots.delete('11,9');
return { dots: newDots, powerPellets: newPowerPellets };
}, []);
const canMove = (pos: Position, dir: Direction): boolean => {
let newX = pos.x, newY = pos.y;
switch (dir) { case 'up': newY--; break; case 'down': newY++; break; case 'left': newX--; break; case 'right': newX++; break; }
if (newX < 0) return MAZE_TEMPLATE[newY]?.[GRID_WIDTH - 1] !== 1;
if (newX >= GRID_WIDTH) return MAZE_TEMPLATE[newY]?.[0] !== 1;
if (newY < 0 || newY >= GRID_HEIGHT) return false;
return MAZE_TEMPLATE[newY][newX] !== 1;
};
const moveEntity = (pos: Position, dir: Direction): Position => {
let newX = pos.x, newY = pos.y;
switch (dir) { case 'up': newY--; break; case 'down': newY++; break; case 'left': newX--; break; case 'right': newX++; break; }
if (newX < 0) newX = GRID_WIDTH - 1;
if (newX >= GRID_WIDTH) newX = 0;
return { x: newX, y: newY };
};
const activatePowerMode = () => {
if (powerTimerRef.current) clearTimeout(powerTimerRef.current);
setIsPowered(true);
powerTimerRef.current = setTimeout(() => { setIsPowered(false); setGhosts(prev => prev.map(g => ({ ...g, eaten: false }))); }, POWER_DURATION);
};
const startGame = () => {
if (powerTimerRef.current) clearTimeout(powerTimerRef.current);
setPacman({ x: 10, y: 15 }); setDirection('right'); setNextDirection('right'); setMouthOpen(true);
setGhosts([{ pos: { x: 9, y: 9 }, dir: 'left', eaten: false }, { pos: { x: 10, y: 9 }, dir: 'up', eaten: false }, { pos: { x: 11, y: 9 }, dir: 'right', eaten: false }]);
const { dots: newDots, powerPellets: newPowerPellets } = initDots();
setDots(newDots); setPowerPellets(newPowerPellets); setIsPowered(false); setScore(0); setLevel(1);
setGameOver(false); setGameComplete(false); setIsPaused(false); setGameStarted(true);
playSound('success'); gameRef.current?.focus();
};
useEffect(() => { return () => { if (powerTimerRef.current) clearTimeout(powerTimerRef.current); }; }, []);
useEffect(() => {
if (!gameStarted || gameOver || gameComplete || isPaused) return;
const interval = setInterval(() => {
setMouthOpen(prev => !prev);
if (canMove(pacman, nextDirection)) setDirection(nextDirection);
const actualDir = canMove(pacman, nextDirection) ? nextDirection : direction;
if (canMove(pacman, actualDir)) {
const newPos = moveEntity(pacman, actualDir);
setPacman(newPos);
const posKey = `${newPos.x},${newPos.y}`;
if (powerPellets.has(posKey)) {
setPowerPellets(prev => { const np = new Set(prev); np.delete(posKey); return np; });
activatePowerMode();
setScore(prev => {
const ns = Math.min(prev + 50, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('success');
} else if (dots.has(posKey)) {
setDots(prev => { const nd = new Set(prev); nd.delete(posKey); return nd; });
setScore(prev => {
const ns = Math.min(prev + 10, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('hover');
}
}
setGhosts(prev => prev.map(ghost => {
if (ghost.eaten) return ghost;
const directions: Direction[] = ['up', 'down', 'left', 'right'];
const opposite: Record<Direction, Direction> = { up: 'down', down: 'up', left: 'right', right: 'left' };
const validDirs = directions.filter(d => d !== opposite[ghost.dir] && canMove(ghost.pos, d));
if (validDirs.length === 0) {
const anyValid = directions.filter(d => canMove(ghost.pos, d));
if (anyValid.length === 0) return ghost;
const dir = anyValid[Math.floor(Math.random() * anyValid.length)];
return { ...ghost, pos: moveEntity(ghost.pos, dir), dir };
}
const dx = pacman.x - ghost.pos.x, dy = pacman.y - ghost.pos.y;
let preferredDirs: Direction[] = [];
if (isPowered) { preferredDirs = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? ['left', 'up', 'down', 'right'] : ['right', 'down', 'up', 'left']) : (dy > 0 ? ['up', 'left', 'right', 'down'] : ['down', 'right', 'left', 'up']); }
else { preferredDirs = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? ['right', 'down', 'up', 'left'] : ['left', 'up', 'down', 'right']) : (dy > 0 ? ['down', 'right', 'left', 'up'] : ['up', 'left', 'right', 'down']); }
if (Math.random() < 0.6) { for (const dir of preferredDirs) { if (validDirs.includes(dir)) return { ...ghost, pos: moveEntity(ghost.pos, dir), dir }; } }
const dir = validDirs[Math.floor(Math.random() * validDirs.length)];
return { ...ghost, pos: moveEntity(ghost.pos, dir), dir };
}));
}, TICK_SPEED);
return () => clearInterval(interval);
}, [gameStarted, gameOver, gameComplete, isPaused, pacman, direction, nextDirection, dots, powerPellets, highScore, isPowered, playSound]);
useEffect(() => {
if (!gameStarted || gameOver || gameComplete) return;
for (let i = 0; i < ghosts.length; i++) {
const ghost = ghosts[i];
if (ghost.pos.x === pacman.x && ghost.pos.y === pacman.y) {
if (isPowered && !ghost.eaten) {
setGhosts(prev => prev.map((g, idx) => idx === i ? { ...g, eaten: true, pos: { x: 10, y: 9 } } : g));
setScore(prev => {
const ns = Math.min(prev + 200, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('success');
} else if (!ghost.eaten) { setGameOver(true); playSound('error'); return; }
}
}
if (dots.size === 0 && powerPellets.size === 0) {
setScore(prev => {
const ns = Math.min(prev + 500, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
setLevel(prev => prev + 1);
const { dots: newDots, powerPellets: newPowerPellets } = initDots();
setDots(newDots); setPowerPellets(newPowerPellets);
playSound('success');
}
}, [pacman, ghosts, dots, powerPellets, gameStarted, gameOver, gameComplete, highScore, isPowered, playSound, initDots]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!gameStarted) return;
switch (e.key) {
case 'ArrowUp': case 'w': e.preventDefault(); setNextDirection('up'); break;
case 'ArrowDown': case 's': e.preventDefault(); setNextDirection('down'); break;
case 'ArrowLeft': case 'a': e.preventDefault(); setNextDirection('left'); break;
case 'ArrowRight': case 'd': e.preventDefault(); setNextDirection('right'); break;
case 'p': e.preventDefault(); if (!gameOver && !gameComplete) setIsPaused(prev => !prev); break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [gameStarted, gameOver, gameComplete]);
const getPacmanRotation = () => { switch (direction) { case 'right': return 0; case 'down': return 90; case 'left': return 180; case 'up': return 270; } };
const renderPacman = () => (
<svg viewBox="0 0 100 100" className="w-full h-full" style={{ transform: `rotate(${getPacmanRotation()}deg)` }}>
<circle cx="50" cy="50" r="45" fill="hsl(var(--primary))" />
{mouthOpen && <path d="M 50 50 L 95 25 L 95 75 Z" fill="hsl(var(--background))" />}
<circle cx="50" cy="25" r="6" fill="hsl(var(--background))" />
</svg>
);
const renderGhost = (index: number, eaten: boolean) => {
const colors = ['hsl(0 70% 50%)', 'hsl(300 70% 50%)', 'hsl(180 70% 50%)'];
const scaredColor = 'hsl(220 70% 50%)';
if (eaten) return null;
return (
<svg viewBox="0 0 100 100" className="w-full h-full">
<path d={`M 10 95 L 10 45 Q 10 5 50 5 Q 90 5 90 45 L 90 95 L 75 80 L 60 95 L 50 80 L 40 95 L 25 80 L 10 95 Z`} fill={isPowered ? scaredColor : colors[index % colors.length]} className={isPowered ? 'animate-pulse' : ''} />
<ellipse cx="35" cy="45" rx="12" ry="15" fill="white" /><ellipse cx="65" cy="45" rx="12" ry="15" fill="white" />
<circle cx="38" cy="48" r="6" fill="hsl(var(--background))" /><circle cx="68" cy="48" r="6" fill="hsl(var(--background))" />
</svg>
);
};
const renderGrid = () => {
const cells = [];
const spriteSize = Math.max(cellSize * 0.7, 12);
for (let y = 0; y < GRID_HEIGHT; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
const isWall = MAZE_TEMPLATE[y][x] === 1;
const isTunnel = MAZE_TEMPLATE[y][x] === 2;
const isPacmanHere = pacman.x === x && pacman.y === y;
const ghostIndex = ghosts.findIndex(g => g.pos.x === x && g.pos.y === y && !g.eaten);
const isDot = dots.has(`${x},${y}`);
const isPowerPellet = powerPellets.has(`${x},${y}`);
cells.push(
<div key={`${x}-${y}`} className={`flex items-center justify-center transition-colors duration-100 ${isWall ? 'bg-primary/20 border border-primary/40' : isTunnel ? 'bg-background/30' : 'bg-background/50 border border-primary/5'}`} style={{ width: cellSize, height: cellSize }}>
{isPacmanHere && <div style={{ width: spriteSize, height: spriteSize }}>{renderPacman()}</div>}
{ghostIndex !== -1 && !isPacmanHere && <div style={{ width: spriteSize, height: spriteSize }}>{renderGhost(ghostIndex, ghosts[ghostIndex].eaten)}</div>}
{isDot && !isPacmanHere && ghostIndex === -1 && <div className="w-1.5 h-1.5 bg-primary/80 rounded-full" />}
{isPowerPellet && !isPacmanHere && ghostIndex === -1 && <div className="w-3 h-3 bg-primary rounded-full animate-pulse box-glow" />}
</div>
);
}
}
return cells;
};
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div ref={gameRef} tabIndex={0} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Pac-Man</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
<div className="border-2 border-primary box-glow p-1 bg-background/80">
<div className="grid" style={{ gridTemplateColumns: `repeat(${GRID_WIDTH}, ${cellSize}px)` }}>{renderGrid()}</div>
</div>
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">SCORE</p><p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p><p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p><p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LEVEL</p><p className="font-minecraft text-lg text-primary text-glow">{level}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p><p className="font-pixel text-[10px] text-foreground/80"> / WASD</p><p className="font-pixel text-[10px] text-foreground/80">P: Pause</p></div>
{!gameStarted || gameOver || gameComplete ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
) : (
<button onClick={() => setIsPaused(p => !p)} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">{isPaused ? 'RESUME' : 'PAUSE'}</button>
)}
</div>
)}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LVL</p><p className="font-minecraft text-sm text-primary">{level}</p></div>
</div>
{gameStarted && !gameOver && !gameComplete && (
<div className="grid grid-cols-3 gap-1 mt-2">
<div />
<GameTouchButton onAction={() => setNextDirection('up')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => setNextDirection('left')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<button onClick={() => setIsPaused(p => !p)} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={() => setNextDirection('right')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => setNextDirection('down')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
</div>
)}
{(!gameStarted || gameOver || gameComplete) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
)}
</div>
)}
</div>
{!isMobile && (gameOver || isPaused || gameComplete) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameComplete ? 'GAME COMPLETE!' : gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{(gameOver || gameComplete) && (<><p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p><p className="font-pixel text-xs text-foreground/60 mb-3">Level: {level}</p></>)}
<button onClick={(gameOver || gameComplete) ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{(gameOver || gameComplete) ? 'PLAY AGAIN' : 'RESUME'}</button>
</div>
</div>
)}
</motion.div>
);
};
export default Pacman;
+255
View File
@@ -0,0 +1,255 @@
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ArrowLeft, ExternalLink, Github } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
interface ProjectData {
title: string;
description: string;
status: string;
longDescription: string;
technologies: string[];
features: string[];
links?: {
demo?: string;
github?: string;
};
}
const projectsData: Record<string, ProjectData> = {
'personal-website': {
title: 'Personal Website',
description: 'This Matrix-themed personal website with retro hacker aesthetics.',
status: 'Complete',
longDescription: 'A fully custom personal website built with React and TypeScript, featuring a Matrix-inspired cyberpunk design. The site includes immersive visual effects like CRT scanlines, Matrix rain animation, and glitch text. Interactive features include a terminal command interface with navigation shortcuts, toggleable sound effects, an integrated AI chat powered by Pollinations.ai, and a radio music player with station browsing. Designed to showcase my projects and personality with a unique hacker aesthetic.',
technologies: ['React', 'TypeScript', 'Tailwind CSS', 'Framer Motion', 'Web Audio API', 'Pollinations.ai', 'Radio Browser API'],
features: [
'Matrix rain animation background with customizable density',
'Custom crosshair cursor with hover scaling effects',
'CRT scanline and flicker effects (toggleable)',
'Terminal command interface with navigation shortcuts (/home, /about, /ai, etc.)',
'Sound effects system with keyboard clicks and terminal beeps',
'Red/Green theme toggle with localStorage persistence',
'ASCII boot sequence with fake system initialization',
'Glitch text effects on hover (character scrambling)',
'Hidden easter egg for old-school gamers',
'AI chat integration with conversation history persistence',
'Radio music player with station search and category filtering',
'Persistent mini music player across all pages',
'Custom Matrix-themed scrollbar',
'Dynamic status based on Amsterdam timezone',
'ASCII art portrait on About page',
'Responsive design for all screen sizes',
],
},
'3-way-speakers': {
title: '3 Way Speakers',
description: 'Building custom 3-way speaker system with crossover design.',
status: 'Complete',
longDescription: 'A DIY audio project involving the design and construction of high-fidelity 3-way speakers. This includes selecting appropriate drivers, designing custom crossover circuits, and building enclosures optimized for acoustic performance.',
technologies: ['Electronics', 'Woodworking', 'Audio Engineering', 'Circuit Design'],
features: [
'Custom crossover network design',
'Frequency response optimization',
'MDF enclosure construction',
'Driver selection and matching',
'Acoustic dampening',
'Bi-wire terminal setup',
],
},
'xray-machine': {
title: 'X-Ray Machine',
description: 'DIY X-ray machine project for educational purposes.',
status: 'In Progress',
longDescription: 'An educational project exploring the principles of X-ray generation and imaging. This involves understanding high-voltage electronics, radiation safety, and imaging techniques. Built with proper safety measures and shielding for experimental purposes.',
technologies: ['High Voltage Electronics', 'Vacuum Tubes', 'Radiation Physics', 'Safety Engineering'],
features: [
'High voltage power supply design',
'X-ray tube integration',
'Lead shielding enclosure',
'Imaging plate system',
'Safety interlock system',
'Dosimetry monitoring',
],
},
'dj-mixing-visualizer': {
title: 'Automated DJ Mixing & Visualizer',
description: 'Automated DJ mixing script with audio visualizer XY mode.',
status: 'In Progress',
longDescription: 'A software project that automates DJ mixing by analyzing BPM, key, and energy levels of tracks. Features an XY mode audio visualizer that creates real-time visual representations of the music being played, perfect for live performances and streaming.',
technologies: ['Python', 'Audio Analysis', 'FFT', 'OpenGL', 'MIDI'],
features: [
'Automatic BPM detection and sync',
'Key detection for harmonic mixing',
'XY mode oscilloscope visualizer',
'Real-time audio analysis',
'Crossfade automation',
'Beat-matched transitions',
'Waveform display',
],
},
'vps-infrastructure': {
title: 'VPS Server Infrastructure',
description: 'Self-hosted VPS with authoritative nameserver, git, password manager, mail, reverse proxy and VPN.',
status: 'Complete',
longDescription: 'A comprehensive self-hosted server infrastructure project. Running on a VPS with full control over DNS, version control, secure password management, email services, and network security. Built for privacy, control, and learning.',
technologies: ['Linux', 'CoreDNS', 'Gitea', 'Vaultwarden', 'Postfix/Dovecot', 'Caddy', 'WireGuard'],
features: [
'Authoritative DNS nameserver (CoreDNS)',
'Self-hosted Git server (Gitea)',
'Password manager (Vaultwarden)',
'Mail server with SMTP/IMAP',
'Caddy reverse proxy with automatic SSL',
'WireGuard VPN server',
'Automated backups',
],
},
};
const ProjectDetail = () => {
const { slug } = useParams<{ slug: string }>();
const { playSound } = useSettings();
const project = slug ? projectsData[slug] : null;
if (!project) {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl text-primary text-glow-strong">
Project Not Found
</h1>
<Link
to="/projects"
onClick={() => playSound('click')}
className="inline-flex items-center gap-2 font-pixel text-primary hover:text-primary/80 transition-colors"
>
<ArrowLeft size={16} />
Back to Projects
</Link>
</motion.div>
);
}
const statusColor = {
'Complete': 'text-green-400 border-green-400',
'In Progress': 'text-yellow-400 border-yellow-400',
'Planning': 'text-blue-400 border-blue-400',
}[project.status] || 'text-primary border-primary';
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<Link
to="/projects"
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="inline-flex items-center gap-2 font-pixel text-primary hover:text-primary/80 transition-colors"
>
<ArrowLeft size={16} />
Back to Projects
</Link>
<div className="flex flex-wrap items-start justify-between gap-4">
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
{project.title}
</h1>
<span className={`font-pixel text-xs px-3 py-1 border ${statusColor}`}>
{project.status}
</span>
</div>
<p className="font-pixel text-foreground/80 leading-relaxed">
{project.longDescription}
</p>
{/* Technologies */}
<div className="space-y-3">
<h2 className="font-minecraft text-xl text-primary text-glow">
Technologies
</h2>
<div className="flex flex-wrap gap-2">
{project.technologies.map((tech) => (
<span
key={tech}
className="font-pixel text-xs px-3 py-1 border border-primary/50 text-primary bg-primary/10"
>
{tech}
</span>
))}
</div>
</div>
{/* Features */}
<div className="space-y-3">
<h2 className="font-minecraft text-xl text-primary text-glow">
Features
</h2>
<ul className="space-y-2">
{project.features.map((feature, index) => (
<motion.li
key={feature}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
className="font-pixel text-foreground/80 flex items-center gap-2"
>
<span className="text-primary">{'>'}</span>
{feature.includes('easter egg') ? (
<span className="group cursor-help inline-flex items-center gap-2">
{feature}
<span className="px-2 py-0.5 bg-primary/10 border border-primary/30 text-primary/50 text-xs opacity-0 group-hover:opacity-100 transition-opacity duration-300 whitespace-nowrap">
... you know the rest
</span>
</span>
) : (
feature
)}
</motion.li>
))}
</ul>
</div>
{/* Links */}
{project.links && (
<div className="flex gap-4 pt-4">
{project.links.demo && (
<a
href={project.links.demo}
target="_blank"
rel="noopener noreferrer"
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="inline-flex items-center gap-2 font-pixel text-sm px-4 py-2 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
>
<ExternalLink size={14} />
Live Demo
</a>
)}
{project.links.github && (
<a
href={project.links.github}
target="_blank"
rel="noopener noreferrer"
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="inline-flex items-center gap-2 font-pixel text-sm px-4 py-2 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
>
<Github size={14} />
Source Code
</a>
)}
</div>
)}
</motion.div>
);
};
export default ProjectDetail;
+100
View File
@@ -0,0 +1,100 @@
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import { ArrowRight } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
const projects = [
{
slug: 'personal-website',
title: 'Personal Website',
description: 'This Matrix-themed personal website with retro hacker aesthetics.',
status: 'Complete',
},
{
slug: '3-way-speakers',
title: '3 Way Speakers',
description: 'Building custom 3-way speaker system with crossover design.',
status: 'Complete',
},
{
slug: 'xray-machine',
title: 'X-Ray Machine',
description: 'DIY X-ray machine project for educational purposes.',
status: 'In Progress',
},
{
slug: 'dj-mixing-visualizer',
title: 'Automated DJ Mixing & Visualizer',
description: 'Automated DJ mixing script with audio visualizer XY mode.',
status: 'In Progress',
},
{
slug: 'vps-infrastructure',
title: 'VPS Server Infrastructure',
description: 'Self-hosted VPS with authoritative nameserver, git, password manager, mail, reverse proxy and VPN.',
status: 'Complete',
},
];
const Projects = () => {
const { playSound } = useSettings();
const statusColor = (status: string) => {
return {
'Complete': 'text-green-400 border-green-400',
'In Progress': 'text-yellow-400 border-yellow-400',
'Planning': 'text-blue-400 border-blue-400',
}[status] || 'text-primary border-primary';
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Projects
</h1>
<p className="font-pixel text-foreground/80">
Here are some of the things I've been working on:
</p>
<div className="grid gap-4">
{projects.map((project, index) => (
<motion.div
key={project.slug}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link
to={`/projects/${project.slug}`}
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="group block p-4 border border-primary/30 hover:border-primary transition-all duration-300 hover:box-glow"
>
<div className="flex justify-between items-start mb-2">
<h2 className="font-minecraft text-xl text-primary text-glow group-hover:text-glow-strong transition-all">
{project.title}
</h2>
<span className={`font-pixel text-xs px-2 py-1 border ${statusColor(project.status)}`}>
{project.status}
</span>
</div>
<p className="font-pixel text-foreground/80 mb-3">{project.description}</p>
<div className="flex items-center gap-2 font-pixel text-sm text-primary opacity-0 group-hover:opacity-100 transition-opacity duration-300">
<span>View Details</span>
<ArrowRight size={14} />
</div>
</Link>
</motion.div>
))}
</div>
</motion.div>
);
};
export default Projects;
+110
View File
@@ -0,0 +1,110 @@
import { motion } from 'framer-motion';
import { ExternalLink, Book, Wrench, Code, Server } from 'lucide-react';
const resourceCategories = [
{
title: 'Documentation',
icon: Book,
resources: [
{ name: 'MDN Web Docs', url: 'https://developer.mozilla.org', description: 'Web development reference' },
{ name: 'React Documentation', url: 'https://react.dev', description: 'Official React docs' },
{ name: 'TypeScript Handbook', url: 'https://www.typescriptlang.org/docs/', description: 'TypeScript guide' },
],
},
{
title: 'Development Tools',
icon: Wrench,
resources: [
{ name: 'Neovim', url: 'https://neovim.io', description: 'Hyperextensible Vim-based text editor' },
{ name: 'GitHub', url: 'https://github.com', description: 'Version control & collaboration' },
{ name: 'Gitea', url: 'https://gitea.io', description: 'Self-hosted Git service' },
{ name: 'Figma', url: 'https://figma.com', description: 'Design & prototyping' },
],
},
{
title: 'Frameworks & Libraries',
icon: Code,
resources: [
{ name: 'Tailwind CSS', url: 'https://tailwindcss.com', description: 'Utility-first CSS framework' },
{ name: 'Framer Motion', url: 'https://www.framer.com/motion/', description: 'Animation library for React' },
{ name: 'Vite', url: 'https://vitejs.dev', description: 'Fast build tool' },
],
},
{
title: 'Self-Hosting & Infrastructure',
icon: Server,
resources: [
{ name: 'Proxmox', url: 'https://www.proxmox.com', description: 'Virtualization platform' },
{ name: 'Docker', url: 'https://docker.com', description: 'Container platform' },
{ name: 'Caddy', url: 'https://caddyserver.com', description: 'Web server with automatic HTTPS' },
],
},
];
const Resources = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Resources
</h1>
<p className="font-pixel text-foreground/80">
Tools, documentation, and resources I recommend:
</p>
<div className="space-y-6">
{resourceCategories.map((category, categoryIndex) => {
const Icon = category.icon;
return (
<motion.div
key={category.title}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: categoryIndex * 0.1 }}
className="space-y-3"
>
<div className="flex items-center gap-2">
<Icon className="w-5 h-5 text-primary" />
<h2 className="font-minecraft text-xl text-primary text-glow">
{category.title}
</h2>
</div>
<div className="grid gap-2 pl-7">
{category.resources.map((resource, index) => (
<motion.a
key={resource.name}
href={resource.url}
target="_blank"
rel="noopener noreferrer"
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: categoryIndex * 0.1 + index * 0.05 }}
className="group flex items-center justify-between p-3 border border-primary/20 hover:border-primary/60 transition-all duration-300 hover:bg-primary/5"
>
<div className="flex flex-col">
<span className="font-minecraft text-sm text-primary">
{resource.name}
</span>
<span className="font-pixel text-xs text-foreground/60">
{resource.description}
</span>
</div>
<ExternalLink className="w-4 h-4 text-primary opacity-0 group-hover:opacity-100 transition-opacity" />
</motion.a>
))}
</div>
</motion.div>
);
})}
</div>
</motion.div>
);
};
export default Resources;
+355
View File
@@ -0,0 +1,355 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const GRID_SIZE = 20;
const TICK_SPEED = 120;
const MAX_SCORE = 4294967296;
const HIGHSCORE_KEY = 'snake-highscore';
type Direction = 'up' | 'down' | 'left' | 'right';
type Position = { x: number; y: number };
const Snake = () => {
const { playSound } = useSettings();
const [snake, setSnake] = useState<Position[]>([{ x: 10, y: 10 }]);
const [direction, setDirection] = useState<Direction>('right');
const [food, setFood] = useState<Position>({ x: 15, y: 10 });
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
const [gameComplete, setGameComplete] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const gameRef = useRef<HTMLDivElement>(null);
const directionQueueRef = useRef<Direction[]>([]);
const currentDirectionRef = useRef<Direction>('right');
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
// Calculate cell size based on screen
const getCellSize = useCallback(() => {
if (typeof window === 'undefined') return 24;
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 40;
const maxHeight = window.innerHeight - 300;
return Math.min(Math.floor(maxWidth / GRID_SIZE), Math.floor(maxHeight / GRID_SIZE), 18);
}
return isFullscreen ? 28 : 24;
}, [isFullscreen]);
const [cellSize, setCellSize] = useState(getCellSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCellSize(getCellSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCellSize]);
useEffect(() => {
setCellSize(getCellSize());
}, [isFullscreen, getCellSize]);
// Auto-fullscreen on mobile
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) {
setIsFullscreen(true);
enterFullscreen();
}
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) {
setIsFullscreen(true);
await enterFullscreen();
} else {
setIsFullscreen(false);
await exitFullscreen();
}
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isFullscreen) {
setIsFullscreen(false);
exitFullscreen();
}
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const spawnFood = useCallback((currentSnake: Position[]): Position | null => {
const occupied = new Set(currentSnake.map(s => `${s.x},${s.y}`));
const available: Position[] = [];
for (let x = 0; x < GRID_SIZE; x++) {
for (let y = 0; y < GRID_SIZE; y++) {
if (!occupied.has(`${x},${y}`)) available.push({ x, y });
}
}
if (available.length === 0) return null;
return available[Math.floor(Math.random() * available.length)];
}, []);
const resetSnakeKeepScore = useCallback(() => {
const initialSnake = [{ x: 10, y: 10 }];
setSnake(initialSnake);
setDirection('right');
currentDirectionRef.current = 'right';
directionQueueRef.current = [];
setFood(spawnFood(initialSnake)!);
playSound('success');
}, [spawnFood, playSound]);
const startGame = () => {
const initialSnake = [{ x: 10, y: 10 }];
setSnake(initialSnake);
setDirection('right');
currentDirectionRef.current = 'right';
directionQueueRef.current = [];
setFood(spawnFood(initialSnake)!);
setScore(0);
setGameOver(false);
setGameComplete(false);
setIsPaused(false);
setGameStarted(true);
playSound('success');
gameRef.current?.focus();
};
useEffect(() => {
if (!gameStarted || gameOver || gameComplete || isPaused) return;
const interval = setInterval(() => {
const opposite: Record<Direction, Direction> = { up: 'down', down: 'up', left: 'right', right: 'left' };
let nextDir = currentDirectionRef.current;
while (directionQueueRef.current.length > 0) {
const queuedDir = directionQueueRef.current.shift()!;
if (queuedDir !== opposite[currentDirectionRef.current]) {
nextDir = queuedDir;
break;
}
}
currentDirectionRef.current = nextDir;
setDirection(nextDir);
setSnake(prev => {
const head = prev[0];
let newHead: Position;
switch (nextDir) {
case 'up': newHead = { x: head.x, y: head.y - 1 }; break;
case 'down': newHead = { x: head.x, y: head.y + 1 }; break;
case 'left': newHead = { x: head.x - 1, y: head.y }; break;
case 'right': newHead = { x: head.x + 1, y: head.y }; break;
}
if (newHead.x < 0 || newHead.x >= GRID_SIZE || newHead.y < 0 || newHead.y >= GRID_SIZE) {
setGameOver(true);
playSound('error');
return prev;
}
if (prev.some(s => s.x === newHead.x && s.y === newHead.y)) {
setGameOver(true);
playSound('error');
return prev;
}
const newSnake = [newHead, ...prev];
if (newHead.x === food.x && newHead.y === food.y) {
playSound('success');
setScore(s => {
const newScore = Math.min(s + 10, MAX_SCORE);
if (newScore >= MAX_SCORE) setShowGlitchCrash(true);
if (newScore > highScore) {
setHighScore(newScore);
localStorage.setItem(HIGHSCORE_KEY, newScore.toString());
}
return newScore;
});
const newFood = spawnFood(newSnake);
if (newFood === null) setTimeout(() => resetSnakeKeepScore(), 500);
else setFood(newFood);
return newSnake;
}
newSnake.pop();
return newSnake;
});
}, TICK_SPEED);
return () => clearInterval(interval);
}, [gameStarted, gameOver, gameComplete, isPaused, food, highScore, playSound, spawnFood, resetSnakeKeepScore]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!gameStarted) return;
let newDir: Direction | null = null;
switch (e.key) {
case 'ArrowUp': case 'w': e.preventDefault(); newDir = 'up'; break;
case 'ArrowDown': case 's': e.preventDefault(); newDir = 'down'; break;
case 'ArrowLeft': case 'a': e.preventDefault(); newDir = 'left'; break;
case 'ArrowRight': case 'd': e.preventDefault(); newDir = 'right'; break;
case 'p': e.preventDefault(); if (!gameOver && !gameComplete) setIsPaused(p => !p); return;
}
if (newDir && directionQueueRef.current.length < 3) directionQueueRef.current.push(newDir);
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [gameStarted, gameOver, gameComplete]);
const renderGrid = () => {
const cells = [];
const snakeSet = new Set(snake.map(s => `${s.x},${s.y}`));
const head = snake[0];
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const isSnake = snakeSet.has(`${x},${y}`);
const isHead = head.x === x && head.y === y;
const isFood = food.x === x && food.y === y;
cells.push(
<div
key={`${x}-${y}`}
className={`flex items-center justify-center border transition-colors duration-75 ${
isHead ? 'bg-primary box-glow border-primary'
: isSnake ? 'bg-primary/80 border-primary/60'
: isFood ? 'bg-destructive/80 border-destructive/60'
: 'bg-background/50 border-primary/10'
}`}
style={{ width: cellSize, height: cellSize }}
>
{isFood && <div className="bg-destructive rounded-sm animate-pulse" style={{ width: cellSize * 0.5, height: cellSize * 0.5 }} />}
</div>
);
}
}
return cells;
};
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div
ref={gameRef}
tabIndex={0}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}
>
{/* Header */}
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Snake</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
{/* Main layout */}
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
{/* Game Grid */}
<div className="border-2 border-primary box-glow p-1 bg-background/80">
<div className="grid" style={{ gridTemplateColumns: `repeat(${GRID_SIZE}, ${cellSize}px)` }}>{renderGrid()}</div>
</div>
{/* Side Panel */}
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60">SCORE</p>
<p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p>
</div>
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p>
<p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p>
<p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p>
</div>
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60">LENGTH</p>
<p className="font-minecraft text-lg text-primary text-glow">{snake.length}</p>
</div>
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p>
<p className="font-pixel text-[10px] text-foreground/80"> / WASD</p>
<p className="font-pixel text-[10px] text-foreground/80">P: Pause</p>
</div>
{!gameStarted || gameOver || gameComplete ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">
{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}
</button>
) : (
<button onClick={() => setIsPaused(p => !p)} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">
{isPaused ? 'RESUME' : 'PAUSE'}
</button>
)}
</div>
)}
{/* Mobile Controls */}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LEN</p><p className="font-minecraft text-sm text-primary">{snake.length}</p></div>
</div>
{gameStarted && !gameOver && !gameComplete && (
<div className="grid grid-cols-3 gap-1 mt-2">
<div />
<GameTouchButton onAction={() => directionQueueRef.current.push('up')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => directionQueueRef.current.push('left')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<button onClick={() => setIsPaused(p => !p)} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={() => directionQueueRef.current.push('right')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => directionQueueRef.current.push('down')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
</div>
)}
{(!gameStarted || gameOver || gameComplete) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">
{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}
</button>
)}
</div>
)}
</div>
{/* Desktop Overlay */}
{!isMobile && (gameOver || isPaused || gameComplete) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameComplete ? 'GAME COMPLETE!' : gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{(gameOver || gameComplete) && (
<>
<p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p>
<p className="font-pixel text-xs text-foreground/60 mb-3">Length: {snake.length}</p>
</>
)}
<button onClick={(gameOver || gameComplete) ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">
{(gameOver || gameComplete) ? 'PLAY AGAIN' : 'RESUME'}
</button>
</div>
</div>
)}
</motion.div>
);
};
export default Snake;
+347
View File
@@ -0,0 +1,347 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 20;
const TICK_SPEED = 500;
const HIGHSCORE_KEY = 'tetris-highscore';
const MAX_SCORE = 4294967296;
type Board = (string | null)[][];
const TETROMINOS = {
I: { shape: [[1, 1, 1, 1]], color: 'hsl(var(--primary))' },
O: { shape: [[1, 1], [1, 1]], color: 'hsl(var(--primary))' },
T: { shape: [[0, 1, 0], [1, 1, 1]], color: 'hsl(var(--primary))' },
S: { shape: [[0, 1, 1], [1, 1, 0]], color: 'hsl(var(--primary))' },
Z: { shape: [[1, 1, 0], [0, 1, 1]], color: 'hsl(var(--primary))' },
J: { shape: [[1, 0, 0], [1, 1, 1]], color: 'hsl(var(--primary))' },
L: { shape: [[0, 0, 1], [1, 1, 1]], color: 'hsl(var(--primary))' },
};
type TetrominoKey = keyof typeof TETROMINOS;
interface Piece {
shape: number[][];
color: string;
x: number;
y: number;
}
const createBoard = (): Board => Array.from({ length: BOARD_HEIGHT }, () => Array(BOARD_WIDTH).fill(null));
const randomTetromino = (): Piece => {
const keys = Object.keys(TETROMINOS) as TetrominoKey[];
const key = keys[Math.floor(Math.random() * keys.length)];
const tetromino = TETROMINOS[key];
return { shape: tetromino.shape, color: tetromino.color, x: Math.floor(BOARD_WIDTH / 2) - Math.floor(tetromino.shape[0].length / 2), y: 0 };
};
const rotate = (matrix: number[][]): number[][] => {
const rows = matrix.length;
const cols = matrix[0].length;
const result: number[][] = [];
for (let col = 0; col < cols; col++) {
const newRow: number[] = [];
for (let row = rows - 1; row >= 0; row--) newRow.push(matrix[row][col]);
result.push(newRow);
}
return result;
};
const Tetris = () => {
const { playSound } = useSettings();
const [board, setBoard] = useState<Board>(createBoard);
const [piece, setPiece] = useState<Piece>(randomTetromino);
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [lines, setLines] = useState(0);
const [gameOver, setGameOver] = useState(false);
const [gameComplete, setGameComplete] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const gameRef = useRef<HTMLDivElement>(null);
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
const getCellSize = useCallback(() => {
if (typeof window === 'undefined') return 24;
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 40;
const maxHeight = window.innerHeight - 320;
return Math.min(Math.floor(maxWidth / BOARD_WIDTH), Math.floor(maxHeight / BOARD_HEIGHT), 22);
}
return isFullscreen ? 30 : 24;
}, [isFullscreen]);
const [cellSize, setCellSize] = useState(getCellSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCellSize(getCellSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCellSize]);
useEffect(() => {
setCellSize(getCellSize());
}, [isFullscreen, getCellSize]);
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) {
setIsFullscreen(true);
enterFullscreen();
}
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) { setIsFullscreen(true); await enterFullscreen(); }
else { setIsFullscreen(false); await exitFullscreen(); }
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isFullscreen) { setIsFullscreen(false); exitFullscreen(); }
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const isValidMove = useCallback((newPiece: Piece, currentBoard: Board): boolean => {
for (let y = 0; y < newPiece.shape.length; y++) {
for (let x = 0; x < newPiece.shape[y].length; x++) {
if (newPiece.shape[y][x]) {
const newX = newPiece.x + x;
const newY = newPiece.y + y;
if (newX < 0 || newX >= BOARD_WIDTH || newY >= BOARD_HEIGHT) return false;
if (newY >= 0 && currentBoard[newY][newX]) return false;
}
}
}
return true;
}, []);
const mergePiece = useCallback((currentBoard: Board, currentPiece: Piece): Board => {
const newBoard = currentBoard.map(row => [...row]);
for (let y = 0; y < currentPiece.shape.length; y++) {
for (let x = 0; x < currentPiece.shape[y].length; x++) {
if (currentPiece.shape[y][x]) {
const boardY = currentPiece.y + y;
const boardX = currentPiece.x + x;
if (boardY >= 0) newBoard[boardY][boardX] = currentPiece.color;
}
}
}
return newBoard;
}, []);
const clearLines = useCallback((currentBoard: Board): { board: Board; cleared: number } => {
const newBoard = currentBoard.filter(row => row.some(cell => !cell));
const cleared = BOARD_HEIGHT - newBoard.length;
while (newBoard.length < BOARD_HEIGHT) newBoard.unshift(Array(BOARD_WIDTH).fill(null));
return { board: newBoard, cleared };
}, []);
const moveDown = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const newPiece = { ...piece, y: piece.y + 1 };
if (isValidMove(newPiece, board)) {
setPiece(newPiece);
} else {
const mergedBoard = mergePiece(board, piece);
const { board: clearedBoard, cleared } = clearLines(mergedBoard);
if (cleared > 0) {
playSound('success');
setLines(prev => prev + cleared);
setScore(prev => {
const newScore = Math.min(prev + cleared * 100 * cleared, MAX_SCORE);
if (newScore >= MAX_SCORE) setShowGlitchCrash(true);
if (newScore > highScore) { setHighScore(newScore); localStorage.setItem(HIGHSCORE_KEY, newScore.toString()); }
return newScore;
});
} else { playSound('click'); }
setBoard(clearedBoard);
const newTetromino = randomTetromino();
if (!isValidMove(newTetromino, clearedBoard)) { setGameOver(true); playSound('error'); }
else { setPiece(newTetromino); }
}
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, mergePiece, clearLines, playSound, highScore]);
const moveLeft = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const newPiece = { ...piece, x: piece.x - 1 };
if (isValidMove(newPiece, board)) { setPiece(newPiece); playSound('hover'); }
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const moveRight = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const newPiece = { ...piece, x: piece.x + 1 };
if (isValidMove(newPiece, board)) { setPiece(newPiece); playSound('hover'); }
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const rotatePiece = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const rotatedShape = rotate(piece.shape);
const newPiece = { ...piece, shape: rotatedShape };
if (isValidMove(newPiece, board)) { setPiece(newPiece); playSound('hover'); }
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const hardDrop = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
let newPiece = { ...piece };
while (isValidMove({ ...newPiece, y: newPiece.y + 1 }, board)) newPiece.y++;
setPiece(newPiece);
playSound('click');
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const startGame = () => {
setBoard(createBoard());
setPiece(randomTetromino());
setScore(0);
setLines(0);
setGameOver(false);
setGameComplete(false);
setIsPaused(false);
setGameStarted(true);
playSound('success');
gameRef.current?.focus();
};
const togglePause = () => {
if (!gameStarted || gameOver || gameComplete) return;
setIsPaused(prev => !prev);
playSound('click');
};
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!gameStarted) return;
switch (e.key) {
case 'ArrowLeft': case 'a': e.preventDefault(); moveLeft(); break;
case 'ArrowRight': case 'd': e.preventDefault(); moveRight(); break;
case 'ArrowDown': case 's': e.preventDefault(); moveDown(); break;
case 'ArrowUp': case 'w': e.preventDefault(); rotatePiece(); break;
case ' ': e.preventDefault(); hardDrop(); break;
case 'p': e.preventDefault(); togglePause(); break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [moveLeft, moveRight, moveDown, rotatePiece, hardDrop, gameStarted]);
useEffect(() => {
if (!gameStarted || gameOver || gameComplete || isPaused) return;
const interval = setInterval(moveDown, TICK_SPEED);
return () => clearInterval(interval);
}, [moveDown, gameStarted, gameOver, gameComplete, isPaused]);
const renderBoard = () => {
const displayBoard = board.map(row => [...row]);
if (gameStarted && !gameOver && !gameComplete) {
for (let y = 0; y < piece.shape.length; y++) {
for (let x = 0; x < piece.shape[y].length; x++) {
if (piece.shape[y][x]) {
const boardY = piece.y + y;
const boardX = piece.x + x;
if (boardY >= 0 && boardY < BOARD_HEIGHT && boardX >= 0 && boardX < BOARD_WIDTH) displayBoard[boardY][boardX] = piece.color;
}
}
}
}
return displayBoard.map((row, y) => (
<div key={y} className="flex">
{row.map((cell, x) => (
<div key={`${y}-${x}`} className={`border border-primary/20 transition-colors duration-100 ${cell ? 'bg-primary box-glow' : 'bg-background/50'}`} style={{ width: cellSize, height: cellSize }} />
))}
</div>
));
};
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div ref={gameRef} tabIndex={0} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Tetris</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
<div className="border-2 border-primary box-glow p-1 bg-background/80">{renderBoard()}</div>
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">SCORE</p><p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p><p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p><p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LINES</p><p className="font-minecraft text-lg text-primary text-glow">{lines}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p><p className="font-pixel text-[10px] text-foreground/80"> / WASD</p><p className="font-pixel text-[10px] text-foreground/80">Space: Drop</p><p className="font-pixel text-[10px] text-foreground/80">P: Pause</p></div>
{!gameStarted || gameOver || gameComplete ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
) : (
<button onClick={togglePause} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">{isPaused ? 'RESUME' : 'PAUSE'}</button>
)}
</div>
)}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LINES</p><p className="font-minecraft text-sm text-primary">{lines}</p></div>
</div>
{gameStarted && !gameOver && !gameComplete && (
<div className="grid grid-cols-3 gap-1 mt-2">
<div />
<GameTouchButton onAction={rotatePiece} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg" interval={200}></GameTouchButton>
<div />
<GameTouchButton onAction={moveLeft} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<GameTouchButton onAction={hardDrop} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px]" interval={500}>DROP</GameTouchButton>
<GameTouchButton onAction={moveRight} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<button onClick={togglePause} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={moveDown} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
</div>
)}
{(!gameStarted || gameOver || gameComplete) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
)}
</div>
)}
</div>
{!isMobile && (gameOver || isPaused || gameComplete) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameComplete ? 'GAME COMPLETE!' : gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{(gameOver || gameComplete) && (<><p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p><p className="font-pixel text-xs text-foreground/60 mb-3">Lines: {lines}</p></>)}
<button onClick={(gameOver || gameComplete) ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{(gameOver || gameComplete) ? 'PLAY AGAIN' : 'RESUME'}</button>
</div>
</div>
)}
</motion.div>
);
};
export default Tetris;