To enhance your Pokémon TCG Random Card Picker to simulate opening a pack with the correct number of cards and types, we'll implement the following features:
-
Pack Structure:
- Energy Cards: 1 per pack
- Normal Cards: 6 per pack (Pokémon or Trainer cards)
- Reverse Holographic Cards: 2 per pack
- Rare or Higher Cards: 1 per pack
-
Ordering:
- Display cards in the order: Energy → Normal → Reverse Holo → Rare
-
Dynamic Handling Based on Sets:
- While most sets follow a standard pack structure, you can adjust the distribution per set if needed.
-
UI Enhancements:
- Replace the single card display with a deck layout to show multiple cards per pack.
- Add a "Open Pack" button instead of "Pick a Card."
-
Performance Optimization:
- Cache fetched cards to minimize API calls when opening multiple packs.
Below is the improved code incorporating these features:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pokémon TCG Random Pack Opener</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
text-align: center;
padding: 20px;
}
h1 {
color: #2a75bb;
margin-bottom: 20px;
}
/* Set Selection Modal Styles */
#setModal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0,0,0,0.8); /* Black w/ opacity */
}
#setModalContent {
background-color: #fff;
margin: 5% auto; /* 5% from top and centered */
padding: 20px;
border: 1px solid #888;
width: 90%;
max-width: 1200px; /* Could be more or less, depending on screen size */
border-radius: 10px;
}
#closeModal {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
#closeModal:hover,
#closeModal:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
/* Set Grid Styles */
#setGrid {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
max-height: 70vh;
overflow-y: auto;
}
.setCard {
width: 150px;
cursor: pointer;
border: 2px solid transparent;
border-radius: 8px;
transition: transform 0.2s, border-color 0.2s;
}
.setCard:hover {
transform: scale(1.05);
border-color: #2a75bb;
}
.setCard img {
width: 100%;
height: auto;
border-radius: 8px;
}
.selectedSetInfo {
margin: 20px 0;
}
#openPackButton {
background-color: #ffcb05;
color: #2a75bb;
border: none;
padding: 15px 30px;
font-size: 18px;
cursor: pointer;
border-radius: 8px;
transition: background-color 0.3s;
}
#openPackButton:hover {
background-color: #f2b807;
}
#cardContainer {
display: none;
margin-top: 30px;
}
#cardGrid {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
}
.card {
width: 150px;
text-align: center;
border: 1px solid #ddd;
border-radius: 8px;
background-color: #fff;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.card img {
width: 100%;
height: auto;
border-radius: 5px;
}
.card-details {
font-size: 14px;
color: #333;
margin-top: 10px;
}
.loading {
font-size: 20px;
color: #555;
margin-top: 20px;
}
.error {
font-size: 20px;
color: red;
margin-top: 20px;
}
/* Responsive Design */
@media (max-width: 600px) {
.card {
width: 45%;
}
#cardGrid {
flex-direction: column;
align-items: center;
}
}
</style>
</head>
<body>
<h1>Pokémon TCG Random Pack Opener</h1>
<!-- Button to Open Set Selection Modal -->
<button id="openSetModalButton" style="background-color: #2a75bb; color: #fff; border: none; padding: 10px 20px; font-size: 16px; cursor: pointer; border-radius: 5px; transition: background-color 0.3s;">
Select a Set
</button>
<!-- Set Selection Modal -->
<div id="setModal">
<div id="setModalContent">
<span id="closeModal">×</span>
<h2>Select a Pokémon TCG Set</h2>
<div id="setGrid">
<!-- Dynamically populated set cards will appear here -->
</div>
</div>
</div>
<!-- Display Selected Set Info -->
<div class="selectedSetInfo" id="selectedSetInfo">
<h3>Selected Set: <span id="selectedSetName">None</span></h3>
</div>
<!-- Open Pack Button -->
<button id="openPackButton" disabled>Open a Pack</button>
<!-- Pack Display Container -->
<div id="cardContainer">
<h2>Your Pack:</h2>
<div id="cardGrid">
<!-- Pack cards will appear here -->
</div>
</div>
<!-- Status Message -->
<div id="statusMessage"></div>
<script>
const openSetModalButton = document.getElementById('openSetModalButton');
const setModal = document.getElementById('setModal');
const closeModal = document.getElementById('closeModal');
const setGrid = document.getElementById('setGrid');
const selectedSetInfo = document.getElementById('selectedSetInfo');
const selectedSetName = document.getElementById('selectedSetName');
const openPackButton = document.getElementById('openPackButton');
const cardContainer = document.getElementById('cardContainer');
const cardGrid = document.getElementById('cardGrid');
const statusMessage = document.getElementById('statusMessage');
let selectedSetId = '';
let selectedSetNameText = '';
let cachedCards = []; // Cache for all cards in the selected set
// Function to Open Set Selection Modal
function openSetModal() {
setModal.style.display = 'block';
}
// Function to Close Set Selection Modal
function closeSetModalFunc() {
setModal.style.display = 'none';
}
// When the user clicks the button, open the modal
openSetModalButton.addEventListener('click', openSetModal);
// When the user clicks on <span> (x), close the modal
closeModal.addEventListener('click', closeSetModalFunc);
// When the user clicks anywhere outside of the modal, close it
window.addEventListener('click', function(event) {
if (event.target == setModal) {
setModal.style.display = 'none';
}
});
// Function to Fetch All Available Sets
async function fetchSets() {
try {
statusMessage.textContent = "Loading sets...";
statusMessage.className = "loading";
const response = await fetch('https://api.pokemontcg.io/v2/sets?pageSize=250'); // Adjust pageSize as needed
if (!response.ok) throw new Error('Failed to fetch sets.');
const data = await response.json();
const sets = data.data;
// Sort sets by release date (optional)
sets.sort((a, b) => new Date(a.releaseDate) - new Date(b.releaseDate));
populateSetGrid(sets);
statusMessage.textContent = "";
} catch (error) {
console.error(error);
statusMessage.textContent = "Failed to load sets. Please refresh the page.";
statusMessage.className = "error";
}
}
// Function to Populate the Set Grid in Modal
function populateSetGrid(sets) {
sets.forEach(set => {
const setCard = document.createElement('div');
setCard.className = 'setCard';
setCard.title = set.name;
const img = document.createElement('img');
img.src = set.images.logo || 'https://via.placeholder.com/150?text=No+Image';
img.alt = set.name;
// Handle Image Load Errors
img.onerror = function() {
this.src = 'https://via.placeholder.com/150?text=No+Image';
};
// Click Event to Select Set
setCard.addEventListener('click', function() {
selectedSetId = set.id;
selectedSetNameText = set.name;
selectedSetName.textContent = set.name;
openPackButton.disabled = false;
closeSetModalFunc();
fetchAndCacheCards(set.id);
});
setCard.appendChild(img);
setGrid.appendChild(setCard);
});
}
// Function to Fetch and Cache All Cards in Selected Set
async function fetchAndCacheCards(setId) {
try {
statusMessage.textContent = "Loading cards...";
statusMessage.className = "loading";
cardGrid.innerHTML = "";
cardContainer.style.display = "none";
let allCards = [];
let page = 1;
const pageSize = 250; // Maximum allowed by API
let totalPages = 1;
// Initial fetch to get total count
const initialResponse = await fetch(`https://api.pokemontcg.io/v2/cards?q=set.id:"${setId}"&page=${page}&pageSize=${pageSize}`);
if (!initialResponse.ok) throw new Error('Failed to fetch cards.');
const initialData = await initialResponse.json();
allCards = allCards.concat(initialData.data);
const totalCards = initialData.totalCount;
totalPages = Math.ceil(totalCards / pageSize);
// Fetch remaining pages if any
while (page < totalPages) {
page++;
const response = await fetch(`https://api.pokemontcg.io/v2/cards?q=set.id:"${setId}"&page=${page}&pageSize=${pageSize}`);
if (!response.ok) throw new Error('Failed to fetch cards.');
const data = await response.json();
allCards = allCards.concat(data.data);
}
cachedCards = allCards;
statusMessage.textContent = "";
} catch (error) {
console.error(error);
statusMessage.textContent = "Failed to load cards. Please try selecting the set again.";
statusMessage.className = "error";
}
}
// Function to Categorize Cards
function categorizeCards(cards) {
const energyCards = cards.filter(card => card.supertype === 'Energy');
const normalCards = cards.filter(card => card.supertype !== 'Energy' && card.rarity !== 'Rare' && card.rarity !== 'None');
const reverseHoloCards = cards.filter(card => card.rarity.startsWith('Holo') && card.images && card.images.large);
const rareCards = cards.filter(card => card.rarity === 'Rare' || card.rarity === 'Ultra Rare' || card.rarity === 'Rare Holo');
return { energyCards, normalCards, reverseHoloCards, rareCards };
}
// Function to Get Random Element from Array
function getRandomElement(arr) {
if (arr.length === 0) return null;
const randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
// Function to Open a Pack
function openPack() {
if (!selectedSetId || cachedCards.length === 0) {
alert("Please select a set first.");
return;
}
const { energyCards, normalCards, reverseHoloCards, rareCards } = categorizeCards(cachedCards);
// Define pack structure
const pack = {
energy: getRandomElement(energyCards),
normal: [],
reverseHolo: [],
rare: getRandomElement(rareCards)
};
// Select 6 Normal Cards
for (let i = 0; i < 6; i++) {
const card = getRandomElement(normalCards);
if (card) {
pack.normal.push(card);
}
}
// Select 2 Reverse Holo Cards
for (let i = 0; i < 2; i++) {
const card = getRandomElement(reverseHoloCards);
if (card) {
pack.reverseHolo.push(card);
}
}
displayPack(pack);
}
// Function to Display the Pack
function displayPack(pack) {
cardGrid.innerHTML = ""; // Clear previous pack
cardContainer.style.display = "block";
// Function to create card HTML
function createCardElement(card, category) {
const cardDiv = document.createElement('div');
cardDiv.className = 'card';
const img = document.createElement('img');
img.src = (card.images && card.images.large) ? card.images.large : 'https://via.placeholder.com/150?text=No+Image';
img.alt = card.name;
// Handle Image Load Errors
img.onerror = function() {
this.src = 'https://via.placeholder.com/150?text=No+Image';
};
const details = document.createElement('div');
details.className = 'card-details';
details.innerHTML = `
<strong>${card.name}</strong> <br>
<strong>Type:</strong> ${card.types ? card.types.join(', ') : 'N/A'} <br>
<strong>Rarity:</strong> ${card.rarity || 'N/A'}
`;
cardDiv.appendChild(img);
cardDiv.appendChild(details);
// Optional: Add category label
const categoryLabel = document.createElement('div');
categoryLabel.style.position = 'absolute';
categoryLabel.style.backgroundColor = '#fff';
categoryLabel.style.padding = '2px 5px';
categoryLabel.style.borderRadius = '3px';
categoryLabel.style.fontSize = '12px';
categoryLabel.style.fontWeight = 'bold';
categoryLabel.style.top = '10px';
categoryLabel.style.left = '10px';
categoryLabel.innerText = category;
cardDiv.style.position = 'relative';
cardDiv.appendChild(categoryLabel);
return cardDiv;
}
// Add Energy Card
if (pack.energy) {
const energyElement = createCardElement(pack.energy, 'Energy');
cardGrid.appendChild(energyElement);
}
// Add Normal Cards
pack.normal.forEach(card => {
const normalElement = createCardElement(card, 'Normal');
cardGrid.appendChild(normalElement);
});
// Add Reverse Holo Cards
pack.reverseHolo.forEach(card => {
const reverseHoloElement = createCardElement(card, 'Reverse Holo');
cardGrid.appendChild(reverseHoloElement);
});
// Add Rare Card
if (pack.rare) {
const rareElement = createCardElement(pack.rare, 'Rare');
cardGrid.appendChild(rareElement);
}
}
// Event Listener for Open Pack Button
openPackButton.addEventListener('click', openPack);
// Fetch Sets on Page Load
window.onload = fetchSets;
</script>
</body>
</html>
Explanation of Enhancements:
-
UI Changes:
- Open Pack Button: Replaced the "Pick a Pokémon Card" button with an "Open a Pack" button.
- Pack Display: Introduced a
cardGrid within cardContainer to display multiple cards per pack in a grid layout.
-
Fetching and Caching Cards:
- Upon selecting a set, all cards from that set are fetched and cached to minimize API calls when opening multiple packs.
- Cards are fetched in batches (
pageSize=250) to ensure complete retrieval even for large sets.
-
Categorizing Cards:
- Energy Cards: Identified by
supertype === 'Energy'.
- Normal Cards: Cards that are neither Energy nor Rare.
- Reverse Holo Cards: Cards with
rarity starting with 'Holo' and having images.
- Rare Cards: Cards with
rarity classified as 'Rare', 'Ultra Rare', or 'Rare Holo'.
-
Pack Opening Logic:
- Energy: 1 card per pack.
- Normal: 6 cards per pack.
- Reverse Holo: 2 cards per pack.
- Rare: 1 card per pack.
- These numbers can be adjusted based on the specific set's pack structure if necessary.
-
Displaying the Pack:
- Cards are displayed in the order: Energy → Normal → Reverse Holo → Rare.
- Each card displays its image, name, type, and rarity.
- An optional category label is added to each card for clarity.
-
Error Handling:
- Alerts the user if no set is selected.
- Displays error messages if fetching sets or cards fails.
-
Responsive Design:
- Ensures that the pack display is responsive on smaller screens by adjusting card sizes and grid layout.
Potential Further Enhancements:
- Dynamic Pack Structures: Allow individual set configurations for pack compositions as different sets might have varying pack structures.
- Multiple Pack Openings: Enable opening multiple packs at once with cumulative displays.
- Advanced Filtering: Allow users to filter cards based on specific types, subtypes, or rarities when selecting a pack.
- Saving Collection: Implement a feature to save opened cards to a personal collection for future reference.
- Animations: Add animations when opening a pack for a better user experience.
Conclusion
This enhanced script transforms your application from picking a single card to simulating the opening of a Pokémon TCG pack with a structured and ordered set of cards. It maintains flexibility for different sets and ensures a user-friendly experience with clear categorizations and responsive design.