<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pokémon TCG Pack…
- Usercode
- Assistant
h1 {
color: #2a75bb;
margin-bottom: 20px;
}
/* Set Selection Modal Styles */
#setModal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.8);
}
#setModalContent {
background-color: #fff;
margin: 5% auto;
padding: 20px;
border: 1px solid #888;
width: 90%;
max-width: 1200px;
border-radius: 10px;
max-height: 80vh;
overflow-y: auto;
}
#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;
}
.setCard {
width: 120px;
cursor: pointer;
border: 2px solid transparent;
border-radius: 8px;
transition: transform 0.2s, border-color 0.2s;
flex: 0 0 auto;
}
.setCard:hover {
transform: scale(1.05);
border-color: #2a75bb;
}
.setCard img {
width: 100%;
height: auto;
border-radius: 8px;
max-height: 180px;
object-fit: contain;
}
.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;
margin: 10px;
}
#openPackButton:hover {
background-color: #f2b807;
}
/* Pack Display Container */
#packContainer {
display: none;
margin-top: 30px;
}
#packContainer h2 {
color: #2a75bb;
margin-bottom: 20px;
}
#packCards {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
}
.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;
vertical-align: top;
background-color: #fff;
}
.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;
max-height: 220px;
object-fit: contain;
}
.pack-card-details {
padding: 10px;
text-align: left;
font-size: 14px;
color: #333;
}
.loading {
font-size: 20px;
color: #555;
margin-top: 20px;
}
.error {
font-size: 20px;
color: red;
margin-top: 20px;
}
/* Responsive Design */
@media (max-width: 800px) {
.setCard {
width: 100px;
}
#packContainer h2 {
font-size: 24px;
}
.pack-card {
width: 45%;
}
}
@media (max-width: 500px) {
#setModalContent {
width: 95%;
margin: 10% auto;
}
.pack-card {
width: 100%;
}
.setCard {
width: 80px;
}
}
</style>
<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');
if (!response.ok) throw new Error('Failed to fetch sets.');
const data = await response.json();
const sets = data.data;
// Sort sets by release date
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 and Type
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 and type
rarityGroups = {
"Rare": [],
"Uncommon": [],
"Common": [],
"Energy": []
};
allCards.forEach(card => {
// Check if the card is an Energy card
if (card.types && card.types.includes('Energy')) {
rarityGroups["Energy"].push(card);
return;
}
let rarity = card.rarity || 'Common'; // Default to 'Common' if rarity is undefined
// Normalize rarity values
const rarityLower = rarity.toLowerCase();
if (rarityLower.includes('ultra') || rarityLower.includes('rare')) {
rarity = 'Rare';
} else if (rarityLower.includes('uncommon')) {
rarity = 'Uncommon';
} else if (rarityLower.includes('common') || rarityLower.includes('basic')) {
rarity = 'Common';
} else {
// Ignore cards that don't fit into the main categories
return;
}
if (rarityGroups[rarity]) {
rarityGroups[rarity].push(card);
}
});
// Adjust pack structure based on available rarities
determinePackStructure();
statusMessage.textContent = "";
} catch (error) {
console.error(error);
statusMessage.textContent = "Failed to load cards. Please try again.";
statusMessage.className = "error";
}
}
// Function to Determine Pack Structure based on Available Rarities
let packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Energy": 5
};
function determinePackStructure() {
// Ensure that energy cards are always included
if (!rarityGroups["Energy"] || rarityGroups["Energy"].length === 0) {
console.warn("No Energy cards found in the selected set.");
packStructure["Energy"] = 0;
}
// Check and adjust other rarities if necessary
for (const rarity in packStructure) {
if (rarity !== "Energy" && (!rarityGroups[rarity] || rarityGroups[rarity].length < packStructure[rarity])) {
console.warn(`Not enough cards in rarity category: ${rarity}. Redistributing to Common.`);
packStructure["Common"] += packStructure[rarity];
delete packStructure[rarity];
}
}
}
// Function to Open a Pack
function openPack() {
if (!selectedSetId) {
alert("Please select a set first.");
return;
}
// Reset any previous error messages
statusMessage.textContent = "";
statusMessage.className = "";
const pack = [];
try {
// Check if enough cards are available in each category
for (const [rarity, count] of Object.entries(packStructure)) {
if (rarity === "Energy") {
if (rarityGroups[rarity] && rarityGroups[rarity].length >= count) {
const selectedCards = getRandomCards(rarityGroups[rarity], count, pack);
pack.push(...selectedCards);
} else {
console.warn("Not enough Energy cards available.");
}
} else {
if (!rarityGroups[rarity] || rarityGroups[rarity].length < count) {
throw new Error(`Not enough cards in rarity category: ${rarity}`);
}
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.some(c => c.id === card.id));
if (availableCards.length < count) {
throw new Error(`Not enough unique cards in category:`);
}
const selected = [];
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * availableCards.length);
const card = availableCards[randomIndex];
selected.push(card);
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>
Please identify the problem in this code that doesn't give me energy cards in the pack and fix it please :) Love you!
Hello! 😊 I'm happy to help you fix the issue with energy cards not appearing in your Pokémon TCG Pack Opener. After reviewing your code, I've identified the problem and provided a solution below.
The primary issue lies in the packStructure configuration:
let packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Energy": 5
};
Setting "Energy": 5 requests five energy cards per pack. However, most Pokémon TCG sets typically include one or two energy cards per pack. If a selected set doesn't have enough energy cards to meet this requirement, the code skips adding energy cards altogether, resulting in no energy cards appearing in the pack.
Adjust the Pack Structure:
Enhance Flexibility:
determinePackStructure function to dynamically set the number of energy cards based on availability, ensuring that energy cards are always included if possible.Optional - Provide Fallbacks:
Below are the modifications you need to make to your existing code:
packStructureChange the number of energy cards from 5 to 2 (or any desired realistic number).
// Original packStructure
let packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Energy": 5
};
Update to:
// Updated packStructure with realistic Energy count
let packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Energy": 2
};
determinePackStructure FunctionEnsure that the pack structure adjusts based on the available number of energy cards.
function determinePackStructure() {
// Ensure that energy cards are always included
if (!rarityGroups["Energy"] || rarityGroups["Energy"].length === 0) {
console.warn("No Energy cards found in the selected set.");
packStructure["Energy"] = 0;
} else if (rarityGroups["Energy"].length < packStructure["Energy"]) {
// Adjust the number of Energy cards if not enough are available
console.warn(`Only ${rarityGroups["Energy"].length} Energy cards available. Adjusting the pack structure.`);
packStructure["Energy"] = rarityGroups["Energy"].length;
}
// Check and adjust other rarities if necessary
for (const rarity in packStructure) {
if (rarity !== "Energy" && (!rarityGroups[rarity] || rarityGroups[rarity].length < packStructure[rarity])) {
console.warn(`Not enough cards in rarity category: ${rarity}. Redistributing to Common.`);
packStructure["Common"] += packStructure[rarity];
delete packStructure[rarity];
}
}
}
openPack FunctionProvide a more informative message if energy cards couldn't be added.
function openPack() {
if (!selectedSetId) {
alert("Please select a set first.");
return;
}
// Reset any previous error messages
statusMessage.textContent = "";
statusMessage.className = "";
const pack = [];
try {
// Check if enough cards are available in each category
for (const [rarity, count] of Object.entries(packStructure)) {
if (rarity === "Energy") {
if (rarityGroups["Energy"] && rarityGroups["Energy"].length >= count) {
const selectedCards = getRandomCards(rarityGroups["Energy"], count, pack);
pack.push(...selectedCards);
} else if (rarityGroups["Energy"] && rarityGroups["Energy"].length > 0) {
// Add available Energy cards if less than required
const selectedCards = getRandomCards(rarityGroups["Energy"], rarityGroups["Energy"].length, pack);
pack.push(...selectedCards);
statusMessage.textContent += " Not enough Energy cards available. Added available Energy cards.\n";
} else {
console.warn("Not enough Energy cards available.");
}
} else {
if (!rarityGroups[rarity] || rarityGroups[rarity].length < count) {
throw new Error(`Not enough cards in rarity category: ${rarity}`);
}
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";
}
}
Here's the complete updated code with the necessary changes highlighted:
Reduced Energy Cards per Pack:
packStructure. This aligns better with standard Pokémon TCG pack contents.Dynamic Adjustment of Pack Structure:
determinePackStructure function to adjust the number of energy cards based on their availability within the selected set. If there are fewer energy cards than desired, it adjusts accordingly instead of setting the count to zero.Improved Error Handling:
openPack function to provide feedback if not all requested energy cards could be added, ensuring the user is informed about the pack contents.Maintained Existing Functionality:
Flexibility: You can further adjust the packStructure to better match specific sets or desired pack configurations.
Validation: Ensure that the selected sets have the desired number of energy cards. Some sets might have special energy types or different card distributions.
Testing: After implementing these changes, test with multiple sets to ensure energy cards are now appearing as expected in the packs.
I hope this resolves the issue! If you have any more questions or need further assistance, feel free to ask. Happy packing! 🐱🏍✨
Not yet included in a published release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pokémon TCG Pack Opener</title>
<style>
/* [Your existing CSS remains unchanged] */
/* ... */
</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');
if (!response.ok) throw new Error('Failed to fetch sets.');
const data = await response.json();
const sets = data.data;
// Sort sets by release date
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 and Type
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 and type
rarityGroups = {
"Rare": [],
"Uncommon": [],
"Common": [],
"Energy": []
};
allCards.forEach(card => {
// Check if the card is an Energy card
if (card.types && card.types.includes('Energy')) {
rarityGroups["Energy"].push(card);
return;
}
let rarity = card.rarity || 'Common'; // Default to 'Common' if rarity is undefined
// Normalize rarity values
const rarityLower = rarity.toLowerCase();
if (rarityLower.includes('ultra') || rarityLower.includes('rare')) {
rarity = 'Rare';
} else if (rarityLower.includes('uncommon')) {
rarity = 'Uncommon';
} else if (rarityLower.includes('common') || rarityLower.includes('basic')) {
rarity = 'Common';
} else {
// Ignore cards that don't fit into the main categories
return;
}
if (rarityGroups[rarity]) {
rarityGroups[rarity].push(card);
}
});
// Adjust pack structure based on available cards
determinePackStructure();
statusMessage.textContent = "";
} catch (error) {
console.error(error);
statusMessage.textContent = "Failed to load cards. Please try again.";
statusMessage.className = "error";
}
}
// Function to Determine Pack Structure based on Available Rarities
let packStructure = {
"Rare": 1,
"Uncommon": 3,
"Common": 5,
"Energy": 2 // Updated from 5 to 2
};
function determinePackStructure() {
// Ensure that energy cards are always included
if (!rarityGroups["Energy"] || rarityGroups["Energy"].length === 0) {
console.warn("No Energy cards found in the selected set.");
packStructure["Energy"] = 0;
} else if (rarityGroups["Energy"].length < packStructure["Energy"]) {
// Adjust the number of Energy cards if not enough are available
console.warn(`Only ${rarityGroups["Energy"].length} Energy cards available. Adjusting the pack structure.`);
packStructure["Energy"] = rarityGroups["Energy"].length;
}
// Check and adjust other rarities if necessary
for (const rarity in packStructure) {
if (rarity !== "Energy" && (!rarityGroups[rarity] || rarityGroups[rarity].length < packStructure[rarity])) {
console.warn(`Not enough cards in rarity category: ${rarity}. Redistributing to Common.`);
packStructure["Common"] += packStructure[rarity];
delete packStructure[rarity];
}
}
}
// Function to Open a Pack
function openPack() {
if (!selectedSetId) {
alert("Please select a set first.");
return;
}
// Reset any previous error messages
statusMessage.textContent = "";
statusMessage.className = "";
const pack = [];
try {
// Check if enough cards are available in each category
for (const [rarity, count] of Object.entries(packStructure)) {
if (rarity === "Energy") {
if (rarityGroups["Energy"] && rarityGroups["Energy"].length >= count) {
const selectedCards = getRandomCards(rarityGroups["Energy"], count, pack);
pack.push(...selectedCards);
} else if (rarityGroups["Energy"] && rarityGroups["Energy"].length > 0) {
// Add available Energy cards if less than required
const selectedCards = getRandomCards(rarityGroups["Energy"], rarityGroups["Energy"].length, pack);
pack.push(...selectedCards);
statusMessage.textContent += " Not enough Energy cards available. Added available Energy cards.\n";
} else {
console.warn("Not enough Energy cards available.");
}
} else {
if (!rarityGroups[rarity] || rarityGroups[rarity].length < count) {
throw new Error(`Not enough cards in rarity category: ${rarity}`);
}
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.some(c => c.id === card.id));
if (availableCards.length < count) {
throw new Error(`Not enough unique cards in category.`);
}
const selected = [];
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * availableCards.length);
const card = availableCards[randomIndex];
selected.push(card);
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>