popraw i daj cały kod, chodzi o to że niepoprawnie wykrywane jest kliknięcie kafelków…
- User
popraw i daj cały kod, chodzi o to że niepoprawnie wykrywane jest kliknięcie kafelków wyzwań, działa jakby 1/4 pola które da się kliknąć na dany kafelek: import pygame import os import time import math from game.level_manager import load_levels, load_progress, save_progress from game.eightball import EightBallGame from utils.assets import load_ball_images, load_cue_image, load_triangle_image, load_sounds from physics.ball import Ball
ASSETS_UI_DIR = os.path.join(os.path.dirname(file), '../assets/ui')
def load_star_icon(): path = os.path.join(ASSETS_UI_DIR, 'star.png') try: img = pygame.image.load(path).convert_alpha() return pygame.transform.smoothscale(img, (28, 28)) except Exception: return None
def load_star_empty_icon(): path = os.path.join(ASSETS_UI_DIR, 'star_empty.png') try: img = pygame.image.load(path).convert_alpha() return pygame.transform.smoothscale(img, (28, 28)) except Exception: return None
def load_locked_icon(): path = os.path.join(ASSETS_UI_DIR, 'locked.png') try: img = pygame.image.load(path).convert_alpha() return pygame.transform.smoothscale(img, (32, 32)) except Exception: return None
class ChallengeMode: def init(self, screen): self.screen = screen self.levels = sorted(load_levels(), key=lambda lvl: lvl.get('id', 0)) # sortowanie po id self.progress = load_progress() self.selected = 0 self.font = pygame.font.SysFont('arial', 36) self.title_font = pygame.font.SysFont('arial', 50, bold=True) self.info_font = pygame.font.SysFont('arial', 24) self.scroll_offset = 0.0 # float dla płynnego scrolla self.max_scroll = 0.0 self.star_icon = load_star_icon() self.star_empty_icon = load_star_empty_icon() self.locked_icon = load_locked_icon()
# Animacja scrolla self._scroll_anim = 0.0 # Hover i wybór kafelka self.hovered_tile = -1 self.hover_alpha = 0.0 self.hover_continue = False self.clock = pygame.time.Clock() def _truncate_text(self, text, font, max_width): if font.size(text)[0] <= max_width: return text while len(text) > 0 and font.size(text + '...')[0] > max_width: text = text[:-1] return text + '...' def draw(self): dt = self.clock.tick(60) / 1000.0 # elapsed seconds w, h = self.screen.get_width(), self.screen.get_height() self.screen.fill((20, 30, 50)) t = pygame.time.get_ticks() / 1000.0 # --- Animacje tła --- light_surf = pygame.Surface((w, h), pygame.SRCALPHA) lx = int(w//2 + math.sin(t*0.5)*w//3) ly = int(120 + math.cos(t*0.7)*60) pygame.draw.ellipse(light_surf, (255,255,200,30), (lx-220, ly-60, 440, 120)) self.screen.blit(light_surf, (0,0)) for i in range(18): px = int((w/18)*i + (math.sin(t*0.7+i)*30)) py = int((h-60)*((math.sin(t*0.5+i*0.5+t*0.2*i)+1)/2)) + 60 alpha = int(60 + 40*math.sin(t*1.2+i)) pygame.draw.circle(self.screen, (255,255,255,alpha), (px, py), 2) # --- Pasek ukończenia --- total = len(self.levels)*3 earned = sum(self.progress.get(str(lvl.get('id', i+1)), 0) for i, lvl in enumerate(self.levels)) percent = earned/total if total else 0 bar_w = w - 120 bar_x = 60 bar_y = 110 pygame.draw.rect(self.screen, (60,60,60), (bar_x, bar_y, bar_w, 18), border_radius=9) pygame.draw.rect(self.screen, (255, 215, 0), (bar_x, bar_y, int(bar_w*percent), 18), border_radius=9) percent_text = self.info_font.render(f"{int(percent*100)}% ukończono", True, (255,255,255)) self.screen.blit(percent_text, (bar_x + bar_w//2 - percent_text.get_width()//2, bar_y-28)) # --- Tytuł --- title = self.title_font.render('Wyzwania', True, (255, 180, 0)) self.screen.blit(title, (w // 2 - title.get_width() // 2, 24)) # --- Siatka kafelków --- cols = 4 tile_w, tile_h = int(180 * 1.4), 110 # szerokość kafelka zwiększona o 20% margin_x, margin_y = 60, 140 pad_x, pad_y = 32, 30 grid_height = ((len(self.levels) + cols - 1) // cols) * (tile_h + pad_y) - pad_y visible_height = h - margin_y - 40 need_scroll = grid_height > visible_height self.max_scroll = max(0, grid_height - visible_height) if need_scroll else 0 # Aktualizuj animowany scroll self._scroll_anim += (self.scroll_offset - self._scroll_anim) * min(0.35, 8 * abs(self.scroll_offset - self._scroll_anim) / max(visible_height,1)) scroll_draw = int(self._scroll_anim) # Mouse position for hover mx, my = pygame.mouse.get_pos() self.hover_continue = False # Resetuj hover stanu for i, lvl in enumerate(self.levels): row, col = divmod(i, cols) x = margin_x + col * (tile_w + pad_x) y = margin_y + row * (tile_h + pad_y) - scroll_draw # widoczność if y + tile_h < margin_y + 10 or y > h - 40: continue # Fade/clip na górze (kafelki blisko paska postępu) fade_height = 32 # wysokość strefy fade visible_top = margin_y + 10 tile_rect = pygame.Rect(x, y, tile_w, tile_h) fade_alpha = 255 if y < visible_top + fade_height: fade_alpha = max(0, min(255, int(255 * (y + tile_h - visible_top) / fade_height))) stars = self.progress.get(str(lvl.get('id', i + 1)), 0) # Blokada: zablokowane jeśli poprzedni poziom nieukończony gwiazdką locked = False if i > 0: prev_id = str(self.levels[i-1].get('id', i)) if self.progress.get(prev_id, 0) < 1: locked = True selected = (i == self.selected) # Ustal scale jak przy rysowaniu scale = 1.0 if selected: scale = 1.05 + 0.02 * math.sin(pygame.time.get_ticks() / 200) elif self.hovered_tile == i: scale = 1.03 rect = pygame.Rect( int(x - (tile_w * scale - tile_w) // 2), int(y - (tile_h * scale - tile_h) // 2), int(tile_w * scale), int(tile_h * scale) ) hovered = False if rect.collidepoint(mx, my) and not locked: hovered = True self.hover_continue = True self.hovered_tile = i # Animacja hover_alpha if hovered: self.hover_alpha += dt * 6 elif self.hovered_tile == i: self.hover_alpha -= dt * 6 else: self.hover_alpha = max(self.hover_alpha - dt * 6, 0) self.hover_alpha = min(max(self.hover_alpha, 0), 1) base_color = (255, 255, 180) locked_color = (255, 80, 80) normal_color = (220, 220, 220) selected_color = (255, 230, 150) hover_color = (255, 240, 200) draw_color = normal_color if locked: draw_color = locked_color if selected: draw_color = selected_color if hovered: # Zaokrąglony rectangle z lekko jaśniejszą obwódką i "glow" glow_surf = pygame.Surface((tile_w+12, tile_h+12), pygame.SRCALPHA) glow_alpha = int(120 * self.hover_alpha) pygame.draw.rect(glow_surf, (255, 215, 60, glow_alpha), (6, 6, tile_w, tile_h), border_radius=22) self.screen.blit(glow_surf, (x - 6, y - 6)) # Lekko jaśniejszy kolor wypełnienia przy hover lerp_c = [ draw_color[j] + (hover_color[j] - draw_color[j]) * self.hover_alpha for j in range(3) ] draw_color = tuple(map(int, lerp_c)) # Rysuj kafelek z animacją skali scale = 1.0 if selected: # Pulsowanie skali dla wybranego kafelka scale = 1.05 + 0.02 * math.sin(pygame.time.get_ticks() / 200) elif hovered: scale = 1.03 tile_surf = pygame.Surface((int(tile_w*scale), int(tile_h*scale)), pygame.SRCALPHA) pygame.draw.rect(tile_surf, draw_color, (0, 0, tile_surf.get_width(), tile_surf.get_height()), border_radius=20) # Obramowanie border_col = (255, 215, 0) if selected else (40, 40, 40) pygame.draw.rect(tile_surf, border_col, tile_surf.get_rect(), width=3, border_radius=20) # --- Fading na górze kafelka --- if fade_alpha < 255: fade_mask = pygame.Surface(tile_surf.get_size(), pygame.SRCALPHA) fade_mask.fill((255,255,255,fade_alpha)) tile_surf.blit(fade_mask, (0,0), special_flags=pygame.BLEND_RGBA_MULT) # Nazwa i gwiazdki z paddingiem do skali offset_x = int(x - (tile_surf.get_width() - tile_w)//2) offset_y = int(y - (tile_surf.get_height() - tile_h)//2) self.screen.blit(tile_surf, (offset_x, offset_y)) name = lvl.get('name', f'Poziom {i + 1}') name_col = (40, 40, 40) if not locked else (120, 0, 0) name_surf = self.info_font.render(name, True, name_col) # --- Przewijanie tekstu jeśli za długi --- max_name_w = tile_w - 32 name_w = name_surf.get_width() scrollable = name_w > max_name_w if scrollable: # Ustal offset przewijania (oscylacja tam i z powrotem) scroll_time = 2.5 # czas pełnego przejazdu w jedną stronę t = pygame.time.get_ticks() / 1000.0 scroll_range = name_w - max_name_w # Cykliczne przewijanie tam i z powrotem period = 2 * scroll_time phase = (t % period) if phase < scroll_time: offset = int((phase / scroll_time) * scroll_range) else: offset = int(((period - phase) / scroll_time) * scroll_range) name_clip = pygame.Rect(offset, 0, max_name_w, name_surf.get_height()) self.screen.set_clip(pygame.Rect(x + 16, y + 12, max_name_w, name_surf.get_height())) self.screen.blit(name_surf, (x + 16 - offset, y + 12)) self.screen.set_clip(None) else: self.screen.blit(name_surf, (x + 16, y + 12)) # Gwiazdki for s in range(3): cx = x + 40 + s * 36 cy = y + tile_h - 36 if self.star_icon and self.star_empty_icon: if s < stars: self.screen.blit(self.star_icon, (cx - 14, cy - 14)) else: self.screen.blit(self.star_empty_icon, (cx - 14, cy - 14)) else: star_color = (255, 215, 0) if s < stars else (120, 120, 120) pygame.draw.polygon(self.screen, star_color, [ (cx, cy-12), (cx+6, cy-2), (cx+18, cy), (cx+6, cy+2), (cx, cy+12), (cx-6, cy+2), (cx-18, cy), (cx-6, cy-2) ]) # Zablokowany - rysuj kłódkę if locked: if self.locked_icon: self.screen.blit(self.locked_icon, (x + tile_w - 40, y + tile_h - 40)) else: pygame.draw.rect(self.screen, (180, 0, 0), (x + tile_w - 38, y + tile_h - 38, 28, 28), border_radius=8) pygame.draw.circle(self.screen, (120, 0, 0), (x + tile_w - 24, y + tile_h - 38), 14) # --- Scrollbar --- if need_scroll: bar_x = w - 36 bar_y = margin_y bar_w = 16 bar_h = visible_height pygame.draw.rect(self.screen, (60, 60, 60), (bar_x, bar_y, bar_w, bar_h), border_radius=8) thumb_h = max(40, int(bar_h * visible_height / grid_height)) if self.max_scroll <= 0: thumb_y = bar_y else: thumb_y = int(bar_y + (bar_h - thumb_h) * (self._scroll_anim / self.max_scroll)) thumb_rect = pygame.Rect(bar_x + 2, thumb_y, bar_w - 4, thumb_h) # Animacja podświetlenia paska przewijania mx, my = pygame.mouse.get_pos() if pygame.Rect(bar_x, bar_y, bar_w, bar_h).collidepoint(mx, my): # Podświetlenie scrollbar pygame.draw.rect(self.screen, (255, 215, 30), thumb_rect, border_radius=8) else: pygame.draw.rect(self.screen, (255, 180, 0), thumb_rect, border_radius=8) self.scrollbar_rect = pygame.Rect(bar_x, bar_y, bar_w, bar_h) self.scrollbar_thumb = thumb_rect else: self.scrollbar_rect = None self.scrollbar_thumb = None pygame.display.flip() def run(self): clock = pygame.time.Clock() sounds = load_sounds() cols = 4 tile_w, tile_h = int(180 * 1.2), 110 # szerokość kafelka zwięksona o 20% margin_x, margin_y = 60, 140 pad_x, pad_y = 32, 30 dragging_scroll = False drag_offset = 0 while True: self.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.MOUSEWHEEL: mx, my = pygame.mouse.get_pos() # Przewijaj tylko gdy KURSOR NIE JEST nad kafelkiem over_tile = False for i, lvl in enumerate(self.levels): row = i // cols col = i % cols x = margin_x + col * (tile_w + pad_x) y = margin_y + row * (tile_h + pad_y) - self.scroll_offset rect = pygame.Rect(x, y, tile_w, tile_h) if rect.collidepoint(mx, my): over_tile = True break if not over_tile and self.max_scroll > 0: # Scroll kółkiem myszy (odwrócone kierunki) self.scroll_offset = max(0, min(self.scroll_offset - event.y * 40, self.max_scroll)) elif event.type == pygame.MOUSEBUTTONDOWN: mx, my = event.pos # Scrollbar kliknięcie if self.scrollbar_thumb and self.scrollbar_thumb.collidepoint(mx, my): dragging_scroll = True drag_offset = my - self.scrollbar_thumb.y elif self.scrollbar_rect and self.scrollbar_rect.collidepoint(mx, my): # Kliknięcie w pasek przewijania (skok do pozycji) rel = (my - self.scrollbar_rect.y) / self.scrollbar_rect.height self.scroll_offset = int(rel * self.max_scroll) else: # Kliknięcie w kafelek for i, lvl in enumerate(self.levels): row = i // cols col = i % cols x = margin_x + col * (tile_w + pad_x) y = margin_y + row * (tile_h + pad_y) - self.scroll_offset selected = (i == self.selected) # Ustal scale jak przy rysowaniu scale = 1.0 if selected: scale = 1.05 + 0.02 * math.sin(pygame.time.get_ticks() / 200) else: scale = 1.03 if self.hovered_tile == i else 1.0 rect = pygame.Rect( int(x - (tile_w * scale - tile_w) // 2), int(y - (tile_h * scale - tile_h) // 2), int(tile_w * scale), int(tile_h * scale) ) locked = False if i > 0: prev_id = str(self.levels[i - 1].get('id', i)) if self.progress.get(prev_id, 0) < 1: locked = True if rect.collidepoint(mx, my) and not locked: if self.selected == i: sounds['button'].play() self.start_level(self.selected) return else: self.selected = i sounds['button'].play() break elif event.type == pygame.MOUSEBUTTONUP: dragging_scroll = False elif event.type == pygame.MOUSEMOTION: mx, my = event.pos if dragging_scroll and self.scrollbar_rect and self.scrollbar_thumb: thumb_h = self.scrollbar_thumb.height if self.scrollbar_thumb else 1 rel = (my - self.scrollbar_rect.y - drag_offset) / max(1, self.scrollbar_rect.height - thumb_h) rel = max(0.0, min(rel, 1.0)) self.scroll_offset = rel * self.max_scroll else: found = False for i, lvl in enumerate(self.levels): row = i // cols col = i % cols x = margin_x + col * (tile_w + pad_x) y = margin_y + row * (tile_h + pad_y) - self.scroll_offset rect = pygame.Rect(x, y, tile_w, tile_h) locked = False if i > 0: prev_id = str(self.levels[i - 1].get('id', i)) if self.progress.get(prev_id, 0) < 1: locked = True if rect.collidepoint(mx, my) and not locked: self.hovered_tile = i found = True break if not found: self.hovered_tile = -1 elif event.type == pygame.KEYDOWN: if event.key in (pygame.K_UP, pygame.K_DOWN): sounds['button'].play() # Zmiana wybranego poziomu (nawigacja klawiaturą) old_selected = self.selected step = -1 if event.key == pygame.K_UP else 1 for _ in range(len(self.levels)): self.selected = (self.selected + step) % len(self.levels) if self.selected == 0 or self.progress.get(str(self.levels[self.selected-1].get('id', self.selected)), 0) >= 1: break if self.selected == old_selected: self.selected = old_selected # Scrolluj do widoku row = self.selected // cols tile_top = margin_y + row * (tile_h + pad_y) screen_h = self.screen.get_height() if tile_top < self.scroll_offset + margin_y: self.scroll_offset = max(0, tile_top - margin_y) elif tile_top + tile_h > self.scroll_offset + screen_h - 40: self.scroll_offset = min(self.max_scroll, tile_top + tile_h - (screen_h - 40)) elif event.key == pygame.K_RETURN and self.selected != -1: sounds['button'].play() self.start_level(self.selected) return elif event.key == pygame.K_ESCAPE: return def show_stars_earned(self, stars): # (Twój oryginalny kod - nie edytowany) w, h = 420, 220 x = self.screen.get_width() // 2 - w // 2 y = self.screen.get_height() // 2 - h // 2 font = pygame.font.SysFont('arial', 38, bold=True) info = font.render('Ukończono!', True, (255, 255, 0)) star_img = self.star_icon star_empty = self.star_empty_icon star_sound = None try: star_sound = pygame.mixer.Sound(os.path.join(ASSETS_UI_DIR, '../audio/star.wav')) except Exception: star_sound = None for frame in range(30 + 3*8): self.screen.fill((20, 30, 50)) pygame.draw.rect(self.screen, (40, 40, 60), (x, y, w, h), border_radius=24) self.screen.blit(info, (x + w//2 - info.get_width()//2, y + 30)) for s in range(3): cx = x + 90 + s * 80 cy = y + 120 scale = 1.0 appear_frame = 18 + s * 8 if stars > s and frame > appear_frame: scale = min(1.2, 1 + (frame - appear_frame) * 0.04) img = star_img if stars > s and frame > appear_frame else star_empty if img: img_scaled = pygame.transform.smoothscale(img, (int(48*scale), int(48*scale))) self.screen.blit(img_scaled, (cx - 24*scale, cy - 24*scale)) if star_sound and frame == appear_frame+1 and stars > s: star_sound.play() pygame.display.flip() pygame.time.delay(18) pygame.time.delay(900) def start_level(self, idx): # (Twój oryginalny kod funkcji start_level - nieedytowany, kopiuj z oryginału) level = self.levels[idx] while True: self.screen.fill((20, 30, 50)) desc = self.info_font.render(level.get('description', ''), True, (255, 255, 255)) criteria = level.get('star_criteria', {'perfect': 1, 'good': 2, 'pass': 3}) criteria_text = f"Gwiazdki: 3 za {criteria['perfect']} strzał(y), 2 za {criteria['good']}, 1 za {criteria['pass']}" criteria_surf = self.info_font.render(criteria_text, True, (255, 255, 255)) self.screen.blit(desc, (60, 200)) self.screen.blit(criteria_surf, (60, 250)) pygame.display.flip() waiting = True restart = False while waiting: for event in pygame.event.get(): if event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN: waiting = False if event.type == pygame.QUIT: exit() game = EightBallGame(self.screen) game.set_assets(load_ball_images(), load_cue_image(), load_triangle_image()) balls = [Ball(b['number'], b['x'], b['y']) for b in level['balls']] game.set_custom_state(balls, level) challenge_target = [b['number'] for b in level['balls'] if b['number'] != 0] target_pockets = level.get('target_pockets', {}) shot_count = game.run( game.ball_images, game.cue_image, game.triangle_image, player_only=True, challenge_target=challenge_target, target_pockets=target_pockets ) if shot_count == -1: continue if shot_count > 0: stars = 0 if shot_count <= criteria['perfect']: stars = 3 elif shot_count <= criteria['good']: stars = 2 elif shot_count <= criteria['pass']: stars = 1 level_id = str(level.get('id', idx + 1)) self.progress[level_id] = max(self.progress.get(level_id, 0), stars) next_idx = idx + 1 if next_idx < len(self.levels): next_id = str(self.levels[next_idx].get('id', next_idx + 1)) if next_id not in self.progress: self.progress[next_id] = 0 save_progress(self.progress) try: pygame.mixer.music.set_volume(0.2) completed_sound = pygame.mixer.Sound(os.path.join(ASSETS_UI_DIR, '../audio/level_completed.wav')) completed_sound.play() except Exception: pass self.show_stars_earned(stars) try: pygame.mixer.music.set_volume(1.0) except Exception: pass return else: self.screen.fill((20, 30, 50)) msg = self.font.render('Przerwano wyzwanie.', True, (255, 100, 100)) self.screen.blit(msg, (60, 300)) pygame.display.flip() pygame.time.wait(1000) return - Assistant