Coding Adventure Game
Adventure Log
Adventure Complete!
Congratulations, you navigated the coding challenges!
Game Levels
These are the challenges in the Coding Adventure Game. (Editing is not currently enabled).
Success: ${cag_escapeHTML(level.successMessage)}
`; cag_levelsDisplay.appendChild(levelDiv); }); } // --- DASHBOARD (GAME) FUNCTIONS --- /** * Starts or restarts the game */ function cag_startGame() { cag_gameState.currentLevelIndex = 0; cag_gameState.log = []; cag_gameState.status = 'playing'; cag_gameArea.classList.remove('hidden'); cag_dashboardOutput.classList.add('hidden'); // Hide results cag_pdfButtonContainer.classList.add('hidden'); cag_gameOutput.innerHTML = ''; // Clear log display cag_feedbackArea.innerHTML = ''; cag_inputCode.value = ''; cag_logMessage("Welcome to the Coding Adventure!"); cag_showLevel(0); } /** * Displays the current level's description and prompt */ function cag_showLevel(index) { if (index < 0 || index >= cag_levels.length) { console.error("Invalid level index:", index); return; } const level = cag_levels[index]; cag_logMessage(`--- Level ${index + 1} ---`); cag_challengePrompt.innerHTML = level.description; // Use innerHTML for tags
cag_inputCode.value = ''; // Clear input for next challenge
cag_feedbackArea.innerHTML = ''; // Clear feedback
}
/**
* Handles the submission of code
*/
function cag_submitCode() {
if (cag_gameState.status !== 'playing') return;
const currentLevel = cag_levels[cag_gameState.currentLevelIndex];
const userCode = cag_inputCode.value.trim();
// Basic validation using regex
if (currentLevel.solution.test(userCode)) {
// Correct code
cag_feedbackArea.innerHTML = `Correct!`;
cag_logMessage(currentLevel.successMessage, 'success');
// Move to next level or end game
cag_gameState.currentLevelIndex++;
if (cag_gameState.currentLevelIndex < cag_levels.length) {
// Slight delay before showing next level
setTimeout(() => cag_showLevel(cag_gameState.currentLevelIndex), 1000);
} else {
// Game complete
cag_gameState.status = 'complete';
cag_logMessage("You've completed all the challenges!", 'success');
cag_showResults();
}
} else {
// Incorrect code
cag_feedbackArea.innerHTML = `Not quite right. Try again!`;
cag_logMessage("That code didn't work as expected.", 'error');
}
}
/**
* Displays the final results screen
*/
function cag_showResults() {
cag_gameArea.classList.add('hidden');
cag_dashboardOutput.classList.remove('hidden');
cag_pdfButtonContainer.classList.remove('hidden');
// Optional: Add summary details if needed
cag_resultsSummary.innerHTML = `You successfully used variables, conditionals, and loops.
`;
}
/**
* Renders a clone for PDF generation (summary only)
*/
function cag_renderPdfClone() {
// Simple summary for PDF
cag_pdfRenderClone.innerHTML = `
Coding Adventure Summary
Adventure Complete!
You successfully navigated the coding challenges using:
- Variable Declaration
- Conditional Statements (if)
- Looping (for)
Keep practicing your coding skills!
`;
}
/**
* Generates and downloads a PDF of the results
*/
async function cag_downloadPDF() {
if (typeof jspdf === 'undefined' || typeof html2canvas === 'undefined') {
console.error("CAG Tool Error: jsPDF or html2canvas library not loaded.");
alert("Error: PDF libraries failed to load. Please check console.");
return;
}
cag_renderPdfClone(); // Create and populate the clone
const { jsPDF } = window.jspdf;
try {
const canvas = await html2canvas(cag_pdfRenderClone, {
scale: 2, // High resolution
useCORS: true,
});
const imgData = canvas.toDataURL('image/png');
const imgWidth = canvas.width;
const imgHeight = canvas.height;
const pdf = new jsPDF({ orientation: 'p', unit: 'pt', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
// Scale image to fit pdf width with margins
const margin = 40;
const ratio = Math.min((pdfWidth - margin * 2) / imgWidth, (pdfHeight - margin * 2) / imgHeight);
const w = imgWidth * ratio;
const h = imgHeight * ratio;
const x = (pdfWidth - w) / 2; // Center horizontally
const y = margin; // Top margin
pdf.addImage(imgData, 'PNG', x, y, w, h);
pdf.save('Coding_Adventure_Summary.pdf');
} catch (error) {
console.error("CAG Tool Error: PDF generation failed.", error);
alert("An error occurred while generating the PDF. Please try again.");
}
}
// --- EVENT LISTENERS ---
// Tab link clicks
cag_tabLinks.forEach((link, index) => {
link.addEventListener('click', () => cag_switchTab(index));
});
// Next/Prev button clicks
if (cag_prevButton) {
cag_prevButton.addEventListener('click', () => {
if (cag_currentTab > 0) cag_switchTab(cag_currentTab - 1);
});
}
if (cag_nextButton) {
cag_nextButton.addEventListener('click', () => {
if (cag_currentTab < cag_tabLinks.length - 1) cag_switchTab(cag_currentTab + 1);
});
}
// PDF download
if (cag_downloadPdfButton) {
cag_downloadPdfButton.addEventListener('click', cag_downloadPDF);
}
// Game Controls
if (cag_submitCodeButton) {
cag_submitCodeButton.addEventListener('click', cag_submitCode);
}
if (cag_restartGameButton) {
cag_restartGameButton.addEventListener('click', cag_startGame);
}
// Allow submitting with Enter key in textarea
if(cag_inputCode){
cag_inputCode.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault(); // Prevent newline in textarea
cag_submitCode();
}
});
}
// --- INITIALIZATION ---
cag_loadLevels();
cag_renderConfig(); // Populate config tab on load
cag_startGame(); // Start the game immediately on load
// Set initial tab state
cag_tabPanes.forEach((pane, index) => {
pane.classList.toggle('hidden', index !== 0);
pane.classList.toggle('cag-active', index === 0);
});
});
