Вылетает программа на python при запуске через python и при компиляции в exe, хотя при запуске в pycharm работает
Вот демонстрация проблемы: https://youtu.be/0ALaK65O44o У меня есть ещё 4 подобных программы, с ними тоже самое, так что думаю дело не в коде, но всё же вот код:
import pygame
import random
import cv2
import sys
# Инициализация Pygame
pygame.init()
# Размеры окна
screen_width = 1920
screen_height = 1080
# Создание окна
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Magic Ball")
# Изображение фона
background_image = pygame.image.load("ball_bg.png").convert()
# Изображение кнопки закрытия
exit_button_image = pygame.image.load("ball_exit_button.png").convert_alpha()
exit_button_image = pygame.transform.scale(exit_button_image, (275, 155))
exit_button_rect = exit_button_image.get_rect(topleft=(15, 15))
# Изображения для кнопки "Получить ответ"
answer_button_images = [
pygame.image.load("ball_answer_1.png").convert_alpha(),
pygame.image.load("ball_answer_2.png").convert_alpha(),
pygame.image.load("ball_answer_3.png").convert_alpha()
]
answer_button_images = [pygame.transform.scale(image, (800, 180)) for image in answer_button_images]
answer_button_rect = answer_button_images[0].get_rect(topleft=(560, 650))
answer_button_state = 0 # 0 - обычное состояние, 1 - наведена мышь, 2 - нажата кнопка
answer_button_pressed = False # Флаг нажатия кнопки
# Путь к видеофайлам
video_files = [
"ball_yes.mp4",
"ball_no.mp4",
"ball_maybe.mp4",
"ball_probably_yes.mp4",
"ball_probably_no.mp4",
"ball_idk.mp4",
"ball_50_50.mp4",
"ball_ask_again.mp4"
]
# Область, при нажатии в которой проигрывается видео
change_background_rect = pygame.Rect(707, 108, 503, 503)
# Флаг для отслеживания проигрывания видео
playing_video = False
current_video = None
# Параметры поля для ввода текста
input_rect = pygame.Rect(200, 855, 1520, 180)
input_color_inactive = pygame.Color(148, 0, 211)
input_color_active = pygame.Color(255, 0, 255)
input_disabled_color = pygame.Color(50, 0, 50)
input_text_color = (255, 0, 255)
font = pygame.font.Font(None, 90)
max_chars = 60
input_text = ''
input_active = False # Флаг активности поля
input_disabled = False # Флаг для отслеживания, нужно ли заблокировать поле после проигрывания видео
reset_text_after_video = False # Флаг для сброса текста после окончания видео
enter_pressed_time = 0 # Время нажатия Enter
backspace_pressed_time = 0 # Время нажатия Backspace
# Основной цикл программы
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
x, y = pygame.mouse.get_pos()
print(f"Mouse Clicked at ({x}, {y})")
if exit_button_rect.collidepoint(x, y):
running = False # Закрыть программу
elif change_background_rect.collidepoint(x, y):
# Остановка текущего видео
if playing_video:
playing_video = False
current_video.release()
# Выбор случайного видео
video_file = random.choice(video_files)
current_video = cv2.VideoCapture(video_file)
playing_video = True
input_disabled = False
reset_text_after_video = False
elif answer_button_rect.collidepoint(x, y):
answer_button_pressed = True
answer_button_state = 2 # Нажата кнопка
# При нажатии кнопки поле остается активным
elif input_rect.collidepoint(x, y):
input_active = True # При клике поле остается активным
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
answer_button_pressed = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
# При нажатии Enter
input_active = False # Убираем активность поля
enter_pressed_time = pygame.time.get_ticks()
elif event.key == pygame.K_BACKSPACE:
# При нажатии Backspace
if input_active:
input_text = input_text[:-1]
backspace_pressed_time = pygame.time.get_ticks()
else:
# При вводе текста
if input_active and len(input_text) < max_chars:
input_text += event.unicode
# Проверка состояния новой кнопки при наведении мыши
if answer_button_rect.collidepoint(pygame.mouse.get_pos()):
answer_button_state = 1 # Наведена мышь
if answer_button_pressed:
answer_button_state = 2 # Нажата кнопка
# Остановка текущего видео
if playing_video:
playing_video = False
current_video.release()
# Выбор случайного видео
video_file = random.choice(video_files)
current_video = cv2.VideoCapture(video_file)
playing_video = True
# input_text = '' # Стираем текст при выборе ответа
# input_active = False # Убираем активность поля
reset_text_after_video = True # Устанавливаем флаг сброса текста после окончания видео
else:
answer_button_state = 0 # Обычное состояние
# Отрисовка фона
screen.blit(background_image, (0, 0))
# Обработка воспроизведения видео
if playing_video:
ret, frame = current_video.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = pygame.surfarray.make_surface(frame.swapaxes(0, 1))
screen.blit(frame, (0, 0))
else:
# Воспроизведение завершено, возвращаем обычный фон
playing_video = False
current_video.release()
if reset_text_after_video:
input_text = '' # Сбрасываем текст только при установленном флаге
reset_text_after_video = False # Сброс текста выполнен, сбрасываем флаг
input_disabled = True # Возвращаем активность полю после окончания проигрывания видео
# Отрисовка кнопок
screen.blit(exit_button_image, exit_button_rect)
screen.blit(answer_button_images[answer_button_state], answer_button_rect)
# Отрисовка поля для ввода текста
pygame.draw.rect(screen, input_color_active if input_active else input_disabled_color if input_disabled else input_color_inactive, input_rect, 2)
# Ограничение ширины текста
input_text_surface = font.render(input_text, True, input_text_color if input_active else (255, 255, 255) if input_disabled else input_disabled_color)
input_text_width, input_text_height = input_text_surface.get_size()
if input_text_width > input_rect.width - 10:
input_text = input_text[:-1]
if pygame.key.get_pressed()[pygame.K_RETURN]:
current_time = pygame.time.get_ticks()
if current_time - enter_pressed_time > 200:
input_text = input_text[:-1]
# Если Backspace зажат, текст стирается без остановки
if pygame.key.get_pressed()[pygame.K_BACKSPACE]:
current_time = pygame.time.get_ticks()
if current_time - backspace_pressed_time > 50:
input_text = input_text[:-1]
# Отрисовка текста с учетом цвета
if len(input_text) >= max_chars:
pygame.draw.rect(screen, (255, 0, 0), input_rect, 2)
input_text_color = (255, 0, 0)
else:
pygame.draw.rect(screen, input_color_active if input_active else input_disabled_color if input_disabled else input_color_inactive, input_rect, 2)
input_text_color = (255, 0, 255)
text_surface = font.render(input_text if input_active else "Введите ваш вопрос: ", True, input_text_color if input_active else (255, 255, 255) if input_disabled else input_disabled_color)
text_rect = text_surface.get_rect(center=input_rect.center)
screen.blit(text_surface, text_rect)
# Обновление экрана
pygame.display.flip()
# Установка FPS
clock.tick(30)
# Завершение Pygame
pygame.quit()
sys.exit()