File size: 11,984 Bytes
9d822c3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | // 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 <vector>') || code.includes('#include <algorithm>')) 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 = '<div class="space-y-2">';
shortcuts.forEach(([key, action]) => {
shortcutHTML += `
<div class="flex justify-between items-center">
<kbd class="px-2 py-1 bg-gray-800 rounded text-sm font-mono">${key}</kbd>
<span class="text-gray-300">${action}</span>
</div>
`;
});
shortcutHTML += '</div>';
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', `
<div class="space-y-1 text-sm">
<div>✓ All buttons and tabs are functional</div>
<div>✓ Real-time code execution simulation</div>
<div>✓ Custom test case support</div>
<div>✓ Submission history tracking</div>
<div>✓ Keyboard shortcuts enabled</div>
</div>
`, 6000);
}, 2000);
}
// Start enhanced application
document.addEventListener('DOMContentLoaded', enhancedInit); |