add Pokémon API integration and team generation features

This commit is contained in:
Matthieu
2025-08-11 22:57:44 +02:00
parent 160aea6128
commit 00bea92154
6 changed files with 1083 additions and 32 deletions

View File

@@ -6,7 +6,8 @@
"Bash(npm install:*)",
"Bash(npm uninstall:*)",
"Bash(rm:*)",
"Bash(npx tailwindcss init:*)"
"Bash(npx tailwindcss init:*)",
"WebFetch(domain:pokeapi.co)"
],
"deny": []
}

83
POKEMON_FEATURES.md Normal file
View File

@@ -0,0 +1,83 @@
# Pokémon API Integration Features
## Overview
The NPC Configuration App now includes comprehensive Pokémon API integration using the [PokéAPI](https://pokeapi.co/) to help you build Pokémon teams for your NPCs.
## New Features
### 1. Form-Based Pokémon Selection 🎯
- **Full Pokémon Dropdown**: Select from all 1010+ Pokémon (Gen 1-9)
- **Level Control**: Set level from 1-100 using slider or number input
- **Individual Move Selection**: Choose up to 4 moves from available movesets
- **Real-time Preview**: See the generated Cobblemon string before adding
### 2. Team Generation Tools ⚡
- **Random Team**: Generate 6 random Pokémon with realistic levels (20-80)
- **Type-based Teams**: Create themed teams (Fire, Water, Grass, Electric, etc.)
- **Quick 3**: Generate smaller teams for testing
### 3. Enhanced UI Components
- **Pokémon Info Display**: Shows artwork, types, stats, and available moves
- **Move Categories**: Includes level-up, TM, and tutor moves
- **Form Validation**: Ensures valid selections before adding
- **Loading States**: Clear feedback during API calls
## How to Use
### Adding Individual Pokémon:
1. Navigate to **Pokemon Party** tab
2. Enable **Battle Configuration** first
3. Click **"Add Pokémon"** button (blue button with search icon)
4. In the form modal:
- Select Pokémon from dropdown
- Adjust level (1-100)
- Choose up to 4 moves
- Preview the result
- Click "Add to Team"
### Quick Team Generation:
- **Random Team**: Click "Random Team" for 6 diverse Pokémon
- **Type Teams**: Use "Generate by Type" dropdown
- **Small Teams**: Click "Quick 3" for testing
### Manual Editing:
- Each Pokémon slot has a text input for manual editing
- Click the 🔍 icon next to any slot to use the form selector
- Use "Add Empty Slot" for manual text entry
## Generated Format
The form automatically creates proper Cobblemon format strings:
```
gastrodon level=44 moves=hydro-pump,rain-dance,mud-bomb,recover
pikachu level=50 moves=thunderbolt,quick-attack,thunder-wave,agility
charizard level=65 moves=flamethrower,dragon-claw,air-slash,roost
```
## API Features
- **Caching**: 10-minute response caching for better performance
- **Error Handling**: Graceful fallbacks for failed requests
- **Move Filtering**: Only shows learnable moves (level-up, TM, tutor)
- **Type Safety**: Full TypeScript support
## Performance
- Lazy loading of Pokémon data
- Efficient move filtering
- Minimal API calls with intelligent caching
- Hot module reloading in development
## Technical Details
### Files Added:
- `src/services/pokemonApi.ts` - API service with caching
- `src/components/PokemonFormSelector.tsx` - Form-based selector
- Enhanced `src/components/NPCPartyBuilder.tsx` - Updated party builder
### Dependencies:
- Uses the free [PokéAPI](https://pokeapi.co/) (no API key required)
- Built with React hooks and TypeScript
- Integrates seamlessly with existing Cobblemon configuration
---
Ready to test at: http://localhost:5173

View File

@@ -1,6 +1,8 @@
import { useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Plus, Trash2, Shuffle, Zap, Search } from 'lucide-react';
import type { NPCConfiguration, NPCPartyProvider, SimplePartyProvider, PoolPartyProvider, PoolEntry } from '../types/npc';
import { pokemonApi } from '../services/pokemonApi';
import { PokemonFormSelector } from './PokemonFormSelector';
interface NPCPartyBuilderProps {
config: NPCConfiguration;
@@ -9,6 +11,9 @@ interface NPCPartyBuilderProps {
export function NPCPartyBuilder({ config, onChange }: NPCPartyBuilderProps) {
const [partyType, setPartyType] = useState<'simple' | 'pool' | 'script'>(config.party?.type || 'simple');
const [showPokemonFormSelector, setShowPokemonFormSelector] = useState(false);
const [selectedPokemonIndex, setSelectedPokemonIndex] = useState<number>(-1);
const [isGenerating, setIsGenerating] = useState(false);
const handlePartyChange = (party: NPCPartyProvider) => {
onChange({ ...config, party });
@@ -30,6 +35,66 @@ export function NPCPartyBuilder({ config, onChange }: NPCPartyBuilderProps) {
}
};
const generateRandomTeam = async (teamSize: number = 6) => {
setIsGenerating(true);
try {
const team = await pokemonApi.generateRandomTeam(teamSize);
const pokemonStrings = team.map(pokemon => pokemonApi.formatToCobblemonString(pokemon));
if (partyType === 'simple') {
handlePartyChange({
type: 'simple',
pokemon: pokemonStrings,
isStatic: (config.party as SimplePartyProvider)?.isStatic
});
}
} catch (error) {
console.error('Failed to generate random team:', error);
} finally {
setIsGenerating(false);
}
};
const generateTeamByType = async (type: string, teamSize: number = 6) => {
setIsGenerating(true);
try {
const team = await pokemonApi.generateTeamByType(type, teamSize);
const pokemonStrings = team.map(pokemon => pokemonApi.formatToCobblemonString(pokemon));
if (partyType === 'simple') {
handlePartyChange({
type: 'simple',
pokemon: pokemonStrings,
isStatic: (config.party as SimplePartyProvider)?.isStatic
});
}
} catch (error) {
console.error(`Failed to generate ${type} team:`, error);
} finally {
setIsGenerating(false);
}
};
const openPokemonFormSelector = (index: number) => {
setSelectedPokemonIndex(index);
setShowPokemonFormSelector(true);
};
const handlePokemonFormSelect = (pokemonString: string) => {
if (partyType === 'simple') {
const party = config.party as SimplePartyProvider;
const newPokemon = [...party.pokemon];
newPokemon[selectedPokemonIndex] = pokemonString;
handlePartyChange({
...party,
pokemon: newPokemon
});
}
setShowPokemonFormSelector(false);
setSelectedPokemonIndex(-1);
};
const renderSimpleParty = () => {
const party = config.party as SimplePartyProvider;
@@ -61,17 +126,85 @@ export function NPCPartyBuilder({ config, onChange }: NPCPartyBuilderProps) {
};
return (
<div className="space-y-3">
<div className="space-y-4">
<div className="flex items-center justify-between">
<h4 className="font-medium">Pokemon List</h4>
<button
type="button"
onClick={addPokemon}
className="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200"
>
<Plus className="h-3 w-3 mr-1" />
Add Pokemon
</button>
<div className="flex gap-2">
<button
type="button"
onClick={addPokemon}
className="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200"
>
<Plus className="h-3 w-3 mr-1" />
Add Empty Slot
</button>
<button
type="button"
onClick={() => {
addPokemon();
const newIndex = (config.party as SimplePartyProvider)?.pokemon?.length || 0;
openPokemonFormSelector(newIndex);
}}
className="inline-flex items-center px-3 py-1 border border-transparent text-xs font-medium rounded text-white bg-indigo-600 hover:bg-indigo-700"
>
<Search className="h-3 w-3 mr-1" />
Add Pokémon
</button>
</div>
</div>
{/* Team Generation Tools */}
<div className="bg-gray-50 p-3 rounded-lg space-y-3">
<h5 className="text-sm font-medium text-gray-700">Team Generation</h5>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => generateRandomTeam(6)}
disabled={isGenerating}
className="inline-flex items-center px-3 py-1 text-xs font-medium rounded-md text-white bg-green-600 hover:bg-green-700 disabled:opacity-50"
>
<Shuffle className="h-3 w-3 mr-1" />
{isGenerating ? 'Generating...' : 'Random Team'}
</button>
<select
onChange={(e) => {
if (e.target.value) {
generateTeamByType(e.target.value, 6);
e.target.value = '';
}
}}
disabled={isGenerating}
className="text-xs border border-gray-300 rounded px-2 py-1 disabled:opacity-50"
>
<option value="">Generate by Type</option>
<option value="fire">Fire Team</option>
<option value="water">Water Team</option>
<option value="grass">Grass Team</option>
<option value="electric">Electric Team</option>
<option value="psychic">Psychic Team</option>
<option value="fighting">Fighting Team</option>
<option value="poison">Poison Team</option>
<option value="ground">Ground Team</option>
<option value="rock">Rock Team</option>
<option value="bug">Bug Team</option>
<option value="ghost">Ghost Team</option>
<option value="steel">Steel Team</option>
<option value="dragon">Dragon Team</option>
<option value="dark">Dark Team</option>
<option value="fairy">Fairy Team</option>
</select>
<button
type="button"
onClick={() => generateRandomTeam(3)}
disabled={isGenerating}
className="inline-flex items-center px-2 py-1 text-xs font-medium rounded text-purple-700 bg-purple-100 hover:bg-purple-200 disabled:opacity-50"
>
<Zap className="h-3 w-3 mr-1" />
Quick 3
</button>
</div>
</div>
{party.pokemon.map((pokemon, index) => (
@@ -83,6 +216,14 @@ export function NPCPartyBuilder({ config, onChange }: NPCPartyBuilderProps) {
className="flex-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm"
placeholder="pikachu level=50 moves=thunderbolt,quick-attack"
/>
<button
type="button"
onClick={() => openPokemonFormSelector(index)}
className="p-1 text-indigo-600 hover:text-indigo-800"
title="Add Pokémon"
>
<Search className="h-4 w-4" />
</button>
<button
type="button"
onClick={() => removePokemon(index)}
@@ -297,30 +438,38 @@ export function NPCPartyBuilder({ config, onChange }: NPCPartyBuilderProps) {
}
return (
<div className="space-y-6">
<h2 className="text-xl font-semibold text-gray-900">Pokemon Party</h2>
<>
<div className="space-y-6">
<h2 className="text-xl font-semibold text-gray-900">Pokemon Party</h2>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Party Type</label>
<div className="flex space-x-4">
{(['simple', 'pool', 'script'] as const).map((type) => (
<label key={type} className="inline-flex items-center">
<input
type="radio"
value={type}
checked={partyType === type}
onChange={(e) => handlePartyTypeChange(e.target.value as 'simple' | 'pool' | 'script')}
className="form-radio"
/>
<span className="ml-2 capitalize">{type}</span>
</label>
))}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Party Type</label>
<div className="flex space-x-4">
{(['simple', 'pool', 'script'] as const).map((type) => (
<label key={type} className="inline-flex items-center">
<input
type="radio"
value={type}
checked={partyType === type}
onChange={(e) => handlePartyTypeChange(e.target.value as 'simple' | 'pool' | 'script')}
className="form-radio"
/>
<span className="ml-2 capitalize">{type}</span>
</label>
))}
</div>
</div>
{partyType === 'simple' && renderSimpleParty()}
{partyType === 'pool' && renderPoolParty()}
{partyType === 'script' && renderScriptParty()}
</div>
{partyType === 'simple' && renderSimpleParty()}
{partyType === 'pool' && renderPoolParty()}
{partyType === 'script' && renderScriptParty()}
</div>
<PokemonFormSelector
isOpen={showPokemonFormSelector}
onSelect={handlePokemonFormSelect}
onClose={() => setShowPokemonFormSelector(false)}
/>
</>
);
}

View File

@@ -0,0 +1,304 @@
import { useState, useEffect } from 'react';
import { X, Loader } from 'lucide-react';
import { pokemonApi, type PokemonListItem, type Pokemon } from '../services/pokemonApi';
interface PokemonFormData {
pokemon: string;
level: number;
moves: string[];
}
interface PokemonFormSelectorProps {
onSelect: (pokemonString: string) => void;
onClose: () => void;
isOpen: boolean;
}
export function PokemonFormSelector({ onSelect, onClose, isOpen }: PokemonFormSelectorProps) {
const [allPokemon, setAllPokemon] = useState<PokemonListItem[]>([]);
const [selectedPokemon, setSelectedPokemon] = useState<Pokemon | null>(null);
const [isLoadingMoves, setIsLoadingMoves] = useState(false);
const [availableMoves, setAvailableMoves] = useState<string[]>([]);
const [formData, setFormData] = useState<PokemonFormData>({
pokemon: '',
level: 50,
moves: ['', '', '', '']
});
// Load all Pokemon on component mount
useEffect(() => {
const loadAllPokemon = async () => {
try {
const response = await pokemonApi.getAllPokemon(1010); // Gen 1-9
setAllPokemon(response.results);
} catch (error) {
console.error('Failed to load Pokemon list:', error);
}
};
if (isOpen && allPokemon.length === 0) {
loadAllPokemon();
}
}, [isOpen, allPokemon.length]);
// Load Pokemon details when Pokemon is selected
useEffect(() => {
const loadPokemonDetails = async () => {
if (!formData.pokemon) {
setSelectedPokemon(null);
setAvailableMoves([]);
return;
}
setIsLoadingMoves(true);
try {
const pokemon = await pokemonApi.getPokemon(formData.pokemon);
setSelectedPokemon(pokemon);
// Get all moves the Pokemon can learn
const moves = pokemon.moves
.filter(moveData =>
moveData.version_group_details.some(detail =>
detail.move_learn_method.name === 'level-up' ||
detail.move_learn_method.name === 'machine' ||
detail.move_learn_method.name === 'tutor'
)
)
.map(moveData => moveData.move.name)
.sort();
setAvailableMoves(moves);
} catch (error) {
console.error('Failed to load Pokemon details:', error);
setSelectedPokemon(null);
setAvailableMoves([]);
} finally {
setIsLoadingMoves(false);
}
};
loadPokemonDetails();
}, [formData.pokemon]);
const handlePokemonChange = (pokemonName: string) => {
setFormData(prev => ({
...prev,
pokemon: pokemonName,
moves: ['', '', '', ''] // Reset moves when Pokemon changes
}));
};
const handleLevelChange = (level: number) => {
setFormData(prev => ({ ...prev, level }));
};
const handleMoveChange = (index: number, move: string) => {
setFormData(prev => {
const newMoves = [...prev.moves];
newMoves[index] = move;
return { ...prev, moves: newMoves };
});
};
const handleSubmit = () => {
if (!formData.pokemon) return;
// Filter out empty moves
const selectedMoves = formData.moves.filter(move => move !== '');
const movesString = selectedMoves.length > 0 ? ` moves=${selectedMoves.join(',')}` : '';
const pokemonString = `${formData.pokemon} level=${formData.level}${movesString}`;
onSelect(pokemonString);
handleClose();
};
const handleClose = () => {
setFormData({
pokemon: '',
level: 50,
moves: ['', '', '', '']
});
setSelectedPokemon(null);
setAvailableMoves([]);
onClose();
};
const isFormValid = formData.pokemon !== '';
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-lg font-semibold">Add Pokémon to Team</h2>
<button
onClick={handleClose}
className="p-1 hover:bg-gray-100 rounded"
>
<X className="h-5 w-5" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-4 space-y-6">
{/* Pokemon Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Select Pokémon *
</label>
<select
value={formData.pokemon}
onChange={(e) => handlePokemonChange(e.target.value)}
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
>
<option value="">Choose a Pokémon...</option>
{allPokemon.map((pokemon) => (
<option key={pokemon.name} value={pokemon.name}>
{pokemon.name.charAt(0).toUpperCase() + pokemon.name.slice(1)}
</option>
))}
</select>
</div>
{/* Pokemon Info */}
{selectedPokemon && (
<div className="bg-gray-50 p-4 rounded-lg">
<div className="flex items-center mb-3">
{selectedPokemon.sprites.other?.['official-artwork']?.front_default && (
<img
src={selectedPokemon.sprites.other['official-artwork'].front_default}
alt={selectedPokemon.name}
className="w-16 h-16 mr-4"
/>
)}
<div>
<h3 className="text-lg font-bold capitalize">{selectedPokemon.name}</h3>
<div className="flex gap-2 mt-1">
{selectedPokemon.types.map((type) => (
<span
key={type.slot}
className="px-2 py-1 bg-white border text-xs rounded capitalize"
>
{type.type.name}
</span>
))}
</div>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-2 gap-2 text-xs">
<div>Height: {selectedPokemon.height / 10}m</div>
<div>Weight: {selectedPokemon.weight / 10}kg</div>
<div>Base Experience: {selectedPokemon.base_experience}</div>
<div>Available Moves: {availableMoves.length}</div>
</div>
</div>
)}
{/* Level Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Level: {formData.level}
</label>
<div className="flex items-center gap-4">
<input
type="range"
min="1"
max="100"
value={formData.level}
onChange={(e) => handleLevelChange(parseInt(e.target.value))}
className="flex-1"
/>
<input
type="number"
min="1"
max="100"
value={formData.level}
onChange={(e) => handleLevelChange(parseInt(e.target.value) || 1)}
className="w-16 border border-gray-300 rounded px-2 py-1 text-sm"
/>
</div>
</div>
{/* Move Selection */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Moves (Optional - up to 4)
</label>
{isLoadingMoves ? (
<div className="flex items-center justify-center py-8">
<Loader className="h-5 w-5 animate-spin text-indigo-600" />
<span className="ml-2 text-sm text-gray-600">Loading available moves...</span>
</div>
) : (
<div className="space-y-3">
{formData.moves.map((selectedMove, index) => (
<div key={index}>
<label className="block text-xs font-medium text-gray-600 mb-1">
Move {index + 1}
</label>
<select
value={selectedMove}
onChange={(e) => handleMoveChange(index, e.target.value)}
disabled={availableMoves.length === 0}
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent disabled:bg-gray-100"
>
<option value="">No move</option>
{availableMoves.map((move) => (
<option key={move} value={move}>
{move.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
</option>
))}
</select>
</div>
))}
{availableMoves.length === 0 && selectedPokemon && (
<p className="text-sm text-gray-500 italic">
No moves available for this Pokémon
</p>
)}
</div>
)}
</div>
{/* Preview */}
{isFormValid && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Preview
</label>
<div className="bg-gray-100 p-3 rounded border font-mono text-sm">
{formData.pokemon} level={formData.level}
{formData.moves.filter(m => m !== '').length > 0 && (
<span> moves={formData.moves.filter(m => m !== '').join(',')}</span>
)}
</div>
</div>
)}
</div>
{/* Footer */}
<div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
<button
onClick={handleClose}
className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded transition-colors"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={!isFormValid || isLoadingMoves}
className="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Add to Team
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,265 @@
import { useState, useEffect, useRef } from 'react';
import { Search, Loader, X } from 'lucide-react';
import { pokemonApi, type PokemonListItem, type Pokemon } from '../services/pokemonApi';
interface PokemonSelectorProps {
onSelect: (pokemonString: string) => void;
onClose: () => void;
isOpen: boolean;
}
export function PokemonSelector({ onSelect, onClose, isOpen }: PokemonSelectorProps) {
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<PokemonListItem[]>([]);
const [selectedPokemon, setSelectedPokemon] = useState<Pokemon | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [level, setLevel] = useState(50);
const [selectedMoves, setSelectedMoves] = useState<string[]>([]);
const searchInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (isOpen && searchInputRef.current) {
searchInputRef.current.focus();
}
}, [isOpen]);
useEffect(() => {
const searchPokemon = async () => {
if (searchQuery.length < 2) {
setSearchResults([]);
return;
}
setIsSearching(true);
try {
const results = await pokemonApi.searchPokemon(searchQuery, 10);
setSearchResults(results);
} catch (error) {
console.error('Search failed:', error);
setSearchResults([]);
} finally {
setIsSearching(false);
}
};
const timeoutId = setTimeout(searchPokemon, 300);
return () => clearTimeout(timeoutId);
}, [searchQuery]);
const handlePokemonSelect = async (pokemonItem: PokemonListItem) => {
setIsLoading(true);
try {
const pokemon = await pokemonApi.getPokemon(pokemonItem.name);
setSelectedPokemon(pokemon);
setSearchResults([]);
setSearchQuery('');
// Auto-select some random moves
const levelMoves = pokemon.moves
.filter(moveData =>
moveData.version_group_details.some(detail =>
detail.move_learn_method.name === 'level-up'
)
)
.map(moveData => moveData.move.name);
const randomMoves = levelMoves
.sort(() => Math.random() - 0.5)
.slice(0, 4);
setSelectedMoves(randomMoves);
} catch (error) {
console.error('Failed to load pokemon:', error);
} finally {
setIsLoading(false);
}
};
const handleConfirm = () => {
if (selectedPokemon) {
const moves = selectedMoves.length > 0 ? ` moves=${selectedMoves.join(',')}` : '';
const pokemonString = `${selectedPokemon.name} level=${level}${moves}`;
onSelect(pokemonString);
handleClose();
}
};
const handleClose = () => {
setSearchQuery('');
setSearchResults([]);
setSelectedPokemon(null);
setSelectedMoves([]);
setLevel(50);
onClose();
};
const toggleMove = (move: string) => {
if (selectedMoves.includes(move)) {
setSelectedMoves(selectedMoves.filter(m => m !== move));
} else if (selectedMoves.length < 4) {
setSelectedMoves([...selectedMoves, move]);
}
};
const availableMoves = selectedPokemon?.moves
.filter(moveData =>
moveData.version_group_details.some(detail =>
detail.move_learn_method.name === 'level-up'
)
)
.map(moveData => moveData.move.name)
.sort() || [];
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-lg font-semibold">Select a Pokémon</h2>
<button
onClick={handleClose}
className="p-1 hover:bg-gray-100 rounded"
>
<X className="h-5 w-5" />
</button>
</div>
<div className="flex-1 overflow-hidden flex flex-col">
{!selectedPokemon ? (
// Search Phase
<div className="p-4 flex-1 flex flex-col">
<div className="relative mb-4">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
ref={searchInputRef}
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search for a Pokémon..."
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
/>
{isSearching && (
<Loader className="absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
)}
</div>
{searchResults.length > 0 && (
<div className="border rounded-md max-h-64 overflow-y-auto">
{searchResults.map((pokemon) => (
<button
key={pokemon.name}
onClick={() => handlePokemonSelect(pokemon)}
className="w-full text-left px-4 py-2 hover:bg-gray-50 border-b last:border-b-0 flex items-center justify-between"
>
<span className="capitalize font-medium">{pokemon.name}</span>
</button>
))}
</div>
)}
{searchQuery.length >= 2 && searchResults.length === 0 && !isSearching && (
<p className="text-gray-500 text-center py-4">No Pokémon found</p>
)}
{isLoading && (
<div className="flex items-center justify-center py-8">
<Loader className="h-6 w-6 animate-spin text-indigo-600" />
<span className="ml-2">Loading Pokémon details...</span>
</div>
)}
</div>
) : (
// Configuration Phase
<div className="p-4 flex-1 flex flex-col overflow-hidden">
<div className="flex items-center mb-4">
{selectedPokemon.sprites.other?.['official-artwork']?.front_default && (
<img
src={selectedPokemon.sprites.other['official-artwork'].front_default}
alt={selectedPokemon.name}
className="w-16 h-16 mr-4"
/>
)}
<div>
<h3 className="text-xl font-bold capitalize">{selectedPokemon.name}</h3>
<div className="flex gap-2 mt-1">
{selectedPokemon.types.map((type) => (
<span
key={type.slot}
className="px-2 py-1 bg-gray-100 text-xs rounded capitalize"
>
{type.type.name}
</span>
))}
</div>
</div>
</div>
{/* Level */}
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-1">
Level: {level}
</label>
<input
type="range"
min="1"
max="100"
value={level}
onChange={(e) => setLevel(parseInt(e.target.value))}
className="w-full"
/>
</div>
{/* Moves */}
<div className="flex-1 overflow-hidden">
<label className="block text-sm font-medium text-gray-700 mb-2">
Moves ({selectedMoves.length}/4)
</label>
<div className="border rounded-md p-2 max-h-40 overflow-y-auto">
<div className="grid grid-cols-2 gap-1">
{availableMoves.map((move) => (
<button
key={move}
onClick={() => toggleMove(move)}
disabled={selectedMoves.length >= 4 && !selectedMoves.includes(move)}
className={`text-left px-2 py-1 text-xs rounded transition-colors ${
selectedMoves.includes(move)
? 'bg-indigo-100 text-indigo-800'
: selectedMoves.length >= 4
? 'text-gray-400 cursor-not-allowed'
: 'hover:bg-gray-50'
}`}
>
{move.replace('-', ' ')}
</button>
))}
</div>
</div>
</div>
</div>
)}
</div>
{/* Footer */}
{selectedPokemon && (
<div className="flex justify-end gap-2 p-4 border-t">
<button
onClick={() => setSelectedPokemon(null)}
className="px-4 py-2 text-gray-600 hover:bg-gray-50 rounded"
>
Back
</button>
<button
onClick={handleConfirm}
className="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700"
>
Add to Team
</button>
</div>
)}
</div>
</div>
);
}

249
src/services/pokemonApi.ts Normal file
View File

@@ -0,0 +1,249 @@
const POKEMON_API_BASE = 'https://pokeapi.co/api/v2';
export interface PokemonListItem {
name: string;
url: string;
}
export interface PokemonListResponse {
count: number;
next: string | null;
previous: string | null;
results: PokemonListItem[];
}
export interface PokemonType {
slot: number;
type: {
name: string;
url: string;
};
}
export interface PokemonStat {
base_stat: number;
effort: number;
stat: {
name: string;
url: string;
};
}
export interface PokemonSprites {
front_default: string | null;
front_shiny: string | null;
other?: {
'official-artwork'?: {
front_default: string | null;
};
};
}
export interface PokemonMove {
move: {
name: string;
url: string;
};
version_group_details: {
level_learned_at: number;
move_learn_method: {
name: string;
};
version_group: {
name: string;
};
}[];
}
export interface Pokemon {
id: number;
name: string;
height: number;
weight: number;
base_experience: number;
types: PokemonType[];
stats: PokemonStat[];
sprites: PokemonSprites;
moves: PokemonMove[];
}
export interface CobblemonPokemon {
name: string;
level: number;
moves: string[];
displayName?: string;
}
class PokemonApiService {
private cache = new Map<string, any>();
private readonly CACHE_EXPIRY = 10 * 60 * 1000; // 10 minutes
private async fetchWithCache<T>(url: string): Promise<T> {
const cacheKey = url;
const cached = this.cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < this.CACHE_EXPIRY) {
return cached.data;
}
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
this.cache.set(cacheKey, { data, timestamp: Date.now() });
return data;
} catch (error) {
console.error('Pokemon API fetch error:', error);
throw error;
}
}
async getAllPokemon(limit: number = 1000): Promise<PokemonListResponse> {
return this.fetchWithCache<PokemonListResponse>(`${POKEMON_API_BASE}/pokemon?limit=${limit}`);
}
async searchPokemon(query: string, limit: number = 20): Promise<PokemonListItem[]> {
const allPokemon = await this.getAllPokemon();
const filtered = allPokemon.results
.filter(pokemon => pokemon.name.toLowerCase().includes(query.toLowerCase()))
.slice(0, limit);
return filtered;
}
async getPokemon(nameOrId: string | number): Promise<Pokemon> {
return this.fetchWithCache<Pokemon>(`${POKEMON_API_BASE}/pokemon/${nameOrId}`);
}
async getRandomPokemon(): Promise<Pokemon> {
const randomId = Math.floor(Math.random() * 1010) + 1; // Gen 1-9 Pokemon
return this.getPokemon(randomId);
}
async generateRandomTeam(teamSize: number = 6): Promise<CobblemonPokemon[]> {
const team: CobblemonPokemon[] = [];
const usedPokemon = new Set<number>();
for (let i = 0; i < teamSize; i++) {
let pokemon: Pokemon;
let attempts = 0;
do {
pokemon = await this.getRandomPokemon();
attempts++;
} while (usedPokemon.has(pokemon.id) && attempts < 50);
if (attempts >= 50) {
break; // Prevent infinite loop
}
usedPokemon.add(pokemon.id);
const level = this.generateRandomLevel();
const moves = this.selectRandomMoves(pokemon, 4);
team.push({
name: pokemon.name,
level,
moves,
displayName: this.formatPokemonName(pokemon.name)
});
}
return team;
}
formatToCobblemonString(pokemon: CobblemonPokemon): string {
const moves = pokemon.moves.length > 0 ? ` moves=${pokemon.moves.join(',')}` : '';
return `${pokemon.name} level=${pokemon.level}${moves}`;
}
private generateRandomLevel(): number {
// Generate levels between 20 and 80 with higher probability for mid-range
const min = 20;
const max = 80;
const avg = (min + max) / 2;
const stdDev = (max - min) / 6;
// Simple normal distribution approximation
let level = Math.round(avg + stdDev * (Math.random() + Math.random() + Math.random() - 1.5));
return Math.max(min, Math.min(max, level));
}
private selectRandomMoves(pokemon: Pokemon, count: number): string[] {
// Filter moves that can be learned by leveling up
const levelMoves = pokemon.moves
.filter(moveData =>
moveData.version_group_details.some(detail =>
detail.move_learn_method.name === 'level-up' &&
detail.level_learned_at > 0
)
)
.map(moveData => moveData.move.name);
if (levelMoves.length === 0) {
// If no level moves, use any moves
const allMoves = pokemon.moves.map(moveData => moveData.move.name);
return this.shuffleArray(allMoves).slice(0, count);
}
return this.shuffleArray(levelMoves).slice(0, count);
}
private shuffleArray<T>(array: T[]): T[] {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
private formatPokemonName(name: string): string {
return name.charAt(0).toUpperCase() + name.slice(1);
}
async generateTeamByType(type: string, teamSize: number = 6): Promise<CobblemonPokemon[]> {
try {
const typeResponse = await this.fetchWithCache<any>(`${POKEMON_API_BASE}/type/${type.toLowerCase()}`);
const pokemonOfType = typeResponse.pokemon.map((p: any) => p.pokemon);
if (pokemonOfType.length === 0) {
throw new Error(`No Pokemon found for type: ${type}`);
}
const team: CobblemonPokemon[] = [];
const selectedPokemon = this.shuffleArray(pokemonOfType).slice(0, teamSize);
for (const pokemonRef of selectedPokemon) {
try {
const pokemonData = pokemonRef as { name: string; pokemon: { name: string; url: string } };
const pokemon = await this.getPokemon(pokemonData.pokemon.name);
const level = this.generateRandomLevel();
const moves = this.selectRandomMoves(pokemon, 4);
team.push({
name: pokemon.name,
level,
moves,
displayName: this.formatPokemonName(pokemon.name)
});
} catch (error) {
const pokemonData = pokemonRef as { pokemon: { name: string } };
console.warn(`Failed to fetch pokemon ${pokemonData.pokemon.name}:`, error);
}
}
return team;
} catch (error) {
console.error(`Failed to generate team for type ${type}:`, error);
// Fallback to random team
return this.generateRandomTeam(teamSize);
}
}
}
export const pokemonApi = new PokemonApiService();