Загрузка данных


import pygame
import sys
import os
import random

# Инициализация Pygame
pygame.init()
pygame.font.init()

# --- АВТООПРЕДЕЛЕНИЕ ПУТЕЙ (Работает и в .py, и в .exe) ---
def get_path(relative_path):
    if getattr(sys, 'frozen', False):
        base_path = os.path.dirname(sys.executable)
    else:
        base_path = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(base_path, relative_path)

# Размеры экрана
WIDTH, HEIGHT = 900, 650
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("КПП: Пограничный досмотр")

# Цвета
BG_COLOR = (40, 44, 52)
DESK_COLOR = (70, 50, 40)
TEXT_COLOR = (255, 255, 255)
BTN_GREEN = (46, 139, 87)
BTN_RED = (178, 34, 34)
BTN_BLUE = (30, 144, 255)
PANEL_BG = (220, 220, 220)

# Шрифты
font_main = pygame.font.SysFont("Arial", 16)
font_bold = pygame.font.SysFont("Arial", 18, bold=True)
font_large = pygame.font.SysFont("Arial", 22, bold=True)

# Состояние игры
score = 0
lives = 3
current_npc = None
inspecting_phone = False
inspecting_bag = False

# Страны
VALID_COUNTRIES = ["Россия", "Китай", "КНДР"]
INVALID_COUNTRIES = ["США", "Великобритания", "Германия", "Япония"]

# Загрузка списков файлов
def load_image_files(folder_path):
    path = get_path(folder_path)
    if not os.path.exists(path):
        os.makedirs(path, exist_ok=True)
        return []
    valid_exts = ('.png', '.jpg', '.jpeg', '.bmp')
    return [os.path.join(path, f) for f in os.listdir(path) if f.lower().endswith(valid_exts)]

def load_and_scale(image_path, size):
    try:
        img = pygame.image.load(image_path).convert_alpha()
        return pygame.transform.scale(img, size)
    except Exception:
        return create_placeholder(size, "Ошибка")

def create_placeholder(size, text):
    surf = pygame.Surface(size)
    surf.fill((200, 200, 200))
    pygame.draw.rect(surf, (100, 100, 100), surf.get_rect(), 2)
    txt_surf = font_main.render(text, True, (50, 50, 50))
    rect = txt_surf.get_rect(center=(size[0]//2, size[1]//2))
    surf.blit(txt_surf, rect)
    return surf

class NPC:
    def __init__(self):
        # 60% шанс на нелегала/угрозу
        self.is_threat = random.random() < 0.60
        
        # Выбор страны
        if self.is_threat and random.random() < 0.5:
            self.country = random.choice(INVALID_COUNTRIES)
        else:
            self.country = random.choice(VALID_COUNTRIES)

        # Валидация паспорта
        self.passport_valid = (self.country in VALID_COUNTRIES)

        # Фото персонажа (friends)
        friends_files = load_image_files('friends')
        if friends_files:
            self.avatar = load_and_scale(random.choice(friends_files), (200, 240))
        else:
            self.avatar = create_placeholder((200, 240), "Нет фото в friends")

        # Наполнение телефона (phone_photos)
        good_photos = load_image_files(os.path.join('phone_photos', 'good'))
        bad_photos = load_image_files(os.path.join('phone_photos', 'bad'))

        self.phone_photo_path = None
        if self.is_threat and bad_photos:
            self.phone_photo_path = random.choice(bad_photos)
        elif good_photos:
            self.phone_photo_path = random.choice(good_photos)
        
        if self.phone_photo_path:
            self.phone_img = load_and_scale(self.phone_photo_path, (180, 240))
        else:
            self.phone_img = create_placeholder((180, 240), "Галерея пуста")

        # Вещи в сумке (items)
        items_files = load_image_files('items')
        self.items = []
        if items_files:
            sample_count = min(len(items_files), 3)
            selected = random.sample(items_files, sample_count)
            for path in selected:
                name = os.path.splitext(os.path.basename(path))[0]
                if name.lower() == "запрещенная рация":
                    name = "Рация"
                self.items.append((name, load_and_scale(path, (50, 50))))

    def check_verdict(self, player_action):
        # player_action: 'allow' или 'deny'
        should_deny = self.is_threat or (not self.passport_valid)
        if player_action == 'allow':
            return not should_deny
        else:
            return should_deny

def spawn_npc():
    global current_npc, inspecting_phone, inspecting_bag
    current_npc = NPC()
    inspecting_phone = False
    inspecting_bag = False

# Отрисовка документов и правил
def draw_ui():
    screen.fill(BG_COLOR)
    
    # Стол
    pygame.draw.rect(screen, DESK_COLOR, (0, 330, WIDTH, HEIGHT - 330))

    # Окно досмотра (слева)
    pygame.draw.rect(screen, (20, 20, 20), (50, 30, 300, 270))
    if current_npc:
        screen.blit(current_npc.avatar, (100, 45))

    # Уменьшенный лист правил (справа)
    rule_rect = pygame.Rect(400, 30, 450, 180)
    pygame.draw.rect(screen, (245, 235, 210), rule_rect)
    pygame.draw.rect(screen, (100, 80, 50), rule_rect, 3)
    
    rules = [
        "ПРАВИЛА КПП КНДР",
        "1. Пропускать ТОЛЬКО: Россия, Китай, КНДР",
        "2. Граждан США и других стран — СТРЕЛЯТЬ!",
        "3. Досматривайте сумку на вещи и оружие.",
        "4. Проверяйте Галерею (bad-фото = СТРЕЛЯТЬ!)."
    ]
    for i, line in enumerate(rules):
        color = (180, 0, 0) if "СТРЕЛЯТЬ" in line else (0, 0, 0)
        txt = (font_bold if i==0 else font_main).render(line, True, color)
        screen.blit(txt, (415, 40 + i * 30))

    # Увеличенный Паспорт на столе
    passport_rect = pygame.Rect(350, 360, 220, 130)
    pygame.draw.rect(screen, (20, 60, 120), passport_rect)
    pygame.draw.rect(screen, (215, 165, 32), passport_rect, 3)
    
    pass_title = font_large.render("ПАСПОРТ", True, (255, 215, 0))
    screen.blit(pass_title, (pass_title.get_rect(center=(460, 400))))
    
    if current_npc:
        country_txt = font_bold.render(f"Страна: {current_npc.country}", True, TEXT_COLOR)
        screen.blit(country_txt, (360, 440))

    # Кнопки действий
    btn_allow = pygame.Rect(600, 430, 240, 50)
    btn_deny = pygame.Rect(600, 500, 240, 50)
    pygame.draw.rect(screen, BTN_GREEN, btn_allow, border_radius=5)
    pygame.draw.rect(screen, BTN_RED, btn_deny, border_radius=5)

    txt_allow = font_large.render("ВПУСТИТЬ", True, TEXT_COLOR)
    txt_deny = font_large.render("СТРЕЛЯТЬ", True, TEXT_COLOR)
    screen.blit(txt_allow, txt_allow.get_rect(center=btn_allow.center))
    screen.blit(txt_deny, txt_deny.get_rect(center=btn_deny.center))

    # Кнопки проверок
    btn_phone = pygame.Rect(50, 580, 200, 40)
    btn_bag = pygame.Rect(270, 580, 200, 40)
    pygame.draw.rect(screen, BTN_BLUE, btn_phone, border_radius=5)
    pygame.draw.rect(screen, BTN_BLUE, btn_bag, border_radius=5)

    txt_phone = font_bold.render("Проверить телефон", True, TEXT_COLOR)
    txt_bag = font_bold.render("Обыскать сумку", True, TEXT_COLOR)
    screen.blit(txt_phone, txt_phone.get_rect(center=btn_phone.center))
    screen.blit(txt_bag, txt_bag.get_rect(center=btn_bag.center))

    # Оверлей Телефона
    if inspecting_phone and current_npc:
        p_box = pygame.Rect(50, 320, 220, 250)
        pygame.draw.rect(screen, PANEL_BG, p_box, border_radius=10)
        pygame.draw.rect(screen, (50, 50, 50), p_box, 3)
        screen.blit(current_npc.phone_img, (70, 330))

    # Оверлей Сумки
    if inspecting_bag and current_npc:
        b_box = pygame.Rect(270, 320, 250, 250)
        pygame.draw.rect(screen, PANEL_BG, b_box, border_radius=10)
        pygame.draw.rect(screen, (50, 50, 50), b_box, 3)
        
        if not current_npc.items:
            t = font_main.render("Сумка пуста", True, (0, 0, 0))
            screen.blit(t, (290, 340))
        else:
            for idx, (iname, img) in enumerate(current_npc.items):
                screen.blit(img, (280, 330 + idx * 60))
                lbl = font_main.render(iname, True, (0, 0, 0))
                screen.blit(lbl, (340, 345 + idx * 60))

    # Статистика
    stat_txt = font_large.render(f"Очки: {score}  Жизни: {lives}", True, TEXT_COLOR)
    screen.blit(stat_txt, (50, 625))

    return btn_allow, btn_deny, btn_phone, btn_bag

# Главный игровой цикл
spawn_npc()
clock = pygame.time.Clock()

while True:
    btn_allow, btn_deny, btn_phone, btn_bag = draw_ui()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mpos = event.pos

            if btn_phone.collidepoint(mpos):
                inspecting_phone = not inspecting_phone
                inspecting_bag = False
            elif btn_bag.collidepoint(mpos):
                inspecting_bag = not inspecting_bag
                inspecting_phone = False
            elif btn_allow.collidepoint(mpos):
                if current_npc.check_verdict('allow'):
                    score += 100
                else:
                    lives -= 1
                spawn_npc()
            elif btn_deny.collidepoint(mpos):
                if current_npc.check_verdict('deny'):
                    score += 100
                else:
                    lives -= 1
                spawn_npc()

    if lives <= 0:
        score = 0
        lives = 3
        spawn_npc()

    pygame.display.flip()
    clock.tick(30)