// Additional fixes and enhancements for CodeJudge Pro // Fix for Monaco Editor loading function ensureEditorLoaded() { if (typeof monaco === 'undefined' || !editor) { console.log('Editor not loaded, retrying...'); setTimeout(initializeEditor, 500); return false; } return true; } // Enhanced code formatting with language-specific rules function enhancedFormatCode() { if (!ensureEditorLoaded()) return; const code = editor.getValue(); let formatted = code; if (currentLanguage === 'cpp') { // Basic C++ formatting formatted = code .replace(/\t/g, ' ') .replace(/\n\s*\n\s*\n/g, '\n\n') .replace(/\{\s*\n/g, ' {\n') .replace(/\s+\}/g, '\n}') .replace(/\)\s*\{/g, ') {'); } else if (currentLanguage === 'python') { // Basic Python formatting formatted = code .replace(/\t/g, ' ') .replace(/\n\s*\n\s*\n/g, '\n\n') .replace(/\:\s*\n/g, ':\n') .replace(/\s+\#/g, ' #'); } else if (currentLanguage === 'java') { // Basic Java formatting formatted = code .replace(/\t/g, ' ') .replace(/\n\s*\n\s*\n/g, '\n\n') .replace(/\{\s*\n/g, ' {\n') .replace(/\s+\}/g, '\n}') .replace(/\)\s*\{/g, ') {'); } editor.setValue(formatted); showToast('success', 'Code Formatted', 'Your code has been formatted successfully'); } // Enhanced language switching with confirmation function enhancedChangeLanguage() { if (editor && editor.getValue().trim() !== cppTemplate.trim()) { if (!confirm('Changing language will reset your code. Continue?')) { languageSelect.value = currentLanguage; return; } } changeLanguage(); } // Enhanced simulation with more realistic behavior function enhancedSimulateExecution(isSubmit = false) { if (isJudging) { showToast('warning', 'Already Judging', 'Please wait for current submission to complete'); return; } const code = editor.getValue().trim(); if (!code) { showToast('error', 'Empty Code', 'Please write some code before running'); return; } // Check for common errors in code if (currentLanguage === 'cpp') { if (!code.includes('#include')) { showToast('warning', 'Missing Includes', 'Your C++ code might be missing necessary includes'); } if (!code.includes('main') && !code.includes('Main')) { showToast('warning', 'No main function', 'C++ programs require a main function'); } } isJudging = true; loadingOverlay.classList.remove('hidden'); // Update loading message based on action const loadingTitle = document.getElementById('loadingTitle'); const loadingMessage = document.getElementById('loadingMessage'); if (isSubmit) { loadingTitle.textContent = 'Submitting Solution'; loadingMessage.textContent = 'Running all test cases...'; } else { loadingTitle.textContent = 'Running Code'; loadingMessage.textContent = 'Testing with sample cases...'; } // Reset results resultsContainer.innerHTML = ''; // Show execution status executionStatus.classList.remove('hidden'); const statusText = document.getElementById('statusText'); const statusIcon = document.getElementById('statusIcon'); const timer = document.getElementById('timer'); // Simulate compilation phase statusText.textContent = 'Compiling...'; statusIcon.className = 'w-4 h-4 rounded-full bg-yellow-500 animate-pulse'; let timeElapsed = 0; const timerInterval = setInterval(() => { timeElapsed += 0.1; timer.textContent = `${timeElapsed.toFixed(1)}s`; }, 100); // Simulate different phases with more realistic timing setTimeout(() => { statusText.textContent = 'Running Test Cases...'; statusIcon.className = 'w-4 h-4 rounded-full bg-blue-500 animate-pulse'; // Add some variation in timing const testCaseDelay = isSubmit ? 2500 : 1500; setTimeout(() => { // Generate more realistic results based on code quality const codeQuality = assessCodeQuality(code, currentLanguage); let resultIndex; if (isSubmit) { // For submission, use code quality to determine success chance const successChance = codeQuality.score > 0.7 ? 0.8 : codeQuality.score > 0.4 ? 0.5 : 0.2; resultIndex = Math.random() < successChance ? 0 : Math.floor(Math.random() * (mockSubmissionResults.length - 1)) + 1; } else { // For run, always show success but vary time/memory resultIndex = 0; // Adjust time based on code quality mockSubmissionResults[0].time = Math.max(5, Math.floor(50 * codeQuality.score)); mockSubmissionResults[0].memory = Math.max(5000, Math.floor(15000 * codeQuality.score)); } const result = {...mockSubmissionResults[resultIndex]}; // Adjust results based on custom test cases if (customTestCases.length > 0 && isSubmit) { customTestCases.forEach((testCase, index) => { result.testResults.push({ caseId: 6 + index, passed: Math.random() > 0.3, time: Math.floor(Math.random() * 20) + 5, output: testCase.expected }); }); } // Show final result statusText.textContent = getStatusDisplayName(result.status); statusIcon.className = `w-4 h-4 rounded-full ${getStatusColor(result.status)}`; statusIcon.classList.remove('animate-pulse'); clearInterval(timerInterval); timer.textContent = `${(timeElapsed + 0.5).toFixed(1)}s`; // Display results displayResults(result, isSubmit); // Show toast notification showResultToast(result.status, result.message); // Save submission if it's a submit action if (isSubmit) { saveUserSubmission(result); } // Hide loading overlay setTimeout(() => { loadingOverlay.classList.add('hidden'); isJudging = false; }, 500); }, testCaseDelay); }, 1000); } // Assess code quality function assessCodeQuality(code, language) { let score = 0.7; // Base score // Check for comments const hasComments = (code.includes('//') || code.includes('/*') || code.includes('#')); if (hasComments) score += 0.1; // Check for proper indentation const lines = code.split('\n'); let properlyIndented = 0; lines.forEach(line => { if (line.trim() === '' || line.match(/^\s*[\}\]]/)) return; if (line.match(/^\s{2,}/) || line.match(/^\t/)) properlyIndented++; }); const indentationScore = lines.length > 0 ? properlyIndented / lines.length : 0; score += indentationScore * 0.1; // Check for common good practices if (language === 'cpp') { if (code.includes('using namespace std;')) score -= 0.05; if (code.includes('#include ') || code.includes('#include ')) score += 0.05; if (code.includes('auto ')) score += 0.05; } // Check for code length (not too long, not too short) const lineCount = lines.length; if (lineCount > 10 && lineCount < 100) score += 0.1; return { score: Math.min(Math.max(score, 0.1), 0.95), hasComments: hasComments, indentationScore: indentationScore, lineCount: lineCount }; } // Add keyboard shortcuts helper function showKeyboardShortcuts() { const shortcuts = [ ['Ctrl/Cmd + Enter', 'Submit Solution'], ['Ctrl/Cmd + R', 'Run Code'], ['Ctrl/Cmd + Shift + F', 'Format Code'], ['Ctrl/Cmd + S', 'Save Code'], ['Esc', 'Close Modals'], ['Ctrl/Cmd + /', 'Toggle Comment'] ]; let shortcutHTML = '
'; shortcuts.forEach(([key, action]) => { shortcutHTML += `
${key} ${action}
`; }); shortcutHTML += '
'; showToast('info', 'Keyboard Shortcuts', shortcutHTML, 5000); } // Add code persistence function saveCodeToStorage() { if (!editor) return; const code = editor.getValue(); const key = `codejudge_code_${currentLanguage}_twosum`; localStorage.setItem(key, code); } function loadCodeFromStorage() { if (!editor) return; const key = `codejudge_code_${currentLanguage}_twosum`; const savedCode = localStorage.getItem(key); if (savedCode && savedCode.trim() !== '') { editor.setValue(savedCode); showToast('info', 'Code Loaded', 'Restored your previous code'); } } // Initialize with enhanced features function enhancedInit() { init(); // Call original init // Override format function formatBtn.removeEventListener('click', formatCode); formatBtn.addEventListener('click', enhancedFormatCode); // Override language change languageSelect.removeEventListener('change', changeLanguage); languageSelect.addEventListener('change', enhancedChangeLanguage); // Override run/submit runBtn.removeEventListener('click', () => simulateExecution(false)); submitBtn.removeEventListener('click', () => simulateExecution(true)); runBtn.addEventListener('click', () => enhancedSimulateExecution(false)); submitBtn.addEventListener('click', () => enhancedSimulateExecution(true)); // Add code persistence editor.onDidChangeModelContent(saveCodeToStorage); // Load saved code after a delay setTimeout(loadCodeFromStorage, 1000); // Add keyboard shortcuts info document.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === '/') { e.preventDefault(); const selection = editor.getSelection(); const model = editor.getModel(); // Simple comment toggle // This is a simplified version - Monaco has built-in comment toggling showToast('info', 'Comment Toggle', 'Use Ctrl+/ to toggle comments (built-in)'); } if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); saveCodeToStorage(); showToast('success', 'Code Saved', 'Your code has been saved locally'); } if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'K') { e.preventDefault(); showKeyboardShortcuts(); } }); // Show welcome message with features setTimeout(() => { showToast('info', 'CodeJudge Pro Ready', `
✓ All buttons and tabs are functional
✓ Real-time code execution simulation
✓ Custom test case support
✓ Submission history tracking
✓ Keyboard shortcuts enabled
`, 6000); }, 2000); } // Start enhanced application document.addEventListener('DOMContentLoaded', enhancedInit);