File size: 2,483 Bytes
162286c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# optimization.py
import zlib
import base64
from PIL import Image
import io
import json

class SpaceOptimizer:
    """Clase para optimizar recursos en HuggingFace Spaces"""
    def __init__(self):
        self.asset_cache = {}
        self.compression_level = 6
    
    def compress_assets(self, asset_data: bytes) -> str:
        """Comprime assets usando zlib y base64"""
        compressed = zlib.compress(asset_data, level=self.compression_level)
        return base64.b64encode(compressed).decode('utf-8')
    
    def decompress_assets(self, compressed_str: str) -> bytes:
        """Descomprime assets previamente comprimidos"""
        compressed_data = base64.b64decode(compressed_str)
        return zlib.decompress(compressed_data)
    
    def image_to_webp(self, image_path: str, quality: int = 80) -> bytes:
        """Convierte imágenes a formato WebP optimizado"""
        with Image.open(image_path) as img:
            byte_io = io.BytesIO()
            img.save(byte_io, format='WEBP', quality=quality, method=6)
            return byte_io.getvalue()
    
    def generate_sprite_atlas(self, image_paths: list, tile_size: int = 64) -> dict:
        """Crea atlas de sprites optimizados para el juego"""
        atlas = {}
        total_width = tile_size * len(image_paths)
        composite = Image.new('RGBA', (total_width, tile_size))
        
        for idx, path in enumerate(image_paths):
            img = Image.open(path).resize((tile_size, tile_size))
            composite.paste(img, (idx * tile_size, 0))
            atlas[path.stem] = {
                'x': idx * tile_size,
                'y': 0,
                'width': tile_size,
                'height': tile_size
            }
        
        byte_io = io.BytesIO()
        composite.save(byte_io, format='WEBP')
        return {
            'atlas': byte_io.getvalue(),
            'mapping': atlas
        }
    
    def save_state_optimized(self, game_state: dict) -> str:
        """Guarda el estado del juego en formato optimizado para Spaces"""
        compressed = self.compress_assets(json.dumps(game_state).encode('utf-8'))
        return f"GAUCHO_SAVE::{compressed}"
    
    def load_state_optimized(self, save_str: str) -> dict:
        """Carga el estado del juego desde formato optimizado"""
        if save_str.startswith("GAUCHO_SAVE::"):
            compressed = save_str.split("::", 1)[1]
            return json.loads(self.decompress_assets(compressed))
        return {}