window.gameState = null; const initGame = () => { const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Set canvas to full viewport size const resizeCanvas = () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }; window.addEventListener('resize', resizeCanvas); resizeCanvas(); // Game state let gameState = { time: 0, player: createPlayer(100, 100), // Starting position camera: createCamera(0, 0), world: createWorld() }; // Make gameState globally accessible window.gameState = gameState; // Game loop const gameLoop = (timestamp) => { // Calculate delta time const deltaTime = timestamp - gameState.time; gameState.time = timestamp; // Update gameState = updateGame(gameState, deltaTime); // Render render(ctx, gameState); // Next frame requestAnimationFrame(gameLoop); }; // Start the game loop requestAnimationFrame(gameLoop); }; const updateGame = (state, deltaTime) => { const updatedPlayer = updatePlayer(state.player, deltaTime); const updatedCamera = updateCamera(state.camera, updatedPlayer); return { ...state, player: updatedPlayer, camera: updatedCamera }; }; const render = (ctx, state) => { // Clear the canvas ctx.fillStyle = '#000'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Apply camera transform ctx.save(); ctx.translate(-state.camera.x, -state.camera.y); // 1. Render background objects state.world.backgroundTrees.forEach(tree => { renderTree(ctx, tree, ctx.canvas.height - state.world.groundHeight); }); state.world.backgroundRocks.forEach(rock => { renderRock(ctx, rock, ctx.canvas.height - state.world.groundHeight); }); state.world.backgroundGrass.forEach(grass => { renderGrass(ctx, grass, ctx.canvas.height - state.world.groundHeight, state.time); }); // 2. Render platforms state.world.platforms.forEach(platform => { ctx.fillStyle = platform.color; ctx.fillRect(platform.x, platform.y, platform.width, platform.height); }); // 3. Render player renderPlayer(ctx, state.player); // 4. Render foreground objects state.world.foregroundTrees.forEach(tree => { renderTree(ctx, tree, ctx.canvas.height - state.world.groundHeight); }); state.world.foregroundRocks.forEach(rock => { renderRock(ctx, rock, ctx.canvas.height - state.world.groundHeight); }); state.world.foregroundGrass.forEach(grass => { renderGrass(ctx, grass, ctx.canvas.height - state.world.groundHeight, state.time); }); // 5. Render ground const groundY = ctx.canvas.height - state.world.groundHeight; ctx.fillStyle = '#4a4'; ctx.fillRect( state.camera.x - 1000, groundY, ctx.canvas.width + 2000, state.world.groundHeight ); ctx.restore(); }; // Initialize the game when the window loads window.addEventListener('load', initGame);