help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
python-pattern-generator
/
static
/
js
RSK World
python-pattern-generator
Python Number Pattern Generator - 22 Pattern Types + Fractals + Mathematical Algorithms + GUI & Web Interface + REST API + Educational Design
js
  • app.js16.8 KB
app.js
static/js/app.js
Raw Download
Find: Go to:
// JavaScript for Python Number Pattern Generator Web Interface

document.addEventListener('DOMContentLoaded', function() {
    // Initialize the application
    initializeApp();

    // Setup event listeners
    setupEventListeners();

    // Load initial patterns
    loadPatterns();
});

function initializeApp() {
    console.log('🚀 Initializing Python Number Pattern Generator Web Interface');
    console.log('📊 Developed by Molla Samser (RSK World)');
    console.log('🎨 Designed by Rima Khatun');
    console.log('🌐 Website: https://rskworld.in');
    console.log('📅 Year: 2026');

    // Show welcome message
    showAlert('Welcome to Python Number Pattern Generator!', 'info');
}

function setupEventListeners() {
    // Pattern generation
    document.getElementById('generateBtn').addEventListener('click', generatePattern);

    // Pattern analysis
    document.getElementById('analyzeBtn').addEventListener('click', analyzePattern);

    // Export buttons
    document.getElementById('exportTxtBtn').addEventListener('click', () => exportPattern('txt'));
    document.getElementById('exportJsonBtn').addEventListener('click', () => exportPattern('json'));

    // Copy and clear buttons
    document.getElementById('copyBtn').addEventListener('click', copyPattern);
    document.getElementById('clearBtn').addEventListener('click', clearPattern);

    // Pattern search
    document.getElementById('patternSearch').addEventListener('input', filterPatterns);

    // Pattern type change
    document.getElementById('patternSelect').addEventListener('change', onPatternChange);

    // Enter key support
    document.getElementById('sizeInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') generatePattern();
    });

    document.getElementById('startNumInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') generatePattern();
    });
}

function loadPatterns() {
    // Load pattern types from API
    fetch('/api/patterns')
        .then(response => response.json())
        .then(data => {
            updatePatternSelect(data.patterns, data.patterns_without_start_num);
        })
        .catch(error => {
            console.error('Error loading patterns:', error);
            showAlert('Failed to load patterns. Using defaults.', 'warning');
        });
}

function updatePatternSelect(patterns, patternsWithoutStartNum) {
    const select = document.getElementById('patternSelect');
    const currentValue = select.value;

    // Store patterns without start num for later use
    window.patternsWithoutStartNum = patternsWithoutStartNum;

    // Clear existing options
    select.innerHTML = '';

    // Add new options with badges
    Object.entries(patterns).forEach(([key, value]) => {
        const option = document.createElement('option');
        option.value = key;
        option.textContent = value;

        // Add badge class based on pattern type
        if (['pyramid', 'reverse_pyramid', 'triangle', 'square', 'diamond', 'hourglass'].includes(key)) {
            option.className = 'badge-basic';
        } else if (['sierpinski', 'mandelbrot', 'hilbert', 'dragon', 'koch'].includes(key)) {
            option.className = 'badge-fractal';
        } else if (['cellular', 'binary_tree'].includes(key)) {
            option.className = 'badge-advanced';
        } else {
            option.className = 'badge-math';
        }

        select.appendChild(option);
    });

    // Restore selection if it exists
    if (currentValue && patterns[currentValue]) {
        select.value = currentValue;
    }

    onPatternChange(); // Update UI based on selected pattern
}

function onPatternChange() {
    const patternType = document.getElementById('patternSelect').value;
    const startNumGroup = document.getElementById('startNumGroup');

    // Hide start number input for patterns that don't use it
    if (window.patternsWithoutStartNum && window.patternsWithoutStartNum.includes(patternType)) {
        startNumGroup.style.display = 'none';
    } else {
        startNumGroup.style.display = 'block';
    }
}

function filterPatterns() {
    const searchTerm = document.getElementById('patternSearch').value.toLowerCase();
    const select = document.getElementById('patternSelect');
    const options = select.querySelectorAll('option');

    options.forEach(option => {
        const text = option.textContent.toLowerCase();
        if (text.includes(searchTerm)) {
            option.style.display = '';
        } else {
            option.style.display = 'none';
        }
    });
}

function generatePattern() {
    const patternType = document.getElementById('patternSelect').value;
    const size = parseInt(document.getElementById('sizeInput').value);
    const startNum = parseInt(document.getElementById('startNumInput').value);

    // Validation
    if (size < 1 || size > 50) {
        showAlert('Size must be between 1 and 50', 'danger');
        return;
    }

    if (!window.patternsWithoutStartNum.includes(patternType) && (startNum < 0 || startNum > 1000)) {
        showAlert('Start number must be between 0 and 1000', 'danger');
        return;
    }

    // Show loading
    showLoading(true);

    // Generate pattern
    fetch('/generate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            pattern_type: patternType,
            size: size,
            start_num: startNum
        })
    })
    .then(response => response.json())
    .then(data => {
        showLoading(false);

        if (data.error) {
            showAlert(data.error, 'danger');
            return;
        }

        // Display pattern
        displayPattern(data.pattern, data);

        // Update statistics
        updateStatistics(data.stats);

        showAlert(`Pattern "${data.pattern_type}" generated successfully!`, 'success');
    })
    .catch(error => {
        showLoading(false);
        console.error('Error generating pattern:', error);
        showAlert('Error generating pattern. Please try again.', 'danger');
    });
}

function analyzePattern() {
    const patternOutput = document.getElementById('patternOutput');
    const patternText = patternOutput.textContent;

    if (!patternText || patternText.includes('Welcome to Pattern Generator')) {
        showAlert('Please generate a pattern first.', 'warning');
        return;
    }

    // Show loading
    showLoading(true);

    // Get current parameters
    const patternType = document.getElementById('patternSelect').value;
    const size = parseInt(document.getElementById('sizeInput').value);
    const startNum = parseInt(document.getElementById('startNumInput').value);

    // Analyze pattern
    fetch('/generate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            pattern_type: patternType,
            size: size,
            start_num: startNum
        })
    })
    .then(response => response.json())
    .then(data => {
        showLoading(false);

        if (data.error) {
            showAlert(data.error, 'danger');
            return;
        }

        // Show detailed analysis
        showPatternAnalysis(data);
    })
    .catch(error => {
        showLoading(false);
        console.error('Error analyzing pattern:', error);
        showAlert('Error analyzing pattern. Please try again.', 'danger');
    });
}

function displayPattern(pattern, metadata) {
    const output = document.getElementById('patternOutput');

    // Create header
    let header = `Pattern: ${metadata.pattern_type}\n`;
    header += `Size: ${metadata.size}`;
    if (metadata.start_num !== undefined && metadata.start_num !== null) {
        header += ` | Start: ${metadata.start_num}`;
    }
    header += `\n${'='.repeat(50)}\n\n`;

    // Display pattern
    output.innerHTML = `<div class="pattern-fade-in">${header}${pattern}</div>`;
}

function updateStatistics(stats) {
    const statsPanel = document.getElementById('statsPanel');
    const statsContent = document.getElementById('statsContent');

    if (!stats || Object.keys(stats).length === 0) {
        statsPanel.style.display = 'none';
        return;
    }

    statsContent.innerHTML = `
        <div class="stats-highlight">
            <strong>Lines:</strong> ${stats.lines} |
            <strong>Characters:</strong> ${stats.characters} |
            <strong>Numbers:</strong> ${stats.numbers}
        </div>
        <div class="stats-highlight">
            <strong>Max Number:</strong> ${stats.max_num} |
            <strong>Min Number:</strong> ${stats.min_num} |
            <strong>Sum:</strong> ${stats.sum_nums}
        </div>
        <div class="stats-highlight">
            <strong>Avg per Line:</strong> ${stats.avg_per_line.toFixed(2)}
        </div>
    `;

    statsPanel.style.display = 'block';
}

function showPatternAnalysis(data) {
    const analysis = data.stats;
    const pattern = data.pattern;

    let analysisHTML = `
        <div class="modal fade" id="analysisModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-info text-white">
                        <h5 class="modal-title">
                            <i class="fas fa-chart-bar"></i> Pattern Analysis - ${data.pattern_type}
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="text-info">Statistics</h6>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Lines:</span>
                                        <strong>${analysis.lines}</strong>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Characters:</span>
                                        <strong>${analysis.characters}</strong>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Numbers:</span>
                                        <strong>${analysis.numbers}</strong>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Max Number:</span>
                                        <strong>${analysis.max_num}</strong>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Min Number:</span>
                                        <strong>${analysis.min_num}</strong>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Sum:</span>
                                        <strong>${analysis.sum_nums}</strong>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between">
                                        <span>Avg per Line:</span>
                                        <strong>${analysis.avg_per_line.toFixed(2)}</strong>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h6 class="text-info">Pattern Preview</h6>
                                <pre class="bg-dark text-success p-3 small" style="max-height: 300px; overflow-y: auto;">${pattern}</pre>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Remove existing modal if present
    const existingModal = document.getElementById('analysisModal');
    if (existingModal) {
        existingModal.remove();
    }

    // Add new modal to body
    document.body.insertAdjacentHTML('beforeend', analysisHTML);

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('analysisModal'));
    modal.show();
}

function exportPattern(format) {
    const patternOutput = document.getElementById('patternOutput');
    const patternText = patternOutput.textContent;

    if (!patternText || patternText.includes('Welcome to Pattern Generator')) {
        showAlert('Please generate a pattern first.', 'warning');
        return;
    }

    const patternType = document.getElementById('patternSelect').value;
    const size = parseInt(document.getElementById('sizeInput').value);
    const startNum = parseInt(document.getElementById('startNumInput').value);

    // Create download link
    const link = document.createElement('a');
    link.href = `/export/${patternType}?size=${size}&start_num=${startNum}&format=${format}`;
    link.download = `pattern_${patternType}_${Date.now()}.${format}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showAlert(`Pattern exported as ${format.toUpperCase()}!`, 'success');
}

function copyPattern() {
    const patternOutput = document.getElementById('patternOutput');
    const patternText = patternOutput.textContent;

    if (!patternText || patternText.includes('Welcome to Pattern Generator')) {
        showAlert('Please generate a pattern first.', 'warning');
        return;
    }

    navigator.clipboard.writeText(patternText).then(() => {
        showAlert('Pattern copied to clipboard!', 'success');
    }).catch(() => {
        showAlert('Failed to copy pattern.', 'danger');
    });
}

function clearPattern() {
    const output = document.getElementById('patternOutput');
    output.innerHTML = `
        <div class="text-center text-muted py-5">
            <i class="fas fa-magic fa-3x mb-3"></i>
            <h4>Pattern Cleared</h4>
            <p>Select a pattern type and click "Generate Pattern" to create a new pattern.</p>
        </div>
    `;

    // Hide statistics
    document.getElementById('statsPanel').style.display = 'none';

    showAlert('Pattern output cleared.', 'info');
}

function showLoading(show) {
    const indicator = document.getElementById('loadingIndicator');
    const generateBtn = document.getElementById('generateBtn');

    if (show) {
        indicator.style.display = 'block';
        generateBtn.disabled = true;
        generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';
    } else {
        indicator.style.display = 'none';
        generateBtn.disabled = false;
        generateBtn.innerHTML = '<i class="fas fa-play"></i> Generate Pattern';
    }
}

function showAlert(message, type) {
    // Remove existing alerts
    const existingAlerts = document.querySelectorAll('.alert');
    existingAlerts.forEach(alert => alert.remove());

    // Create new alert
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alert.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alert);

    // Auto-dismiss after 5 seconds
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl+G for generate
    if (e.ctrlKey && e.key === 'g') {
        e.preventDefault();
        generatePattern();
    }

    // Ctrl+A for analyze
    if (e.ctrlKey && e.key === 'a') {
        e.preventDefault();
        analyzePattern();
    }

    // Ctrl+C for copy (when pattern output is focused)
    if (e.ctrlKey && e.key === 'c' && document.activeElement.id === 'patternOutput') {
        e.preventDefault();
        copyPattern();
    }
});
471 lines•16.8 KB
javascript

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer