To enhance your Pokémon TCG Random Card Picker and enable the functionality to open full Pokémon packs with real probabilities and rarities, we'll implement the following features:
-
Fetch and Categorize Cards by Rarity:
- When a set is selected, fetch all cards in that set and categorize them based on their rarity.
-
Define Pack Structure:
- Define the structure of a Pokémon pack (e.g., number of Common, Uncommon, Rare, etc.).
-
Simulate Pack Opening:
- Randomly select cards from each rarity category based on the defined pack structure, ensuring real probability distributions.
-
Display Pack Contents:
- Show all cards in the opened pack with their details.
Below is the improved version of your script incorporating these features:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pokémon TCG Pack Opener</title>
<style>
/* (Existing styles remain unchanged) */
/* New Styles for Pack Display */
#packContainer {
display: none;
margin-top: 30px;
}
.pack-card {
width: 150px;
display: inline-block;
margin: 10px;
border: 2px solid #ccc;
border-radius: 8px;
box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
transition: transform 0.2s;
}
.pack-card:hover {
transform: scale(1.05);
border-color: #2a75bb;
}
.pack-card img {
width: 100%;
height: auto;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
.pack-card-details {
padding: 10px;
text-align: left;
font-size: 14px;
color: #333;
}
/* Responsive Design Adjustment */
@media (max-width: 600px) {
.pack-card {
width: 45%;
}
}
</style>
</head>
<body>
<h1>Pokémon TCG 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 Pokémon Pack</button>
<!-- Pack Display Container -->
<div id="packContainer">
<h2>Your Pack:</h2>
<div id="packCards"></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 packContainer = document.getElementById('packContainer');
const packCards = document.getElementById('packCards');
const statusMessage = document.getElementById('statusMessage');
let selectedSetId = '';
let selectedSetNameText = '';
let rarityGroups = {}; // To store cards categorized by rarity
// 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();
fetchAndCategorizeCards(set.id);
});
setCard.appendChild(img);
setGrid.appendChild(setCard);
});
}
// Function to Fetch and Categorize Cards by Rarity
async function fetchAndCategorizeCards(setId) {
try {
statusMessage.textContent = "Loading cards...";
statusMessage.className = "loading";
packContainer.style.display = "none";
packCards.innerHTML = "";
const allCards = [];
let page = 1;
const pageSize = 250;
let totalPages = 1;
// Initial Fetch to determine total pages
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.push(...initialData.data);
totalPages = Math.ceil(initialData.totalCount / 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.push(...data.data);
}
// Categorize cards by rarity
rarityGroups = {};
allCards.forEach(card => {
let rarity = card.rarity || 'None';
// Handle special rarities if needed
if (rarity.toLowerCase().includes('rare') || rarity.toLowerCase().includes('ultra')) {
rarity = 'Rare';
} else if (rarity.toLowerCase().includes('uncommon')) {
rarity = 'Uncommon';
} else if (rarity.toLowerCase().includes('common')) {
rarity = 'Common';
} else {
rarity = 'Other';
}
if (!rarityGroups[rarity]) {
rarityGroups[rarity] = [];
}
rarityGroups[rarity].push(card);
});
console.log(rarityGroups); // For debugging
statusMessage.textContent = "";
} catch (error) {
console.error(error);
statusMessage.textContent = "Failed to load cards. Please try again.";
statusMessage.className = "error";
}
}
// Function to Open a Pack
function openPack() {
if (!selectedSetId) {
alert("Please select a set first.");
return;
}
// Define Pack Structure
const packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Other": 1 // For cards without a defined rarity, e.g., Basic Energy
};
const pack = [];
try {
// Check if enough cards are available in each category
for (const [rarity, count] of Object.entries(packStructure)) {
if (!rarityGroups[rarity] || rarityGroups[rarity].length < count) {
throw new Error(`Not enough cards in rarity category: ${rarity}`);
}
}
// For each rarity, pick the required number of random unique cards
for (const [rarity, count] of Object.entries(packStructure)) {
const selectedCards = getRandomCards(rarityGroups[rarity], count, pack);
pack.push(...selectedCards);
}
displayPack(pack);
} catch (error) {
console.error(error);
statusMessage.textContent = error.message || "Failed to open pack. Please try again.";
statusMessage.className = "error";
}
}
// Function to Get Random Unique Cards from a Category
function getRandomCards(cardArray, count, currentPack) {
const availableCards = cardArray.filter(card => !currentPack.includes(card.id));
if (availableCards.length < count) {
throw new Error("Not enough unique cards to fulfill the pack.");
}
const selected = [];
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * availableCards.length);
const card = availableCards[randomIndex];
selected.push(card);
// Remove the selected card to prevent duplicates in the pack
availableCards.splice(randomIndex, 1);
}
return selected;
}
// Function to Display the Pack
function displayPack(pack) {
packCards.innerHTML = ""; // Clear previous pack
pack.forEach(card => {
const cardDiv = document.createElement('div');
cardDiv.className = 'pack-card';
const img = document.createElement('img');
img.src = card.images.large || card.images.small || '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 detailsDiv = document.createElement('div');
detailsDiv.className = 'pack-card-details';
detailsDiv.innerHTML = `
<strong>${card.name}</strong><br>
<em>${card.set.name}</em><br>
<strong>Rarity:</strong> ${card.rarity || 'N/A'}
`;
cardDiv.appendChild(img);
cardDiv.appendChild(detailsDiv);
packCards.appendChild(cardDiv);
});
packContainer.style.display = "block";
statusMessage.textContent = "";
}
// Event Listener for Open Pack Button
openPackButton.addEventListener('click', openPack);
// Fetch Sets on Page Load
window.onload = fetchSets;
</script>
</body>
</html>
Explanation of Enhancements
-
Pack Structure Definition:
packStructure: Defines the number of cards per rarity in a pack. For example:
const packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Other": 1 // For special cards like Basic Energy
};
- Adjust these numbers based on the actual pack composition for different sets if needed.
-
Fetching and Categorizing Cards:
fetchAndCategorizeCards(setId):
- Fetches all cards from the selected set, handling pagination if the set contains more than 250 cards.
- Categorizes the cards into groups based on their rarity (
Rare, Uncommon, Common, and Other).
-
Opening a Pack:
openPack():
- Utilizes the categorized rarity groups to randomly select the required number of cards from each rarity.
- Ensures that the same card isn't selected multiple times in the same pack.
-
Displaying the Pack:
displayPack(pack):
- Dynamically creates and displays HTML elements for each card in the opened pack.
- Shows the card image, name, set name, and rarity.
-
User Interface Enhancements:
- Pack Display Container (
#packContainer): Shows the opened pack's contents in a visually appealing grid.
- Pack Card Styling (
.pack-card): Ensures each card in the pack is displayed uniformly with hover effects.
-
Error Handling:
- The script includes error handling to manage scenarios where there aren't enough cards in a rarity category or other fetch-related issues.
Additional Considerations
By implementing these enhancements, your application will now be capable of simulating the opening of full Pokémon TCG packs with accurate rarity distributions, providing a more realistic and enjoyable experience for users.