""" Geometry Dash Clone - Authentic Scratch Version Uses actual level tile images from the Scratch project. Color-based collision detection for authentic gameplay. Controls: - SPACE / UP / CLICK: Jump (cube mode) / Fly up (ship mode) - R: Restart level - ESC: Return to menu - 1-5: Change player skin """ import pygame import math import random import json from dataclasses import dataclass from enum import Enum, auto from typing import List, Tuple, Optional from pathlib import Path # Initialize Pygame pygame.init() pygame.mixer.init() # Constants WINDOW_WIDTH = 1200 WINDOW_HEIGHT = 700 FPS = 120 BASE_FPS = 60 # Physics are tuned for 60 FPS, we scale by delta time # Paths ASSETS_DIR = Path("assets") TILES_DIR = ASSETS_DIR / "level_tiles" / "png" MANIFEST_PATH = ASSETS_DIR / "level_tiles" / "manifest.json" # Colors (Geometry Dash style - neon on dark) BLACK = (0, 0, 0) WHITE = (255, 255, 255) DARK_BG = (20, 20, 35) # Player colors PLAYER_COLOR_1 = (255, 230, 0) PLAYER_COLOR_2 = (255, 100, 0) PLAYER_GLOW = (0, 255, 255) # Obstacle colors from Scratch project analysis SPIKE_COLOR = (40, 40, 40) SPIKE_OUTLINE = (255, 254, 224) PLATFORM_COLOR = (40, 40, 60) PLATFORM_OUTLINE = (100, 100, 150) # SCRATCH COLLISION COLORS (from analyze_collision.py and analyze_tile_colors.py) # These are the colors used in sensing_touchingcolor blocks DEATH_COLORS = [ (255, 254, 222), # #fffede - Spike outline color (255, 254, 224), # #fffee0 - Alternate spike color ] SHIP_PORTAL_COLOR_HEX = (255, 119, 255) # #ff77ff CUBE_PORTAL_COLOR_HEX = (105, 244, 255) # #69f4ff JUMP_ORB_COLOR = (251, 255, 0) # #fbff00 # Solid platform color (black fill in tiles) SOLID_PLATFORM_COLOR = (0, 0, 0) # #000000 - solid ground/ceiling # Portal colors SHIP_PORTAL_COLOR = (255, 100, 200) CUBE_PORTAL_COLOR = (0, 200, 255) GRAVITY_PORTAL_UP = (255, 255, 0) GRAVITY_PORTAL_DOWN = (0, 100, 255) # Ground colors GROUND_COLOR = (30, 30, 50) GROUND_LINE = (60, 60, 90) # Orb color ORB_COLOR = (251, 243, 0) # Physics SCROLL_SPEED = 8 GRAVITY = 1.2 JUMP_FORCE = -16 SHIP_LIFT = -0.8 SHIP_FALL = 0.5 MAX_FALL_SPEED = 15 # Sizes PLAYER_SIZE = 44 SPIKE_SIZE = 44 BLOCK_SIZE = 44 GROUND_HEIGHT = 150 # Tile dimensions (from Scratch) TILE_WIDTH = 480 # PNG output size TILE_HEIGHT = 360 # PNG output size TILE_SPACING = 480 # How far apart tiles are placed (from Scratch motion blocks) class GameMode(Enum): CUBE = auto() SHIP = auto() class GameState(Enum): MENU = auto() PLAYING = auto() DEAD = auto() WIN = auto() @dataclass class Particle: x: float y: float vx: float vy: float life: float max_life: float color: Tuple[int, int, int] size: float class SoundManager: def __init__(self): self.sounds = {} self.music_tracks = [] self.load_sounds() def load_sounds(self): sound_files = { "jump": ASSETS_DIR / "Player_Bonk.wav", "death": ASSETS_DIR / "Player_explode_11.wav", "start": ASSETS_DIR / "Menu_Start.wav", } for name, path in sound_files.items(): if path.exists(): try: self.sounds[name] = pygame.mixer.Sound(str(path)) if name == "jump": self.sounds[name].set_volume(0.3) elif name == "death": self.sounds[name].set_volume(0.5) except Exception as e: print(f"Could not load sound {name}: {e}") music_files = [ ASSETS_DIR / "Music_Stereo_Madness_2.wav", ASSETS_DIR / "Music_Golden_Haze.wav", ASSETS_DIR / "Music_Space_Battle.wav", ] self.music_tracks = [str(f) for f in music_files if f.exists()] def play(self, sound_name: str): if sound_name in self.sounds: self.sounds[sound_name].play() def play_music(self, level: int = 0): if self.music_tracks and level < len(self.music_tracks): try: pygame.mixer.music.load(self.music_tracks[level]) pygame.mixer.music.set_volume(0.4) pygame.mixer.music.play(-1) except Exception as e: print(f"Could not play music: {e}") def stop_music(self): pygame.mixer.music.stop() class AssetManager: def __init__(self): self.player_cubes = [] self.player_ships = [] self.current_skin = 0 self.level_tiles = {} # Dict of level_num -> list of tile surfaces self.manifest = None self.background = None # Authentic Scratch background self.floor = None # Floor sprite self.ceiling = None # Ceiling sprite self.load_assets() self.load_level_tiles() def load_assets(self): # Load background image bg_path = ASSETS_DIR / "background.png" if bg_path.exists(): try: self.background = pygame.image.load(str(bg_path)).convert() # Scale to fill window, may tile horizontally self.background = pygame.transform.scale(self.background, (WINDOW_WIDTH, WINDOW_HEIGHT)) print("Loaded authentic Scratch background") except Exception as e: print(f"Could not load background: {e}") # Load floor sprite (tiles horizontally at bottom) floor_path = ASSETS_DIR / "floor.png" if floor_path.exists(): try: self.floor = pygame.image.load(str(floor_path)).convert_alpha() # Scale floor to be wider for better tiling (double width) floor_w, floor_h = self.floor.get_size() self.floor = pygame.transform.scale(self.floor, (floor_w * 2, floor_h)) print(f"Loaded floor: {self.floor.get_size()}") except Exception as e: print(f"Could not load floor: {e}") # Load ceiling sprite - use ceiling_floor which is larger ceiling_path = ASSETS_DIR / "ceiling_floor.png" if ceiling_path.exists(): try: self.ceiling = pygame.image.load(str(ceiling_path)).convert_alpha() # Scale ceiling to be wider ceil_w, ceil_h = self.ceiling.get_size() self.ceiling = pygame.transform.scale(self.ceiling, (ceil_w * 2, ceil_h)) print(f"Loaded ceiling: {self.ceiling.get_size()}") except Exception as e: print(f"Could not load ceiling: {e}") for i in range(1, 6): path = ASSETS_DIR / f"Player_cube{i}.png" if path.exists(): try: img = pygame.image.load(str(path)).convert_alpha() img = pygame.transform.scale(img, (PLAYER_SIZE, PLAYER_SIZE)) self.player_cubes.append(img) except Exception as e: print(f"Could not load cube{i}: {e}") for i in range(1, 6): path = ASSETS_DIR / f"Player_ship{i}.png" if path.exists(): try: img = pygame.image.load(str(path)).convert_alpha() img = pygame.transform.scale(img, (PLAYER_SIZE, PLAYER_SIZE)) self.player_ships.append(img) except Exception as e: print(f"Could not load ship{i}: {e}") if not self.player_cubes: self.player_cubes.append(self.create_fallback_cube()) if not self.player_ships: self.player_ships.append(self.create_fallback_ship()) def load_level_tiles(self): """Load all level tile PNGs from the converted Scratch assets.""" if not MANIFEST_PATH.exists(): print("Warning: Level tile manifest not found") return try: with open(MANIFEST_PATH) as f: self.manifest = json.load(f) except Exception as e: print(f"Could not load manifest: {e}") return for level_num, level_data in self.manifest['levels'].items(): level_int = int(level_num) self.level_tiles[level_int] = [] for tile_info in level_data['tiles']: tile_name = tile_info['name'] # Convert "Level 1.1" to "Level_1_1" safe_name = tile_name.replace(" ", "_").replace(".", "_") tile_path = TILES_DIR / f"{safe_name}.png" if tile_path.exists(): try: img = pygame.image.load(str(tile_path)).convert_alpha() self.level_tiles[level_int].append(img) except Exception as e: print(f"Could not load tile {tile_name}: {e}") self.level_tiles[level_int].append(None) else: print(f"Tile not found: {tile_path}") self.level_tiles[level_int].append(None) print(f"Loaded {len(self.level_tiles[level_int])} tiles for Level {level_num}") def get_level_tiles(self, level_num: int) -> List: """Get all tile surfaces for a level.""" tiles = self.level_tiles.get(level_num, []) print(f"get_level_tiles({level_num}): returning {len(tiles)} tiles") return tiles def get_level_length(self, level_num: int) -> int: """Get level length from manifest.""" if self.manifest and str(level_num) in self.manifest['levels']: return self.manifest['levels'][str(level_num)].get('length', 10000) return 10000 def create_fallback_cube(self) -> pygame.Surface: surf = pygame.Surface((PLAYER_SIZE, PLAYER_SIZE), pygame.SRCALPHA) pygame.draw.rect(surf, PLAYER_COLOR_1, (0, 0, PLAYER_SIZE, PLAYER_SIZE // 2)) pygame.draw.rect(surf, PLAYER_COLOR_2, (0, PLAYER_SIZE // 2, PLAYER_SIZE, PLAYER_SIZE // 2)) pygame.draw.rect(surf, BLACK, (0, 0, PLAYER_SIZE, PLAYER_SIZE), 2) pygame.draw.rect(surf, PLAYER_GLOW, (8, 10, 10, 10)) pygame.draw.rect(surf, PLAYER_GLOW, (26, 10, 10, 10)) return surf def create_fallback_ship(self) -> pygame.Surface: surf = pygame.Surface((PLAYER_SIZE, PLAYER_SIZE), pygame.SRCALPHA) points = [(PLAYER_SIZE, PLAYER_SIZE // 2), (0, 0), (0, PLAYER_SIZE)] pygame.draw.polygon(surf, PLAYER_COLOR_1, points) pygame.draw.polygon(surf, BLACK, points, 2) pygame.draw.circle(surf, PLAYER_GLOW, (12, PLAYER_SIZE // 2), 6) return surf def get_player_sprite(self, mode: GameMode) -> pygame.Surface: if mode == GameMode.CUBE: return self.player_cubes[self.current_skin % len(self.player_cubes)] else: return self.player_ships[self.current_skin % len(self.player_ships)] def set_skin(self, index: int): self.current_skin = index class ParticleSystem: def __init__(self): self.particles: List[Particle] = [] def emit_trail(self, x: float, y: float, color: Tuple[int, int, int]): for _ in range(2): self.particles.append(Particle( x=x + random.uniform(-5, 5), y=y + random.uniform(-5, 5), vx=random.uniform(-2, -0.5), vy=random.uniform(-1, 1), life=0.5, max_life=0.5, color=color, size=random.uniform(3, 8) )) def emit_death(self, x: float, y: float, color: Tuple[int, int, int]): for _ in range(50): angle = random.uniform(0, 2 * math.pi) speed = random.uniform(3, 12) self.particles.append(Particle( x=x, y=y, vx=math.cos(angle) * speed, vy=math.sin(angle) * speed, life=1.0, max_life=1.0, color=color, size=random.uniform(4, 12) )) def emit_win(self, x: float, y: float): colors = [(255, 230, 0), (0, 255, 255), (255, 100, 200), (100, 255, 100)] for _ in range(100): angle = random.uniform(0, 2 * math.pi) speed = random.uniform(5, 15) self.particles.append(Particle( x=x, y=y, vx=math.cos(angle) * speed, vy=math.sin(angle) * speed, life=2.0, max_life=2.0, color=random.choice(colors), size=random.uniform(5, 15) )) def emit_jump(self, x: float, y: float): for _ in range(8): angle = random.uniform(math.pi * 0.6, math.pi * 1.4) speed = random.uniform(2, 5) self.particles.append(Particle( x=x, y=y + PLAYER_SIZE // 2, vx=math.cos(angle) * speed, vy=math.sin(angle) * speed, life=0.3, max_life=0.3, color=PLAYER_GLOW, size=random.uniform(3, 6) )) def update(self, dt: float): for p in self.particles: p.x += p.vx p.y += p.vy p.vy += 0.2 p.life -= dt self.particles = [p for p in self.particles if p.life > 0] def draw(self, screen: pygame.Surface): for p in self.particles: alpha = int(255 * (p.life / p.max_life)) size = int(p.size * (p.life / p.max_life)) if size > 0: surf = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA) pygame.draw.circle(surf, (*p.color, alpha), (size, size), size) screen.blit(surf, (int(p.x - size), int(p.y - size))) class Player: def __init__(self, x: float, y: float, assets: AssetManager): self.x = x self.y = y self.vy = 0 self.rotation = 0 self.mode = GameMode.CUBE self.gravity_flipped = False self.on_ground = False self.dead = False self.assets = assets def jump(self) -> bool: if self.mode == GameMode.CUBE and self.on_ground: grav_mult = -1 if self.gravity_flipped else 1 self.vy = JUMP_FORCE * grav_mult self.on_ground = False return True return False def orb_jump(self): grav_mult = -1 if self.gravity_flipped else 1 self.vy = JUMP_FORCE * grav_mult def update(self, holding_jump: bool, dt: float = 1.0): if self.dead: return grav_mult = -1 if self.gravity_flipped else 1 if self.mode == GameMode.CUBE: self.vy += GRAVITY * grav_mult * dt if not self.on_ground: self.rotation += 8 * grav_mult * dt else: target = round(self.rotation / 90) * 90 self.rotation += (target - self.rotation) * 0.3 * dt else: if holding_jump: self.vy += SHIP_LIFT * grav_mult * dt else: self.vy += SHIP_FALL * grav_mult * dt self.vy = max(min(self.vy, MAX_FALL_SPEED), -MAX_FALL_SPEED) target_rotation = self.vy * 3 if self.gravity_flipped: target_rotation = -target_rotation + 180 self.rotation += (target_rotation - self.rotation) * 0.15 * dt self.y += self.vy * dt ground_y = WINDOW_HEIGHT - GROUND_HEIGHT ceiling_y = 50 if not self.gravity_flipped: if self.y + PLAYER_SIZE / 2 > ground_y: self.y = ground_y - PLAYER_SIZE / 2 self.vy = 0 self.on_ground = True else: self.on_ground = False if self.y - PLAYER_SIZE / 2 < ceiling_y and self.mode == GameMode.SHIP: self.y = ceiling_y + PLAYER_SIZE / 2 self.vy = 0 else: if self.y - PLAYER_SIZE / 2 < ceiling_y: self.y = ceiling_y + PLAYER_SIZE / 2 self.vy = 0 self.on_ground = True else: self.on_ground = False if self.y + PLAYER_SIZE / 2 > ground_y and self.mode == GameMode.SHIP: self.y = ground_y - PLAYER_SIZE / 2 self.vy = 0 def get_hitbox(self) -> pygame.Rect: shrink = 8 return pygame.Rect( self.x - PLAYER_SIZE / 2 + shrink, self.y - PLAYER_SIZE / 2 + shrink, PLAYER_SIZE - shrink * 2, PLAYER_SIZE - shrink * 2 ) def draw(self, screen: pygame.Surface, particles: Optional['ParticleSystem'] = None): if self.dead: return # Draw light blue trail particles behind player if particles and not self.dead: for _ in range(2): particles.particles.append(Particle( x=self.x - PLAYER_SIZE // 2 + random.uniform(-5, 5), y=self.y + PLAYER_SIZE // 2 - 5 + random.uniform(-3, 3), vx=random.uniform(-3, -1), vy=random.uniform(-1, 1), life=0.3, max_life=0.3, color=(100, 200, 255), # Light blue size=random.uniform(3, 6) )) sprite = self.assets.get_player_sprite(self.mode) rotated = pygame.transform.rotate(sprite, -self.rotation) rect = rotated.get_rect(center=(self.x, self.y)) screen.blit(rotated, rect.topleft) class Obstacle: def __init__(self, x: float, y: float): self.x = x self.y = y self.active = True def update(self, scroll_speed: float): self.x -= scroll_speed if self.x < -100: self.active = False def get_hitbox(self) -> pygame.Rect: raise NotImplementedError def draw(self, screen: pygame.Surface): raise NotImplementedError def is_deadly(self) -> bool: return True class Spike(Obstacle): def __init__(self, x: float, y: float, inverted: bool = False): super().__init__(x, y) self.inverted = inverted def get_hitbox(self) -> pygame.Rect: shrink = 12 if self.inverted: return pygame.Rect(self.x - SPIKE_SIZE // 2 + shrink, self.y - SPIKE_SIZE + shrink, SPIKE_SIZE - shrink * 2, SPIKE_SIZE - shrink * 2) return pygame.Rect(self.x - SPIKE_SIZE // 2 + shrink, self.y - SPIKE_SIZE + shrink, SPIKE_SIZE - shrink * 2, SPIKE_SIZE - shrink * 2) def draw(self, screen: pygame.Surface): if self.inverted: points = [(self.x, self.y), (self.x - SPIKE_SIZE // 2, self.y - SPIKE_SIZE), (self.x + SPIKE_SIZE // 2, self.y - SPIKE_SIZE)] else: points = [(self.x, self.y - SPIKE_SIZE), (self.x - SPIKE_SIZE // 2, self.y), (self.x + SPIKE_SIZE // 2, self.y)] pygame.draw.polygon(screen, SPIKE_COLOR, points) pygame.draw.polygon(screen, SPIKE_OUTLINE, points, 2) class Block(Obstacle): def __init__(self, x: float, y: float, width: int = 1, height: int = 1): super().__init__(x, y) self.width = width * BLOCK_SIZE self.height = height * BLOCK_SIZE def get_hitbox(self) -> pygame.Rect: return pygame.Rect(self.x, self.y - self.height, self.width, self.height) def draw(self, screen: pygame.Surface): rect = self.get_hitbox() pygame.draw.rect(screen, PLATFORM_COLOR, rect) pygame.draw.rect(screen, PLATFORM_OUTLINE, rect, 2) for i in range(1, self.width // BLOCK_SIZE): pygame.draw.line(screen, PLATFORM_OUTLINE, (rect.x + i * BLOCK_SIZE, rect.y), (rect.x + i * BLOCK_SIZE, rect.bottom), 1) for i in range(1, self.height // BLOCK_SIZE): pygame.draw.line(screen, PLATFORM_OUTLINE, (rect.x, rect.y + i * BLOCK_SIZE), (rect.right, rect.y + i * BLOCK_SIZE), 1) def is_deadly(self) -> bool: return False class Portal(Obstacle): def __init__(self, x: float, y: float, portal_type: str): super().__init__(x, y) self.portal_type = portal_type self.height = BLOCK_SIZE * 3 self.width = BLOCK_SIZE self.used = False self.pulse = 0 def get_hitbox(self) -> pygame.Rect: return pygame.Rect(self.x, self.y - self.height, self.width, self.height) def draw(self, screen: pygame.Surface): rect = self.get_hitbox() self.pulse = (self.pulse + 0.1) % (2 * math.pi) if self.portal_type == 'ship': color = SHIP_PORTAL_COLOR elif self.portal_type == 'cube': color = CUBE_PORTAL_COLOR elif self.portal_type == 'gravity_up': color = GRAVITY_PORTAL_UP else: color = GRAVITY_PORTAL_DOWN glow_size = 5 + 3 * math.sin(self.pulse) glow_rect = rect.inflate(glow_size * 2, glow_size * 2) glow_surf = pygame.Surface((glow_rect.width, glow_rect.height), pygame.SRCALPHA) pygame.draw.ellipse(glow_surf, (*color, 50), glow_surf.get_rect()) screen.blit(glow_surf, glow_rect.topleft) pygame.draw.ellipse(screen, color, rect, 4) inner_rect = rect.inflate(-10, -10) inner_surf = pygame.Surface((inner_rect.width, inner_rect.height), pygame.SRCALPHA) pygame.draw.ellipse(inner_surf, (*color, 80), inner_surf.get_rect()) screen.blit(inner_surf, inner_rect.topleft) cx, cy = rect.centerx, rect.centery if self.portal_type == 'ship': pygame.draw.polygon(screen, WHITE, [(cx + 15, cy), (cx - 10, cy - 10), (cx - 10, cy + 10)]) elif self.portal_type == 'cube': pygame.draw.rect(screen, WHITE, (cx - 10, cy - 10, 20, 20)) elif self.portal_type == 'gravity_up': pygame.draw.polygon(screen, WHITE, [(cx, cy - 15), (cx - 12, cy + 10), (cx + 12, cy + 10)]) else: pygame.draw.polygon(screen, WHITE, [(cx, cy + 15), (cx - 12, cy - 10), (cx + 12, cy - 10)]) def is_deadly(self) -> bool: return False class Orb(Obstacle): def __init__(self, x: float, y: float): super().__init__(x, y) self.radius = 18 self.pulse = 0 self.used = False def get_hitbox(self) -> pygame.Rect: return pygame.Rect(self.x - self.radius - 5, self.y - self.radius - 5, (self.radius + 5) * 2, (self.radius + 5) * 2) def draw(self, screen: pygame.Surface): if self.used: return self.pulse = (self.pulse + 0.15) % (2 * math.pi) pulse_size = 4 * math.sin(self.pulse) glow_surf = pygame.Surface((self.radius * 3, self.radius * 3), pygame.SRCALPHA) pygame.draw.circle(glow_surf, (*ORB_COLOR, 60), (self.radius * 1.5, self.radius * 1.5), int(self.radius + 8 + pulse_size)) screen.blit(glow_surf, (int(self.x - self.radius * 1.5), int(self.y - self.radius * 1.5))) pygame.draw.circle(screen, ORB_COLOR, (int(self.x), int(self.y)), self.radius + 4, 3) pygame.draw.circle(screen, ORB_COLOR, (int(self.x), int(self.y)), self.radius) pygame.draw.circle(screen, WHITE, (int(self.x - 4), int(self.y - 4)), self.radius // 3) def is_deadly(self) -> bool: return False class Level: """Authentic tile-based level using Scratch costume images.""" def __init__(self, level_num: int, assets: AssetManager): self.level_num = level_num self.assets = assets self.tiles = assets.get_level_tiles(level_num) self.length = assets.get_level_length(level_num) self.tile_surfaces = [] # Pre-scaled tile surfaces self.obstacles: List[Obstacle] = [] # Still use obstacles for portals/orbs that need interaction # Collision surface - combined image of visible tiles for pixel-perfect collision self.collision_surface: Optional[pygame.Surface] = None self.prepare_tiles() self.setup_interactables() def prepare_tiles(self): """Scale tiles to fit the game window properly.""" # Scale factor: Scratch stage is 480x360, we want tiles to fill the play area # Play area height is WINDOW_HEIGHT - GROUND_HEIGHT = 700 - 150 = 550 # So scale tiles to fit vertically, maintaining aspect ratio target_height = WINDOW_HEIGHT - GROUND_HEIGHT + 50 # Slight overlap with ground scale = target_height / TILE_HEIGHT scaled_width = int(TILE_WIDTH * scale) for tile in self.tiles: if tile: scaled = pygame.transform.scale(tile, (scaled_width, target_height)) self.tile_surfaces.append(scaled) else: self.tile_surfaces.append(None) self.scaled_tile_width = scaled_width self.scaled_tile_height = target_height print(f"Level {self.level_num}: {len(self.tile_surfaces)} tiles, scale={scale:.2f}, tile_w={scaled_width}") def setup_interactables(self): """Add portal/orb markers based on level - these still need traditional collision.""" ground_y = WINDOW_HEIGHT - GROUND_HEIGHT # Level 1: Ship portal around 20%, Cube portal around 40% if self.level_num == 1: # Approximate positions based on Scratch costume content ship_portal_x = int(self.length * 0.15) cube_portal_x = int(self.length * 0.35) self.obstacles.append(Portal(ship_portal_x, ground_y, 'ship')) self.obstacles.append(Portal(cube_portal_x, ground_y, 'cube')) elif self.level_num == 2: ship_portal_x = int(self.length * 0.25) cube_portal_x = int(self.length * 0.55) self.obstacles.append(Portal(ship_portal_x, ground_y, 'ship')) self.obstacles.append(Portal(cube_portal_x, ground_y, 'cube')) elif self.level_num == 3: # Gravity flip level gravity_up_x = int(self.length * 0.30) gravity_down_x = int(self.length * 0.60) self.obstacles.append(Portal(gravity_up_x, ground_y, 'gravity_up')) self.obstacles.append(Portal(gravity_down_x, 100, 'gravity_down')) def get_visible_tile_indices(self, scroll_x: float) -> List[Tuple[int, float]]: """Get indices of tiles that should be visible, with their screen x positions.""" visible = [] # Tiles are placed at their scaled width apart (no overlap) # But the scroll_x is in "game world" units - we need to map scroll position to tiles # Level length from Scratch / number of tiles = spacing per tile in world units tiles_count = len(self.tile_surfaces) if tiles_count == 0: return visible # World units per tile (based on level length and tile count) world_units_per_tile = self.length / tiles_count for i, tile in enumerate(self.tile_surfaces): if tile is None: continue # World position of this tile tile_world_x = i * world_units_per_tile # Screen position - map world coordinates to screen # scroll_x is how far we've scrolled in world units screen_x = tile_world_x - scroll_x # Scale screen position by the ratio of scroll speed to visual representation # This keeps tiles visually flowing at the right pace # Check if visible (with margin for tile width) if -self.scaled_tile_width < screen_x < WINDOW_WIDTH + 100: visible.append((i, screen_x)) return visible def draw_tiles(self, screen: pygame.Surface, scroll_x: float): """Draw visible level tiles.""" visible = self.get_visible_tile_indices(scroll_x) for idx, screen_x in visible: tile = self.tile_surfaces[idx] if tile: # Position tile so bottom aligns with ground y = WINDOW_HEIGHT - GROUND_HEIGHT - self.scaled_tile_height + 50 screen.blit(tile, (int(screen_x), y)) def check_color_collision(self, player_x: float, player_y: float, scroll_x: float) -> Optional[str]: """Check for collision by sampling pixel colors from tile images. Returns: 'death', 'ship', 'cube', 'orb', or None Note: Solid ground collision is handled separately by check_ground_collision """ visible = self.get_visible_tile_indices(scroll_x) # Sample points around the player - avoid very bottom to not hit ground # Focus on center and sides for spike/portal detection sample_points = [ (player_x, player_y), # Center (player_x - PLAYER_SIZE // 3, player_y), # Left (player_x + PLAYER_SIZE // 3, player_y), # Right (player_x + PLAYER_SIZE // 3, player_y - PLAYER_SIZE // 4), # Front-top (player_x + PLAYER_SIZE // 3, player_y + PLAYER_SIZE // 4), # Front-bottom (not quite at feet) (player_x, player_y - PLAYER_SIZE // 3), # Top ] tile_y = WINDOW_HEIGHT - GROUND_HEIGHT - self.scaled_tile_height + 50 for idx, screen_x in visible: tile = self.tile_surfaces[idx] if tile is None: continue for px, py in sample_points: # Convert player screen pos to tile local coordinates local_x = int(px - screen_x) local_y = int(py - tile_y) # Check if within tile bounds if 0 <= local_x < self.scaled_tile_width and 0 <= local_y < self.scaled_tile_height: try: color = tile.get_at((local_x, local_y))[:3] # Check against Scratch collision colors # Death colors (spike outlines) - highest priority for death_color in DEATH_COLORS: if self.colors_similar(color, death_color, tolerance=25): return 'death' # Ship portal if self.colors_similar(color, SHIP_PORTAL_COLOR_HEX, tolerance=30): return 'ship' # Cube portal if self.colors_similar(color, CUBE_PORTAL_COLOR_HEX, tolerance=30): return 'cube' # Jump orb if self.colors_similar(color, JUMP_ORB_COLOR, tolerance=30): return 'orb' # Note: We no longer return 'solid' here - ground handled separately except (IndexError, ValueError): pass return None def check_ground_collision(self, player_x: float, player_y: float, player_vy: float, scroll_x: float, gravity_flipped: bool) -> Tuple[Optional[float], bool]: """Check if player is touching or about to land on solid ground. Returns: (new_y position if grounded, is_on_ground) """ visible = self.get_visible_tile_indices(scroll_x) tile_y = WINDOW_HEIGHT - GROUND_HEIGHT - self.scaled_tile_height + 50 # For normal gravity, check below player; for flipped, check above if not gravity_flipped: # Check points at bottom of player foot_y = player_y + PLAYER_SIZE // 2 check_points = [ (player_x - PLAYER_SIZE // 3, foot_y), (player_x, foot_y), (player_x + PLAYER_SIZE // 3, foot_y), ] else: # Check points at top of player (gravity flipped) head_y = player_y - PLAYER_SIZE // 2 check_points = [ (player_x - PLAYER_SIZE // 3, head_y), (player_x, head_y), (player_x + PLAYER_SIZE // 3, head_y), ] for idx, screen_x in visible: tile = self.tile_surfaces[idx] if tile is None: continue for px, py in check_points: local_x = int(px - screen_x) local_y = int(py - tile_y) if 0 <= local_x < self.scaled_tile_width and 0 <= local_y < self.scaled_tile_height: try: color = tile.get_at((local_x, local_y))[:3] # Check for solid ground if self.colors_similar(color, SOLID_PLATFORM_COLOR, tolerance=15): # Found ground - search upward/downward for the surface if not gravity_flipped: # Search upward for the top of the platform for search_y in range(local_y, max(local_y - 30, 0), -1): search_color = tile.get_at((local_x, search_y))[:3] if not self.colors_similar(search_color, SOLID_PLATFORM_COLOR, tolerance=15): # Found surface - place player on top surface_screen_y = tile_y + search_y new_y = surface_screen_y - PLAYER_SIZE // 2 return (new_y, True) else: # Search downward for the bottom of the platform (gravity flipped) for search_y in range(local_y, min(local_y + 30, self.scaled_tile_height)): search_color = tile.get_at((local_x, search_y))[:3] if not self.colors_similar(search_color, SOLID_PLATFORM_COLOR, tolerance=15): surface_screen_y = tile_y + search_y new_y = surface_screen_y + PLAYER_SIZE // 2 return (new_y, True) except (IndexError, ValueError): pass return (None, False) def check_ceiling_collision(self, player_x: float, player_y: float, scroll_x: float, gravity_flipped: bool) -> Optional[float]: """Check if player is hitting a ceiling. Returns new y position if hit.""" visible = self.get_visible_tile_indices(scroll_x) tile_y = WINDOW_HEIGHT - GROUND_HEIGHT - self.scaled_tile_height + 50 # For normal gravity, check above player; for flipped, check below if not gravity_flipped: head_y = player_y - PLAYER_SIZE // 2 check_points = [ (player_x - PLAYER_SIZE // 3, head_y), (player_x, head_y), (player_x + PLAYER_SIZE // 3, head_y), ] else: foot_y = player_y + PLAYER_SIZE // 2 check_points = [ (player_x - PLAYER_SIZE // 3, foot_y), (player_x, foot_y), (player_x + PLAYER_SIZE // 3, foot_y), ] for idx, screen_x in visible: tile = self.tile_surfaces[idx] if tile is None: continue for px, py in check_points: local_x = int(px - screen_x) local_y = int(py - tile_y) if 0 <= local_x < self.scaled_tile_width and 0 <= local_y < self.scaled_tile_height: try: color = tile.get_at((local_x, local_y))[:3] if self.colors_similar(color, SOLID_PLATFORM_COLOR, tolerance=15): # Hit ceiling - push player back if not gravity_flipped: # Search down for bottom of ceiling for search_y in range(local_y, min(local_y + 30, self.scaled_tile_height)): search_color = tile.get_at((local_x, search_y))[:3] if not self.colors_similar(search_color, SOLID_PLATFORM_COLOR, tolerance=15): surface_screen_y = tile_y + search_y return surface_screen_y + PLAYER_SIZE // 2 else: # Gravity flipped - search up for top of "ceiling" (which is below player) for search_y in range(local_y, max(local_y - 30, 0), -1): search_color = tile.get_at((local_x, search_y))[:3] if not self.colors_similar(search_color, SOLID_PLATFORM_COLOR, tolerance=15): surface_screen_y = tile_y + search_y return surface_screen_y - PLAYER_SIZE // 2 except (IndexError, ValueError): pass return None @staticmethod def colors_similar(c1: Tuple[int, int, int], c2: Tuple[int, int, int], tolerance: int = 20) -> bool: """Check if two colors are similar within tolerance.""" return all(abs(a - b) <= tolerance for a, b in zip(c1, c2)) def update_obstacles(self, scroll_speed: float): """Update obstacle positions.""" for obs in self.obstacles: obs.update(scroll_speed) class Game: def __init__(self): self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("Geometry Dash Clone") self.clock = pygame.time.Clock() self.font_large = pygame.font.Font(None, 72) self.font_medium = pygame.font.Font(None, 48) self.font_small = pygame.font.Font(None, 32) self.assets = AssetManager() self.sounds = SoundManager() self.state = GameState.MENU self.selected_level = 1 self.max_levels = 3 self.player: Optional[Player] = None self.level: Optional[Level] = None self.particles = ParticleSystem() self.scroll_x = 0 self.attempts = 0 self.bg_offset = 0 self.ground_offset = 0 self.holding_jump = False # Camera zoom: 1.0 = zoomed in (cube), smaller = zoomed out (ship) self.camera_zoom = 1.0 self.target_zoom = 1.0 self.camera_y_offset = 0 # Vertical camera offset self.target_y_offset = 0 # FPS tracking for 1% and 0.1% lows self.frame_times: list[float] = [] self.fps_update_timer = 0 self.fps_1_low = 0 self.fps_01_low = 0 self.sounds.play_music(0) def start_level(self, level_num: int): self.state = GameState.PLAYING self.player = Player(200, WINDOW_HEIGHT - GROUND_HEIGHT - PLAYER_SIZE, self.assets) self.level = Level(level_num, self.assets) self.scroll_x = 0 self.attempts += 1 self.particles = ParticleSystem() self.holding_jump = False self.camera_zoom = 1.0 self.target_zoom = 1.0 self.camera_y_offset = 0 self.target_y_offset = 0 self.sounds.play("start") self.sounds.play_music(level_num - 1) def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: if self.state == GameState.MENU: if event.key in (pygame.K_RETURN, pygame.K_SPACE): self.start_level(self.selected_level) elif event.key == pygame.K_LEFT: self.selected_level = max(1, self.selected_level - 1) elif event.key == pygame.K_RIGHT: self.selected_level = min(self.max_levels, self.selected_level + 1) elif event.key in (pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, pygame.K_5): self.assets.set_skin(event.key - pygame.K_1) elif self.state == GameState.PLAYING: if event.key in (pygame.K_SPACE, pygame.K_UP, pygame.K_w): self.holding_jump = True if self.player and self.player.jump(): self.sounds.play("jump") self.particles.emit_jump(self.player.x, self.player.y) elif event.key == pygame.K_r: self.start_level(self.selected_level) elif event.key == pygame.K_ESCAPE: self.state = GameState.MENU self.sounds.play_music(0) elif event.key in (pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, pygame.K_5): self.assets.set_skin(event.key - pygame.K_1) elif self.state in (GameState.DEAD, GameState.WIN): if event.key in (pygame.K_SPACE, pygame.K_RETURN): if self.state == GameState.DEAD: self.start_level(self.selected_level) else: self.state = GameState.MENU self.sounds.play_music(0) elif event.key == pygame.K_ESCAPE: self.state = GameState.MENU self.sounds.play_music(0) if event.type == pygame.KEYUP: if event.key in (pygame.K_SPACE, pygame.K_UP, pygame.K_w): self.holding_jump = False if event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() if self.state == GameState.PLAYING: self.holding_jump = True if self.player and self.player.jump(): self.sounds.play("jump") self.particles.emit_jump(self.player.x, self.player.y) elif self.state == GameState.MENU: # Check if clicked on PLAY button (yellow triangle area) button_y = WINDOW_HEIGHT // 2 + 20 play_x = WINDOW_WIDTH // 2 - 100 play_rect = pygame.Rect(play_x - 30, button_y - 35, 70, 70) # Check if clicked on level selection boxes level_y = WINDOW_HEIGHT // 2 + 140 for i in range(1, self.max_levels + 1): level_box_x = WINDOW_WIDTH // 2 + (i - 2) * 100 level_rect = pygame.Rect(level_box_x - 35, level_y - 25, 70, 50) if level_rect.collidepoint(mouse_x, mouse_y): self.selected_level = i break # Only start if clicking on play button if play_rect.collidepoint(mouse_x, mouse_y): self.start_level(self.selected_level) elif self.state == GameState.DEAD: # Click to retry when dead self.start_level(self.selected_level) if event.type == pygame.MOUSEBUTTONUP: self.holding_jump = False return True def update(self): # Delta time: how many "60 FPS frames" worth of time passed # At 120 FPS, dt = 0.5 (half a frame at 60 FPS) # At 60 FPS, dt = 1.0 (one full frame) dt = BASE_FPS / FPS if self.state == GameState.PLAYING and self.player and self.level: self.player.update(self.holding_jump, dt) self.scroll_x += SCROLL_SPEED * dt self.bg_offset = (self.bg_offset + SCROLL_SPEED * 0.3 * dt) % WINDOW_WIDTH self.ground_offset = (self.ground_offset + SCROLL_SPEED * dt) % BLOCK_SIZE # Update camera zoom based on game mode if self.player.mode == GameMode.SHIP: self.target_zoom = 0.75 # Zoom out for ship mode self.target_y_offset = -80 # Shift view up to show ceiling else: self.target_zoom = 1.0 # Zoom in for cube mode self.target_y_offset = 0 # Smooth zoom transition (scale interpolation by dt) zoom_speed = 0.08 * dt * 2 # Multiply by 2 to keep similar feel self.camera_zoom += (self.target_zoom - self.camera_zoom) * zoom_speed self.camera_y_offset += (self.target_y_offset - self.camera_y_offset) * zoom_speed for obs in self.level.obstacles: obs.update(SCROLL_SPEED * dt) self.particles.emit_trail(self.player.x - PLAYER_SIZE // 2 - 5, self.player.y, PLAYER_COLOR_2) self.check_collisions() if self.scroll_x >= self.level.length: self.state = GameState.WIN self.particles.emit_win(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) self.sounds.stop_music() self.particles.update(1 / FPS) # Particles use real time def check_collisions(self): if not self.player or not self.level: return player_hitbox = self.player.get_hitbox() # Check ground collision FIRST (for landing on platforms) new_y, on_ground = self.level.check_ground_collision( self.player.x, self.player.y, self.player.vy, self.scroll_x, self.player.gravity_flipped ) if on_ground and new_y is not None: # Only land if we're moving towards the ground if (not self.player.gravity_flipped and self.player.vy >= 0) or \ (self.player.gravity_flipped and self.player.vy <= 0): self.player.y = new_y self.player.vy = 0 self.player.on_ground = True # Check ceiling collision ceiling_y = self.level.check_ceiling_collision( self.player.x, self.player.y, self.scroll_x, self.player.gravity_flipped ) if ceiling_y is not None: # Only apply if moving towards ceiling if (not self.player.gravity_flipped and self.player.vy < 0) or \ (self.player.gravity_flipped and self.player.vy > 0): self.player.y = ceiling_y self.player.vy = 0 # Now check color-based collision for death, portals, orbs # Use a smaller hitbox to avoid false positives collision = self.level.check_color_collision(self.player.x, self.player.y, self.scroll_x) if collision == 'death': self.die() return elif collision == 'ship' and self.player.mode != GameMode.SHIP: self.player.mode = GameMode.SHIP elif collision == 'cube' and self.player.mode != GameMode.CUBE: self.player.mode = GameMode.CUBE self.player.rotation = 0 elif collision == 'orb' and self.holding_jump: self.player.orb_jump() self.sounds.play("jump") self.particles.emit_jump(self.player.x, self.player.y) # Note: 'solid' is handled by ground/ceiling collision, not death # Also check traditional obstacle collision for portals we explicitly added for obs in self.level.obstacles: if not obs.active: continue if player_hitbox.colliderect(obs.get_hitbox()): if isinstance(obs, Portal) and not obs.used: obs.used = True if obs.portal_type == 'ship': self.player.mode = GameMode.SHIP elif obs.portal_type == 'cube': self.player.mode = GameMode.CUBE self.player.rotation = 0 elif obs.portal_type == 'gravity_up': self.player.gravity_flipped = True elif obs.portal_type == 'gravity_down': self.player.gravity_flipped = False elif isinstance(obs, Block): block_rect = obs.get_hitbox() if self.player.vy > 0 and not self.player.gravity_flipped: if player_hitbox.bottom > block_rect.top and player_hitbox.bottom < block_rect.centery: self.player.y = block_rect.top - PLAYER_SIZE // 2 self.player.vy = 0 self.player.on_ground = True elif self.player.vy < 0 and self.player.gravity_flipped: if player_hitbox.top < block_rect.bottom and player_hitbox.top > block_rect.centery: self.player.y = block_rect.bottom + PLAYER_SIZE // 2 self.player.vy = 0 self.player.on_ground = True else: self.die() elif isinstance(obs, Orb) and self.holding_jump and not obs.used: obs.used = True self.player.orb_jump() self.sounds.play("jump") self.particles.emit_jump(self.player.x, self.player.y) elif obs.is_deadly(): self.die() def die(self): if self.player and not self.player.dead: self.player.dead = True self.particles.emit_death(self.player.x, self.player.y, PLAYER_COLOR_1) self.sounds.play("death") self.sounds.stop_music() self.state = GameState.DEAD def draw_animated_background(self): """Draw the authentic Scratch background with parallax scrolling""" if self.assets.background: # Draw the authentic background, scrolling with parallax bg_scroll = int(self.bg_offset * 0.5) % WINDOW_WIDTH # Draw background twice for seamless scrolling self.screen.blit(self.assets.background, (-bg_scroll, 0)) self.screen.blit(self.assets.background, (WINDOW_WIDTH - bg_scroll, 0)) else: # Fallback: Solid purple/magenta background bg_color = (60, 20, 80) # Dark purple self.screen.fill(bg_color) # Layer 1: Slower moving background shapes (darker purple) layer1_color = (80, 30, 100) layer1_offset = self.bg_offset * 0.3 for i in range(-1, 15): x = (i * 120 - layer1_offset) % (WINDOW_WIDTH + 240) - 120 # Draw subtle background rectangles/shapes pygame.draw.rect(self.screen, layer1_color, (x, 100, 80, 300)) # Layer 2: Faster moving mid-ground (lighter purple) layer2_color = (100, 40, 130) layer2_offset = self.bg_offset * 0.6 for i in range(-1, 20): x = (i * 80 - layer2_offset) % (WINDOW_WIDTH + 160) - 80 # Draw mid-layer shapes pygame.draw.rect(self.screen, layer2_color, (x, 150, 50, 250)) def hsv_to_rgb(self, h: float, s: float, v: float) -> Tuple[int, int, int]: """Convert HSV color to RGB""" if s == 0: r = g = b = int(v * 255) return (r, g, b) i = int(h * 6) f = h * 6 - i p = v * (1 - s) q = v * (1 - f * s) t = v * (1 - (1 - f) * s) i = i % 6 if i == 0: r, g, b = v, t, p elif i == 1: r, g, b = q, v, p elif i == 2: r, g, b = p, v, t elif i == 3: r, g, b = p, q, v elif i == 4: r, g, b = t, p, v else: r, g, b = v, p, q return (int(r * 255), int(g * 255), int(b * 255)) def draw(self): # Dynamic colorful background like real Geometry Dash self.draw_animated_background() if self.state == GameState.MENU: self.draw_menu() elif self.state in (GameState.PLAYING, GameState.DEAD, GameState.WIN): self.draw_game() if self.state == GameState.DEAD: self.draw_death_screen() elif self.state == GameState.WIN: self.draw_win_screen() self.particles.draw(self.screen) pygame.display.flip() def draw_menu(self): # GREEN title "GEOMETRY DASH" with YELLOW above title_yellow = self.font_small.render("Python Clone", True, (255, 230, 0)) # Yellow self.screen.blit(title_yellow, title_yellow.get_rect(center=(WINDOW_WIDTH // 2, 90))) title = self.font_large.render("GEOMETRY DASH", True, (0, 255, 100)) # Green self.screen.blit(title, title.get_rect(center=(WINDOW_WIDTH // 2, 130))) # Draw the player cube moving with particles (like Scratch menu) player_x = WINDOW_WIDTH // 2 player_y = WINDOW_HEIGHT // 2 - 120 cube_sprite = pygame.transform.scale(self.assets.get_player_sprite(GameMode.CUBE), (50, 50)) self.screen.blit(cube_sprite, (player_x - 25, player_y - 25)) # Light blue particles behind player for i in range(5): px = player_x - 30 - i * 12 py = player_y + random.randint(-5, 10) pygame.draw.circle(self.screen, (100, 200, 255), (px, py), 4 - i // 2) # Yellow play button, Green plus, Blue square (menu buttons) button_y = WINDOW_HEIGHT // 2 + 20 # Yellow Play triangle play_x = WINDOW_WIDTH // 2 - 100 pygame.draw.polygon(self.screen, (255, 230, 0), [ (play_x - 20, button_y - 25), (play_x - 20, button_y + 25), (play_x + 25, button_y) ]) play_label = self.font_small.render("PLAY", True, WHITE) self.screen.blit(play_label, play_label.get_rect(center=(play_x, button_y + 50))) # Green Plus plus_x = WINDOW_WIDTH // 2 pygame.draw.rect(self.screen, (0, 255, 100), (plus_x - 5, button_y - 25, 10, 50)) pygame.draw.rect(self.screen, (0, 255, 100), (plus_x - 25, button_y - 5, 50, 10)) plus_label = self.font_small.render("EDITOR", True, WHITE) self.screen.blit(plus_label, plus_label.get_rect(center=(plus_x, button_y + 50))) # Blue Square square_x = WINDOW_WIDTH // 2 + 100 pygame.draw.rect(self.screen, (50, 150, 255), (square_x - 25, button_y - 25, 50, 50)) square_label = self.font_small.render("INFO", True, WHITE) self.screen.blit(square_label, square_label.get_rect(center=(square_x, button_y + 50))) # Level selection below level_y = WINDOW_HEIGHT // 2 + 140 level_text = self.font_small.render("Select Level (← →):", True, WHITE) self.screen.blit(level_text, level_text.get_rect(center=(WINDOW_WIDTH // 2, level_y - 30))) for i in range(1, self.max_levels + 1): x = WINDOW_WIDTH // 2 + (i - 2) * 100 color = (0, 255, 255) if i == self.selected_level else (100, 100, 100) pygame.draw.rect(self.screen, color, (x - 35, level_y - 25, 70, 50), 3 if i == self.selected_level else 1) num = self.font_medium.render(str(i), True, WHITE) self.screen.blit(num, num.get_rect(center=(x, level_y))) inst = self.font_small.render("Press SPACE to start", True, WHITE) self.screen.blit(inst, inst.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT - 60))) controls = self.font_small.render("1-5: Change Skin | Controls: SPACE/UP/CLICK to Jump", True, (150, 150, 150)) self.screen.blit(controls, controls.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT - 30))) def draw_game(self): # Create a game surface to apply camera zoom game_surface = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA) game_surface.fill((0, 0, 0, 0)) # Transparent ground_y = WINDOW_HEIGHT - GROUND_HEIGHT # Draw level tile images FIRST (they form the level visuals) if self.level: self.level.draw_tiles(game_surface, self.scroll_x) # Draw floor area with grid pattern (simple and reliable) ground_color = (30, 15, 40) # Dark purple ground pygame.draw.rect(game_surface, ground_color, (0, ground_y, WINDOW_WIDTH, GROUND_HEIGHT)) # White line at top of ground pygame.draw.line(game_surface, (200, 200, 200), (0, ground_y), (WINDOW_WIDTH, ground_y), 2) # Grid lines that scroll grid_color = (50, 30, 60) grid_offset = int(self.ground_offset) % BLOCK_SIZE for i in range(-1, WINDOW_WIDTH // BLOCK_SIZE + 2): x = i * BLOCK_SIZE - grid_offset pygame.draw.line(game_surface, grid_color, (x, ground_y), (x, WINDOW_HEIGHT), 1) for i in range(GROUND_HEIGHT // BLOCK_SIZE + 1): pygame.draw.line(game_surface, grid_color, (0, ground_y + i * BLOCK_SIZE), (WINDOW_WIDTH, ground_y + i * BLOCK_SIZE), 1) # Draw ceiling line (visible when zoomed out in ship mode) ceiling_y = 50 pygame.draw.rect(game_surface, ground_color, (0, 0, WINDOW_WIDTH, ceiling_y)) pygame.draw.line(game_surface, (200, 200, 200), (0, ceiling_y), (WINDOW_WIDTH, ceiling_y), 2) # Ceiling grid for i in range(-1, WINDOW_WIDTH // BLOCK_SIZE + 2): x = i * BLOCK_SIZE - grid_offset pygame.draw.line(game_surface, grid_color, (x, 0), (x, ceiling_y), 1) # Draw any explicit obstacles (portals that we added manually) if self.level: for obs in self.level.obstacles: if obs.active and -100 < obs.x < WINDOW_WIDTH + 100: obs.draw(game_surface) if self.player: self.player.draw(game_surface, self.particles) # Apply camera zoom and offset if self.camera_zoom != 1.0 or self.camera_y_offset != 0: # Scale the game surface scaled_w = int(WINDOW_WIDTH / self.camera_zoom) scaled_h = int(WINDOW_HEIGHT / self.camera_zoom) # Calculate the view area (centered horizontally, shifted vertically) view_x = (WINDOW_WIDTH - scaled_w) // 2 view_y = int((WINDOW_HEIGHT - scaled_h) // 2 + self.camera_y_offset) # Create subsurface of what we want to show # Clamp to valid bounds view_x = max(0, min(view_x, WINDOW_WIDTH - scaled_w)) view_y = max(0, min(view_y, WINDOW_HEIGHT - scaled_h)) try: view_rect = pygame.Rect(view_x, view_y, scaled_w, scaled_h) view_surface = game_surface.subsurface(view_rect) scaled_surface = pygame.transform.scale(view_surface, (WINDOW_WIDTH, WINDOW_HEIGHT)) self.screen.blit(scaled_surface, (0, 0)) except ValueError: # Fallback if subsurface fails self.screen.blit(game_surface, (0, 0)) else: self.screen.blit(game_surface, (0, 0)) # UI is drawn on top without zoom if self.level: progress = min(1.0, self.scroll_x / self.level.length) bar_x = WINDOW_WIDTH // 2 - 150 pygame.draw.rect(self.screen, PLATFORM_COLOR, (bar_x, 20, 300, 20)) pygame.draw.rect(self.screen, PLAYER_GLOW, (bar_x, 20, int(300 * progress), 20)) pygame.draw.rect(self.screen, WHITE, (bar_x, 20, 300, 20), 2) self.screen.blit(self.font_small.render(f"{int(progress * 100)}%", True, WHITE), (bar_x + 310, 18)) self.screen.blit(self.font_small.render(f"Attempt {self.attempts}", True, WHITE), (20, 20)) self.screen.blit(self.font_small.render(f"Level {self.selected_level}", True, PLAYER_GLOW), (WINDOW_WIDTH - 120, 20)) # FPS counter with 1% and 0.1% lows fps = int(self.clock.get_fps()) fps_color = (100, 255, 100) if fps >= 110 else (255, 255, 100) if fps >= 80 else (255, 100, 100) low1_color = (100, 255, 100) if self.fps_1_low >= 90 else (255, 255, 100) if self.fps_1_low >= 60 else (255, 100, 100) low01_color = (100, 255, 100) if self.fps_01_low >= 80 else (255, 255, 100) if self.fps_01_low >= 50 else (255, 100, 100) self.screen.blit(self.font_small.render(f"FPS: {fps}", True, fps_color), (20, 50)) self.screen.blit(self.font_small.render(f"1%: {self.fps_1_low}", True, low1_color), (20, 75)) self.screen.blit(self.font_small.render(f"0.1%: {self.fps_01_low}", True, low01_color), (20, 100)) def draw_death_screen(self): overlay = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA) overlay.fill((0, 0, 0, 150)) self.screen.blit(overlay, (0, 0)) text = self.font_large.render("YOU DIED!", True, (255, 80, 80)) self.screen.blit(text, text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 40))) if self.level: progress = min(1.0, self.scroll_x / self.level.length) * 100 prog = self.font_medium.render(f"Progress: {int(progress)}%", True, WHITE) self.screen.blit(prog, prog.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 20))) hint = self.font_small.render("Press SPACE to retry or ESC for menu", True, (200, 200, 200)) self.screen.blit(hint, hint.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 80))) def draw_win_screen(self): overlay = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA) overlay.fill((0, 0, 0, 150)) self.screen.blit(overlay, (0, 0)) text = self.font_large.render("LEVEL COMPLETE!", True, PLAYER_GLOW) self.screen.blit(text, text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 40))) attempts = self.font_medium.render(f"Attempts: {self.attempts}", True, WHITE) self.screen.blit(attempts, attempts.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 20))) hint = self.font_small.render("Press SPACE to continue", True, (200, 200, 200)) self.screen.blit(hint, hint.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 80))) def run(self): running = True while running: running = self.handle_events() self.update() self.draw() frame_time = self.clock.tick(FPS) # Track frame times for 1% and 0.1% low calculations self.frame_times.append(frame_time) # Keep last 500 frames (~4 seconds at 120fps) if len(self.frame_times) > 500: self.frame_times.pop(0) # Update 1% and 0.1% lows every 0.5 seconds self.fps_update_timer += frame_time if self.fps_update_timer >= 500 and len(self.frame_times) >= 10: self.fps_update_timer = 0 sorted_times = sorted(self.frame_times, reverse=True) # 1% low = average of worst 1% of frame times count_1 = max(1, len(sorted_times) // 100) count_01 = max(1, len(sorted_times) // 1000) if len(sorted_times) >= 1000 else 1 avg_1 = sum(sorted_times[:count_1]) / count_1 avg_01 = sum(sorted_times[:count_01]) / count_01 self.fps_1_low = int(1000 / avg_1) if avg_1 > 0 else 0 self.fps_01_low = int(1000 / avg_01) if avg_01 > 0 else 0 pygame.quit() if __name__ == "__main__": Game().run()