Game Resource Loader
Loading... 0%
Resource Loading Code
// Resource loader class
class ResourceLoader {
    constructor() {
        this.resources = {
            images: new Map(),
            sounds: new Map()
        };
        this.totalResources = 0;
        this.loadedResources = 0;
    }

    // Add resources to load
    addImage(key, url) {
        this.totalResources++;
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.onload = () => {
                this.resources.images.set(key, img);
                this.loadedResources++;
                resolve(img);
            };
            img.onerror = reject;
            img.src = url;
        });
    }

    addSound(key, url) {
        this.totalResources++;
        return new Promise((resolve, reject) => {
            const audio = new Audio();
            audio.oncanplaythrough = () => {
                this.resources.sounds.set(key, audio);
                this.loadedResources++;
                resolve(audio);
            };
            audio.onerror = reject;
            audio.src = url;
        });
    }

    // Get loading progress
    getProgress() {
        return Math.floor((this.loadedResources / this.totalResources) * 100);
    }

    // Load all resources
    async loadAll(resources) {
        const promises = [];
        
        resources.images?.forEach((url, key) => {
            promises.push(this.addImage(key, url));
        });
        
        resources.sounds?.forEach((url, key) => {
            promises.push(this.addSound(key, url));
        });

        return Promise.all(promises);
    }
}

// Initialize game
const loader = new ResourceLoader();
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// Resource list
const gameResources = {
    images: new Map([
        ['player', '/api/placeholder/200/200'],
        ['background', '/api/placeholder/600/400'],
        ['sprite', '/api/placeholder/100/100']
    ]),
    sounds: new Map([
        ['bgm', '/api/placeholder/audio'],
        ['effect', '/api/placeholder/audio']
    ])
};

// Loading animation
function drawLoadingScreen(progress) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Draw progress bar
    const barWidth = canvas.width * 0.8;
    const barHeight = 20;
    const barX = (canvas.width - barWidth) / 2;
    const barY = canvas.height / 2;
    
    // Bar background
    ctx.fillStyle = '#333';
    ctx.fillRect(barX, barY, barWidth, barHeight);
    
    // Progress
    ctx.fillStyle = '#4CAF50';
    ctx.fillRect(barX, barY, barWidth * (progress / 100), barHeight);
    
    // Text
    ctx.fillStyle = '#fff';
    ctx.font = '20px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`Loading... ${progress}%`, canvas.width / 2, barY - 20);
}