Exemple #1
0
class MainCode(QWidget):
    """MainCode of this program"""
    def __init__(self, parent=None):
        super(MainCode, self).__init__(parent)
        self.initUI()

    def initUI(self):
        """constructor"""

        self.main_hbox = QtWidgets.QHBoxLayout()
        self.main_vbox = QtWidgets.QVBoxLayout()

        self.main_elements_created = False
        self.test_elements_created = False
        self.result_elements_created = False
        self.settigs_elements_created = False

        self.square_color_before_change = QtCore.Qt.white
        self.square_color_after_change = QtCore.Qt.red

        self.music_player = QtMultimedia.QMediaPlayer()

        self.resize(1024, 768)
        self.setWindowTitle('Оценка скорости реакции')
        self.main_hbox.addLayout(self.main_vbox)
        self.setLayout(self.main_hbox)

        self.main_stage()

        self.show()

    def create_test_stage_elements(self):
        self.number_indicator = QLCDNumber(self)
        self.number_indicator.setDigitCount(5)
        self.number_indicator.display("00:00")
        self.number_indicator.setFixedSize(400, 100)
        self.timer = QtCore.QTimer()
        self.timer.setInterval(10)
        self.timer.timeout.connect(self.display)
        self.vbox_for_test_elements.addWidget(self.number_indicator,
                                              alignment=QtCore.Qt.AlignHCenter)
        self.vbox_for_test_elements.addStretch(1)

        self.btn_square = QtWidgets.QPushButton(' ', self)
        self.btn_square.setFixedSize(500, 500)
        self.btn_square.setShortcut("Space")
        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button,
                         self.square_color_before_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()
        self.vbox_for_test_elements.addWidget(self.btn_square,
                                              alignment=QtCore.Qt.AlignTop
                                              | QtCore.Qt.AlignHCenter)

        self.vbox_for_test_elements.addStretch(1)
        self.btn_start_stop = QtWidgets.QPushButton('Старт')
        self.btn_start_stop.setFixedSize(300, 50)
        self.btn_start_stop.clicked.connect(self.start_test)
        self.vbox_for_test_elements.addWidget(self.btn_start_stop,
                                              alignment=QtCore.Qt.AlignBottom
                                              | QtCore.Qt.AlignHCenter)

        self.main_elements_created = True
        self.main_vbox.addLayout(self.vbox_for_test_elements)

    def show_test_stage_elements(self):
        self.number_indicator.show()
        self.vbox_for_test_elements.addWidget(self.number_indicator,
                                              alignment=QtCore.Qt.AlignTop
                                              | QtCore.Qt.AlignHCenter)
        self.vbox_for_test_elements.addStretch(1)
        self.vbox_for_test_elements.addWidget(self.btn_square,
                                              alignment=QtCore.Qt.AlignTop
                                              | QtCore.Qt.AlignHCenter)
        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button,
                         self.square_color_before_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()
        self.btn_square.show()

        self.vbox_for_test_elements.addStretch(1)
        self.vbox_for_test_elements.addWidget(self.btn_start_stop,
                                              alignment=QtCore.Qt.AlignBottom
                                              | QtCore.Qt.AlignHCenter)
        self.btn_start_stop.show()
        self.main_vbox.addLayout(self.vbox_for_test_elements)

    def go_to_test_stage(self):
        """create buttons and open test window"""

        self.ms = 0
        self.sec = 0
        self.result_dict = {}
        self.list_of_reaction_times = []
        self.list_of_dicts_reaction_times_num_of_try = []
        self.list_of_falstarts = []

        self.vbox_for_test_elements = QtWidgets.QVBoxLayout()

        if self.test_elements_created == True:
            self.show_test_stage_elements()
        elif self.test_elements_created == False:
            self.create_test_stage_elements()

    def random_second(self, start, end):
        """generate random time in ms"""
        random_sec = start + random.randrange((end - start) * 10) / 10
        return random_sec

    def btn_square_click(self):
        """Останавливает таймер, обовляет счётчик попыток, вносит время реакции в список, обновляет цвет квадрата, БЕЗ звука"""

        self.timer.stop()
        self.count_of_try += 1

        if self.count_of_try == 100:
            self.stop_test_and_go_to_result_stage()

        if self.ms != 0:
            self.list_of_reaction_times.append(
                float(str(self.sec) + "." + str(self.ms)))
            self.list_of_dicts_reaction_times_num_of_try.append(
                {self.count_of_try: float(str(self.sec) + "." + str(self.ms))})
            self.test_start_timer()
        else:
            self.list_of_falstarts.append(self.count_of_try)

        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button,
                         self.square_color_before_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()
        self.sec = 0
        self.ms = 0
        self.number_indicator.display("%02d:%02d" % (self.sec, self.ms))

    def btn_square_click_with_sound(self):
        """Останавливает таймер, обовляет счётчик попыток, вносит время реакции в список, обновляет цвет квадрата, СО звуком"""

        self.timer.stop()
        self.count_of_try += 1

        if self.count_of_try == 100:
            self.stop_test_and_go_to_result_stage()

        if self.ms != 0:
            self.list_of_reaction_times.append(
                float(str(self.sec) + "." + str(self.ms)))
            self.list_of_dicts_reaction_times_num_of_try.append(
                {self.count_of_try: float(str(self.sec) + "." + str(self.ms))})
            self.test_start_timer_with_sonund()
        else:
            self.list_of_falstarts.append(self.count_of_try)

        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button,
                         self.square_color_before_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()
        self.sec = 0
        self.ms = 0
        self.number_indicator.display("%02d:%02d" % (self.sec, self.ms))

    def start_timer(self):
        """Вызывает срабатывание таймера """
        self.timer.start()

    def change_color_start_test_timer(self):
        """Запускает таймер, меняет цвет квадрата, без звука"""
        self.start_timer()

        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button, self.square_color_after_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()

    def change_color_start_test_timer_with_sound(self):
        """Запускает таймер, меняет цвет квадрата, запускает срабатывание звука"""
        self.start_timer()

        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button, self.square_color_after_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()
        self.music_player.play()

    def test_start_timer(self):
        """Запускает внутренний таймер до смены цвета"""
        QtCore.QTimer.singleShot((self.random_second(0.5, 3.0) * 1000),
                                 self.change_color_start_test_timer)

    def test_start_timer_with_sonund(self):
        """Запускает внутренний таймер до смены цвета и запуска звука"""
        QtCore.QTimer.singleShot((self.random_second(0.5, 3.0) * 1000),
                                 self.change_color_start_test_timer_with_sound)

    def start_test(self):
        """Выбирает какой метод запустить: со звуком или без звука, меняет название и функцию кнопки'старт', объявляет счётчик попыток"""
        try:
            if self.sound_checkbox.checkState() == 2:
                self.test_start_timer_with_sonund()
                self.btn_square.clicked.connect(
                    self.btn_square_click_with_sound)
            elif self.sound_checkbox.checkState() == 0:
                self.test_start_timer()
                self.btn_square.clicked.connect(self.btn_square_click)
        except:
            self.test_start_timer()
            self.btn_square.clicked.connect(self.btn_square_click)

        self.count_of_try = 0

        self.btn_start_stop.setText('Стоп')
        self.btn_start_stop.clicked.disconnect()
        self.btn_start_stop.clicked.connect(
            self.stop_test_and_go_to_result_stage)
        self.btn_start_stop.setShortcut("Esc")

    def stop_test_and_go_to_result_stage(self):

        self.timer.stop()

        self.number_indicator.hide()
        self.btn_square.hide()
        self.btn_start_stop.hide()

        self.main_vbox.removeWidget(self.number_indicator)
        self.main_vbox.removeWidget(self.btn_square)
        self.main_vbox.removeWidget(self.btn_start_stop)

        self.clear_the_main_box_from_stretch_and_space()

        self.go_to_result_stage()

    def rounding_func(self, numObj, digits=3):
        """Обрезает знаки за запятой"""
        return f"{numObj:.{digits}f}"

    def back_to_main_window(self):
        """Скрывает все элементы из окна с результатами и возвращается на главное окно"""

        self.table.hide()
        self.graph_of_results.hide()
        self.btn_go_to_main_menu.hide()
        self.btn_import.hide()
        self.clear_the_main_box_from_stretch_and_space()

        self.main_stage()

    def fill_in_the_table(self):
        list_of_table_column_names = [
            'Количество попыток', 'Лучший результат',
            'Номера попыток с лучшим результатом', 'Хуший результат',
            'Номера попыток с худшим результатом', 'Количество фальстартов',
            'Номера попыток с фальстартами', 'Средний результат'
        ]

        for element in list_of_table_column_names:
            column_name = QtGui.QStandardItem(element)
            self.model.setItem(0, self.counter_for_tries_for_table,
                               column_name)
            self.counter_for_tries_for_table += 1

        self.table.resizeRowsToContents()

        self.model.setItem(1, 0, QtGui.QStandardItem(str(self.count_of_try)))

        self.model.setItem(
            1, 1, QtGui.QStandardItem(str(min(self.list_of_reaction_times))))
        list_of_best_tries = []
        for elem in self.list_of_dicts_reaction_times_num_of_try:
            if elem[list(elem)[0]] == min(self.list_of_reaction_times):
                list_of_best_tries.append(list(elem)[0])
        string_of_best_tries = ''
        for num in list_of_best_tries:
            string_of_best_tries += str(num) + ', '
        self.model.setItem(1, 2,
                           QtGui.QStandardItem(str(string_of_best_tries)))

        self.model.setItem(
            1, 3, QtGui.QStandardItem(str(max(self.list_of_reaction_times))))
        list_of_worst_tries = []
        for elem in self.list_of_dicts_reaction_times_num_of_try:
            if elem[list(elem)[0]] == max(self.list_of_reaction_times):
                list_of_worst_tries.append(list(elem)[0])
        string_of_worst_tries = ''
        for num in list_of_worst_tries:
            string_of_worst_tries += str(num) + ', '
        self.model.setItem(1, 4,
                           QtGui.QStandardItem(str(string_of_worst_tries)))

        self.model.setItem(
            1, 5, QtGui.QStandardItem(str(len(self.list_of_falstarts))))
        numbers_of_falstarts = ''
        for num in self.list_of_falstarts:
            numbers_of_falstarts += str(num) + ', '
        self.model.setItem(1, 6,
                           QtGui.QStandardItem(str(len(numbers_of_falstarts))))

        var_for_average_result = 0
        for elem in self.list_of_dicts_reaction_times_num_of_try:
            var_for_average_result += elem[list(elem)[0]]
        average_result = var_for_average_result / len(
            self.list_of_dicts_reaction_times_num_of_try)

        self.model.setItem(
            1, 7, QtGui.QStandardItem(str(self.rounding_func(average_result))))

    def show_result_elements(self):
        self.table.show()
        self.result_stage_vbox.addWidget(self.table,
                                         alignment=QtCore.Qt.AlignTop
                                         | QtCore.Qt.AlignHCenter)
        self.result_stage_vbox.addStretch(1)

        #Создаёт график потому что это не Qt элемент и ему нужно перерисовываться
        self.graph_of_results = PlotCanvas(
            self,
            width=10,
            height=5,
            data_for_graph=self.list_of_dicts_reaction_times_num_of_try)
        self.result_stage_vbox.addWidget(self.graph_of_results,
                                         alignment=QtCore.Qt.AlignTop
                                         | QtCore.Qt.AlignHCenter)

        self.result_stage_vbox.addStretch(1)

        self.btn_go_to_main_menu.show()
        self.result_stage_hbox.addWidget(self.btn_go_to_main_menu)
        self.result_stage_hbox.addStretch(1)

        self.btn_import.show()
        self.result_stage_hbox.addWidget(self.btn_import)
        self.result_stage_hbox.addStretch(1)

        self.result_stage_hbox.addSpacing(200)
        self.result_stage_vbox.addLayout(self.result_stage_hbox)

    def create_result_elements(self):
        self.table = QtWidgets.QTableView()
        self.table.setFixedSize(819, 138)
        self.model = QtGui.QStandardItemModel(2, 8)
        self.table.setModel(self.model)

        self.result_stage_vbox.addWidget(self.table,
                                         alignment=QtCore.Qt.AlignTop
                                         | QtCore.Qt.AlignHCenter)
        self.result_stage_vbox.addStretch(1)

        self.graph_of_results = PlotCanvas(
            self,
            width=10,
            height=5,
            data_for_graph=self.list_of_dicts_reaction_times_num_of_try)
        self.result_stage_vbox.addWidget(self.graph_of_results,
                                         alignment=QtCore.Qt.AlignTop
                                         | QtCore.Qt.AlignHCenter)

        self.result_stage_vbox.addStretch(1)

        self.btn_go_to_main_menu = QtWidgets.QPushButton(
            'Вернуться на главное меню')
        self.btn_go_to_main_menu.setFixedSize(200, 50)
        self.btn_go_to_main_menu.clicked.connect(self.back_to_main_window)
        self.result_stage_hbox.addWidget(self.btn_go_to_main_menu)
        self.result_stage_hbox.addStretch(1)

        self.btn_import = QtWidgets.QPushButton('Импорт')
        self.btn_import.setFixedSize(100, 50)
        self.btn_import.clicked.connect(self.create_csv_table)
        self.result_stage_hbox.addWidget(self.btn_import)
        self.result_stage_hbox.addStretch(1)

        self.result_stage_hbox.addSpacing(200)
        self.result_stage_vbox.addLayout(self.result_stage_hbox)

    def go_to_result_stage(self):
        """Создаёт финальное окно результатов"""

        if bool(self.list_of_reaction_times) == False:
            self.main_stage()
            return

        self.counter_for_tries_for_table = 0

        self.result_stage_vbox = QtWidgets.QVBoxLayout()
        self.result_stage_hbox = QtWidgets.QHBoxLayout()

        if self.result_elements_created == True:
            self.show_result_elements()
        elif self.result_elements_created == False:
            self.create_result_elements()

        self.fill_in_the_table()

        self.main_vbox.addLayout(self.result_stage_vbox)

    def display(self):
        """Отвечает за обновление дисплея таймера"""
        self.number_indicator.display("%02d:%02d" % (self.sec, self.ms))
        if self.ms != 99:
            self.ms += 1
        else:
            self.ms = 0
            if self.sec != 59:
                self.sec += 1

    def background_color_window(self):
        """Создаёт окно и позволяет выбрать и обновить цвет фона"""
        background_color = QtWidgets.QColorDialog.getColor(
            parent=self, title='Выбор цвета фона')
        if background_color.isValid():
            palette = self.palette()
            palette.setColor(QtGui.QPalette.Normal, QtGui.QPalette.Background,
                             background_color)
            palette.setColor(QtGui.QPalette.Inactive,
                             QtGui.QPalette.Background, background_color)
            self.setPalette(palette)

    def square_color_window(self):
        """Создаёт окно и позволяет выбрать и обновить цвет квадрата"""
        self.square_color_before_change = QtWidgets.QColorDialog.getColor(
            parent=self, title='Выбор цвета квадрата')
        if self.square_color_before_change.isValid():
            palette = self.palette()
            palette.setColor(QtGui.QPalette.Button,
                             self.square_color_before_change)
            self.btn_square.setPalette(palette)
            self.btn_square.update()

    def square_after_change_color_window(self):
        """Создаёт окно и позволяет выбрать и обновить цвет квадрата после смены цвета"""
        color_after_change = QtWidgets.QColorDialog.getColor(
            parent=self, title='Выбор цвета квадрата')
        if color_after_change.isValid():
            self.square_color_after_change = color_after_change
            palette = self.palette()
            palette.setColor(QtGui.QPalette.Button,
                             self.square_color_after_change)
            self.btn_square.setPalette(palette)
            self.btn_square.update()

    def change_square_settings_color_before(self):
        """Красит квадрат в цвет до смены цвета"""
        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button,
                         self.square_color_before_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()

    def change_square_settings_color_after(self):
        """Красит квадрат в цвет после смены цвета"""
        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button, self.square_color_after_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()

    def open_music_file(self):
        """Открывает окно для выбора музыкального файла"""
        file = QtWidgets.QFileDialog.getOpenFileUrl(
            parent=self,
            caption="Выберите звуковой файл",
            filter="Звуковые файлы (*.mp3 *.ac3)")

        self.music_player.setMedia(QtMultimedia.QMediaContent(file[0]))

        if self.btn_play_music.isHidden():
            self.btn_play_music.show()

        with open(
                'config.json',
                'w',
                encoding="utf-8",
        ) as config_file:
            config_file.write(file[0].toString())

    def go_to_main_stage_from_setting(self):
        self.btn_go_back.hide()
        self.btn_background_color_settings.hide()
        self.btn_square_color_settings.hide()
        self.btn_square.hide()
        self.sound_option_text.hide()
        self.sound_checkbox.hide()
        self.btn_square_after_change_color_settings.hide()
        self.btn_square_color_before_change_color.hide()
        self.btn_square_color_after_change_color.hide()
        self.btn_open_music.hide()
        self.label_music_status.hide()
        self.btn_play_music.hide()
        self.main_stage()

    def show_settings_elements(self):
        self.btn_go_back.show()
        self.settings_hbox_1.addWidget(self.btn_go_back,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignLeft)

        self.btn_background_color_settings.show()
        self.settings_hbox_1.addWidget(self.btn_background_color_settings,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignLeft)

        self.btn_square_color_settings.show()
        self.settings_hbox_1.addWidget(self.btn_square_color_settings,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignLeft)

        self.btn_square_after_change_color_settings.show()
        self.settings_hbox_1.addWidget(
            self.btn_square_after_change_color_settings,
            alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
        self.settings_hbox_1.addStretch(1)

        self.btn_square_color_before_change_color.show()
        self.settings_hbox_1.addWidget(
            self.btn_square_color_before_change_color,
            alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)

        self.btn_square_color_after_change_color.show()
        self.settings_hbox_1.addWidget(
            self.btn_square_color_after_change_color,
            alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)
        self.settings_vbox_1.addLayout(self.settings_hbox_1)

        self.btn_square.show()
        self.settings_vbox_1.addStretch(1)
        self.settings_vbox_1.addWidget(self.btn_square,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignHCenter)
        self.settings_vbox_1.addStretch(1)

        self.btn_open_music.show()
        self.settings_hbox_2.addWidget(self.btn_open_music)
        self.settings_hbox_2.addStretch(1)

        self.label_music_status.show()
        self.settings_hbox_2.addWidget(self.label_music_status)
        self.settings_hbox_2.addStretch(1)

        self.btn_play_music.show()
        self.settings_hbox_2.addWidget(self.btn_play_music)
        self.settings_hbox_2.addStretch(1)

        self.sound_option_text.show()
        self.settings_hbox_2.addWidget(self.sound_option_text)

        self.sound_checkbox.show()
        self.settings_hbox_2.addWidget(self.sound_checkbox)
        self.settings_hbox_2.addStretch(1)

        self.settings_vbox_1.addLayout(self.settings_hbox_2)
        self.main_vbox.addLayout(self.settings_vbox_1)

    def create_settings_elemens(self):
        self.btn_go_back = QtWidgets.QPushButton('Назад', self)
        self.btn_go_back.setFixedSize(50, 50)
        self.btn_go_back.clicked.connect(self.go_to_main_stage_from_setting)
        self.settings_hbox_1.addWidget(self.btn_go_back,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignLeft)

        self.btn_background_color_settings = QtWidgets.QPushButton(
            'Цвет фона', self)
        self.btn_background_color_settings.setFixedSize(100, 50)
        self.btn_background_color_settings.clicked.connect(
            self.background_color_window)
        self.settings_hbox_1.addWidget(self.btn_background_color_settings,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignLeft)

        self.btn_square_color_settings = QtWidgets.QPushButton(
            'Цвет квадрата до смены цвета', self)
        self.btn_square_color_settings.setFixedSize(250, 50)
        self.btn_square_color_settings.clicked.connect(
            self.square_color_window)
        self.settings_hbox_1.addWidget(self.btn_square_color_settings,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignLeft)

        self.btn_square_after_change_color_settings = QtWidgets.QPushButton(
            'Цвет квадрата после смены цвета', self)
        self.btn_square_after_change_color_settings.setFixedSize(250, 50)
        self.btn_square_after_change_color_settings.clicked.connect(
            self.square_after_change_color_window)
        self.settings_hbox_1.addWidget(
            self.btn_square_after_change_color_settings,
            alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
        self.settings_hbox_1.addStretch(1)

        self.btn_square_color_before_change_color = QtWidgets.QPushButton(
            'Квадрат до смены цвета', self)
        self.btn_square_color_before_change_color.setFixedSize(200, 50)
        self.btn_square_color_before_change_color.clicked.connect(
            self.change_square_settings_color_before)
        self.settings_hbox_1.addWidget(
            self.btn_square_color_before_change_color,
            alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)

        self.btn_square_color_after_change_color = QtWidgets.QPushButton(
            'Квадрат после смены цвета', self)
        self.btn_square_color_after_change_color.setFixedSize(200, 50)
        self.btn_square_color_after_change_color.clicked.connect(
            self.change_square_settings_color_after)
        self.settings_hbox_1.addWidget(
            self.btn_square_color_after_change_color,
            alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)
        self.settings_vbox_1.addLayout(self.settings_hbox_1)

        self.btn_square = QtWidgets.QPushButton(' ', self)
        self.btn_square.setAutoFillBackground(True)
        self.btn_square.setFixedSize(
            500, 500)  # установить 2 переменные для настроек размера
        palette = self.palette()
        palette.setColor(QtGui.QPalette.Button,
                         self.square_color_before_change)
        self.btn_square.setPalette(palette)
        self.btn_square.update()
        self.settings_vbox_1.addStretch(1)
        self.settings_vbox_1.addWidget(self.btn_square,
                                       alignment=QtCore.Qt.AlignTop
                                       | QtCore.Qt.AlignHCenter)
        self.settings_vbox_1.addStretch(1)

        self.btn_open_music = QtWidgets.QPushButton("&Открыть файл...")
        self.btn_open_music.clicked.connect(self.open_music_file)
        self.settings_hbox_2.addWidget(self.btn_open_music)
        self.settings_hbox_2.addStretch(1)

        self.label_music_status = QtWidgets.QLabel('')
        self.label_music_status.hide()
        self.settings_hbox_2.addWidget(self.label_music_status)
        self.settings_hbox_2.addStretch(1)

        self.btn_play_music = QtWidgets.QPushButton('Прослушать')
        self.btn_play_music.clicked.connect(self.music_player.play)
        self.btn_play_music.hide()
        self.settings_hbox_2.addWidget(self.btn_play_music)
        self.settings_hbox_2.addStretch(1)

        self.sound_option_text = QtWidgets.QLabel("Наличие звукового сигнала")
        font_obj_for_label = QtGui.QFont('Segoe UI', pointSize=30)
        self.sound_option_text.setFont(font_obj_for_label)
        self.sound_option_text.show()
        self.settings_hbox_2.addWidget(self.sound_option_text)

        self.sound_checkbox = QtWidgets.QCheckBox(self)
        self.settings_hbox_2.addWidget(self.sound_checkbox)
        self.settings_hbox_2.addStretch(1)

        self.settings_vbox_1.addLayout(self.settings_hbox_2)
        self.main_vbox.addLayout(self.settings_vbox_1)

        self.settigs_elements_created = True

    def go_to_settings_stage(self):
        """Открывает окно настроек, создаёт все кнопки и всё там делает"""

        self.settings_hbox_1 = QtWidgets.QHBoxLayout()
        self.settings_vbox_1 = QtWidgets.QVBoxLayout()
        self.settings_hbox_2 = QtWidgets.QHBoxLayout()

        if self.settigs_elements_created == True:
            self.show_settings_elements()
        elif self.settigs_elements_created == False:
            self.create_settings_elemens()

        try:
            with open(
                    'config.json',
                    'r',
                    encoding="utf-8",
            ) as config_file:
                self.path_to_the_installed_music = config_file.read()

            self.music_player.setMedia(
                QtMultimedia.QMediaContent(
                    QtCore.QUrl(self.path_to_the_installed_music)))
            self.label_music_status.setText('Звук установлен')
            self.label_music_status.show()
            self.btn_play_music.show()
        except:
            self.label_music_status.setText('Звук не установлен')
            self.label_music_status.show()

    def clear_the_main_box_from_stretch_and_space(self):

        for i in range(self.main_vbox.count()):
            layout_item = self.main_vbox.itemAt(i)
            print(layout_item)
            if layout_item.layout() is not None:
                self.main_vbox.removeItem(layout_item)

    def go_to_test_stage_from_main_stage(self):

        self.title.hide()
        self.btn_start_test.hide()
        self.btn_settings.hide()

        self.main_vbox.removeWidget(self.title)
        self.main_vbox.removeWidget(self.btn_start_test)
        self.main_vbox.removeWidget(self.btn_settings)

        self.clear_the_main_box_from_stretch_and_space()

        self.go_to_test_stage()

    def go_to_settings_stage_from_main_stage(self):

        self.title.hide()
        self.btn_start_test.hide()
        self.btn_settings.hide()

        self.main_vbox.removeWidget(self.title)
        self.main_vbox.removeWidget(self.btn_start_test)
        self.main_vbox.removeWidget(self.btn_settings)

        self.clear_the_main_box_from_stretch_and_space()

        self.go_to_settings_stage()

    def create_main_stage_elements(self):

        self.title = QtWidgets.QLabel("Оценка скорости реакции", self)
        font_obj_for_label = QtGui.QFont('Segoe UI', pointSize=50)
        self.title.setFont(font_obj_for_label)
        self.main_vbox.addWidget(self.title,
                                 alignment=QtCore.Qt.AlignTop
                                 | QtCore.Qt.AlignHCenter)

        self.btn_start_test = QtWidgets.QPushButton('Тест', self)
        self.btn_start_test.setFixedSize(300, 50)
        self.btn_start_test.clicked.connect(
            self.go_to_test_stage_from_main_stage)
        self.main_vbox.addWidget(self.btn_start_test,
                                 alignment=QtCore.Qt.AlignTop
                                 | QtCore.Qt.AlignCenter)

        self.btn_settings = QtWidgets.QPushButton('Настройки', self)
        self.btn_settings.setFixedSize(300, 50)
        self.btn_settings.clicked.connect(
            self.go_to_settings_stage_from_main_stage)
        self.main_vbox.addWidget(self.btn_settings,
                                 alignment=QtCore.Qt.AlignTop
                                 | QtCore.Qt.AlignCenter)

        self.settings_elements_created = True

    def show_main_stage_elements(self):
        self.title.show()
        self.main_vbox.addWidget(self.title,
                                 alignment=QtCore.Qt.AlignTop
                                 | QtCore.Qt.AlignHCenter)

        self.btn_start_test.show()
        self.main_vbox.addWidget(self.btn_start_test,
                                 alignment=QtCore.Qt.AlignTop
                                 | QtCore.Qt.AlignCenter)

        self.btn_settings.show()
        self.main_vbox.addWidget(self.btn_settings,
                                 alignment=QtCore.Qt.AlignTop
                                 | QtCore.Qt.AlignCenter)

    def main_stage(self):
        """Создаёт главное окно"""
        self.clear_the_main_box_from_stretch_and_space()

        if self.main_elements_created == True:
            self.show_main_stage_elements()
        elif self.main_elements_created == False:
            self.create_main_stage_elements()

    def create_csv_table(self):

        with open('result_table.csv', "w", newline='') as csv_file:
            writer = csv.writer(csv_file, delimiter=',')
            count_num_and_try_time = []
            for element in self.list_of_dicts_reaction_times_num_of_try:
                count_num_and_try_time.append(
                    [list(element)[0], element[list(element)[0]]])
            for element in count_num_and_try_time:
                writer.writerow(element)
Exemple #2
0
class DisplayCapteur(anr.Capteur, QWidget):
    """Une combinaison de Capteur et d'un QWidget"""
    def __init__(self, parent_robot, nom, min_val, max_val, step=1, unite=None):
        QWidget.__init__(self)
        anr.Capteur.__init__(self, nom, min_val, max_val, step, unite)
        self.parent_robot = parent_robot
        self.backend = self.parent_robot.backend
        self.updated_outside = False
        self.ping = 0

        # Création des widgets de l'équipement
        self.gridlayout_eqp = QGridLayout(self)
        self.spaceritem_equipement = QSpacerItem(1, 15)
        self.label_name_equipement = QLabel()
        self.label_message_equipement = QLabel("Dernière MAJ (s)")
        self.lcdnumber_ping_eqp = QLCDNumber()

        self.lcdnumber_eqp = QLCDNumber()
        self.progressbar_eqp = QProgressBar()

        # Configuration des widgets de l'équipement
        self.ui_setup_equipement()

    def ui_setup_equipement(self):
        """ Configure l'ensemble des widgets de l'équipement"""

        self.gridlayout_eqp.setAlignment(QT_TOP)

        if self.unite == "None" or self.unite is None:
            self.label_name_equipement.setText(self.nom)
        else:
            self.label_name_equipement.setText('{0} ({1})'.format(self.nom, self.unite))
        self.gridlayout_eqp.addWidget(self.label_name_equipement, 0, 0, 1, 1, QT_LEFT)

        self.label_message_equipement.setText("Dernière MAJ (s)")
        self.gridlayout_eqp.addWidget(self.label_message_equipement, 2, 0, 1, 2, QT_LEFT)
        self.lcdnumber_ping_eqp.setMaximumSize(QSize(75, 25))
        self.lcdnumber_ping_eqp.setFixedSize(QLCD_SIZE2)
        self.gridlayout_eqp.addWidget(self.lcdnumber_ping_eqp, 2, 1, 1, 1, QT_RIGHT)

        if self.min_val is None or self.max_val is None or self.step is None:
            self.lcdnumber_eqp.setMinimumSize(150, 30)
            self.gridlayout_eqp.addWidget(self.lcdnumber_eqp, 0, 1, 1, 1, QT_RIGHT)
            self.progressbar_eqp.hide()
        else:
            self.progressbar_eqp.setRange(int(self.min_val), int(self.max_val))
            self.progressbar_eqp.setAlignment(QT_CENTER)
            self.progressbar_eqp.setFormat("%v")
            self.progressbar_eqp.setFixedSize(150, 30)
            self.gridlayout_eqp.addWidget(self.progressbar_eqp, 0, 1, 1, 1, QT_RIGHT)
            self.lcdnumber_eqp.hide()

    #calcul et mise à jour du ping
    def update_ping(self):
        """Mise à jour du ping de l'équipement"""
        self.ping = round(abs(time.time() - self.last_updt), 1)
        self.lcdnumber_ping_eqp.display(format(self.ping))

    def set_state(self, valeur):
        """Change la valeur

        Entrée:
        - valeur (float)"""
        anr.Binaire.set_state(self, valeur)
        self.updated_outside = True
        if self.valeur is not None:
            self.lcdnumber_eqp.display(self.valeur)
            self.progressbar_eqp.setValue(int(self.valeur))
        self.updated_outside = False
Exemple #3
0
class MainWindow(QWidget):
    def __init__(self, ser, sio):
        super().__init__()

        # Setup the colour palette
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(40, 40, 40))
        palette.setColor(QPalette.WindowText, QColor(230, 230, 230))
        palette.setColor(QPalette.Base, QColor(252, 252, 252))
        palette.setColor(QPalette.AlternateBase, QColor(239, 240, 241))
        palette.setColor(QPalette.ToolTipBase, QColor(239, 240, 241))
        palette.setColor(QPalette.ToolTipText, QColor(49, 54, 59))
        palette.setColor(QPalette.Text, QColor(0, 0, 0))
        palette.setColor(QPalette.Button, QColor(85, 90, 95))
        palette.setColor(QPalette.ButtonText, QColor(50, 50, 50))
        palette.setColor(QPalette.BrightText, QColor(255, 255, 255))
        palette.setColor(QPalette.Link, QColor(41, 128, 185))
        palette.setColor(QPalette.Highlight, QColor(136, 136, 136))
        palette.setColor(QPalette.HighlightedText, QColor(239, 240, 241))
        palette.setColor(QPalette.Disabled, QPalette.Light, Qt.white)
        palette.setColor(QPalette.Disabled, QPalette.Shadow,
                         QColor(234, 234, 234))
        self.setPalette(palette)

        self.ser = ser
        self.sio = sio
        self.start = 1
        self.maxforce = 0000.00
        self.oldforce = 0.0
        self.force = 0.0
        self.initUI()

    def initUI(self):
        self.grid = QGridLayout()
        self.teams = {}
        self.currentteam = [QListWidgetItem_Team()]
        self.chartView = QChartView()
        self.loadNewGraph = True

        # LCD Widget to display the force
        self.forcelcd = QLCDNumber(7, self)
        self.forcelcd.setStyleSheet(
            "color: rgb(0, 210, 0); border-image: url(background3.png) stretch; background-repeat: no-repeat;"
        )
        lcdpalette = self.forcelcd.palette()
        lcdpalette.setColor(lcdpalette.Light, QtGui.QColor(0, 255, 0))
        lcdpalette.setColor(lcdpalette.Dark, QtGui.QColor(0, 0, 0))
        self.forcelcd.setPalette(lcdpalette)
        self.forcelcd.setFrameStyle(0)

        # Push buttons
        zero = QPushButton('Zero Scale', self)
        clearmax = QPushButton('Reset', self)
        clearmax.clicked.connect(self.reset)
        export = QPushButton('Export', self)
        togglestart = QPushButton('Start/Stop', self)

        # Push Button Functions
        zero.clicked.connect(self.zero_scale)
        clearmax.clicked.connect(self.reset)
        export.clicked.connect(self.exportTeams)
        togglestart.clicked.connect(self.toggle)

        # Textbox to enter in team name
        self.teaminput = QLineEdit()
        self.teaminput.setText('Enter team here')
        self.teaminput.returnPressed.connect(self.addTeam)

        # Current highest force text
        self.maxforce = 0000.00
        self.maxforcetxt = QLabel()
        self.maxforcetxt.setFont(QtGui.QFont("Quartz", 62))
        self.maxforcetxt.setText("Maximum Force: %.2f N" % self.maxforce)
        self.maxforcetxt.setStyleSheet(
            "color: rgb(0, 210, 0); background-image: url(maxbackground.png); background-attachment: fixed"
        )
        self.maxforcetxt.setAlignment(QtCore.Qt.AlignCenter)

        # List of teams and scores
        self.teamlist = QListWidget()
        self.teamlist.setStyleSheet("background-color: rgb(85, 90, 100);")
        self.teamlist.setSortingEnabled(True)
        self.teamlist.itemDoubleClicked.connect(self.selectTeam)

        # EGBC Logo
        self.EGBC = QLabel()
        img = QPixmap('EGBC_Logo_Mod2.png')
        self.EGBC.setPixmap(img)

        # Add widgets to grid and format
        self.grid.setColumnStretch(1, 2)
        self.grid.setColumnStretch(2, 2)
        self.grid.setColumnStretch(3, 2)
        self.grid.setColumnStretch(4, 2)
        self.grid.setColumnStretch(5, 1)
        self.grid.setColumnStretch(6, 2)
        self.grid.setRowStretch(1, 6)
        self.grid.setRowStretch(0, 1)

        self.grid.addWidget(self.maxforcetxt, 0, 1, 1, 4)
        self.grid.addWidget(self.EGBC, 0, 5, 1, 2)
        self.grid.addWidget(self.forcelcd, 1, 1, 1, 5)
        self.grid.addWidget(zero, 2, 1)
        self.grid.addWidget(clearmax, 2, 2)
        self.grid.addWidget(export, 2, 3)
        self.grid.addWidget(togglestart, 2, 4)
        self.grid.addWidget(self.teamlist, 1, 6)
        self.grid.addWidget(self.teaminput, 2, 6)

        self.updateforce()
        self.setLayout(self.grid)
        print(self.teaminput.width())
        self.showFullScreen()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            reply = QMessageBox.question(self, 'PyQt5 message',
                                         "Do you want to exit the program?",
                                         QMessageBox.Yes | QMessageBox.No,
                                         QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.close()
            else:
                e.ignore()

    def zero_scale(self):
        self.ser.write(b'x\r\n')
        self.sio.flush()
        trunk = self.sio.readline()
        self.ser.write(b'1\r\n')
        self.sio.flush()
        for line in self.sio.readlines():
            if line == '>\r\n':
                break
        self.ser.write(b'x\r\nx\r\n')
        self.sio.flush()
        self.reset()
        return

    def reset(self):
        self.maxforce = 0.0
        self.force = 0.0
        self.maxforcetxt.setText(str("Maximum Force: %.2f N" % self.maxforce))
        self.forcelcd.display(self.force)

    def toggle(self):
        self.start ^= 1
        if self.start:
            self.chartView.hide()
            #self.grid.removeWidget(self.chartView)
            self.forcelcd.show()
        else:
            self.loadNewGraph = True
            self.forcelcd.hide()

    def addTeam(self):
        self.grid.removeWidget(self.chartView)
        team = self.teaminput.text()
        print(team)
        if team and team != "Enter team here":
            self.teaminput.setText("")
            self.teams[team] = [
                0.00,
            ]

            item = QListWidgetItem_Team()
            item.setText(team + " - " + str(self.teams[team]))
            item.setFont(QtGui.QFont("Times", 32))

            self.teamlist.addItem(item)

        with open(os.path.join(csv_path, team + '.csv'), 'w',
                  newline='') as csvfileout:
            writer = csv.DictWriter(csvfileout, fieldnames=['Sample', 'Force'])
            writer.writeheader()
            csvfileout.close()

    def selectTeam(self):
        self.chartView.hide()
        self.currentteam = self.teamlist.selectedItems()
        if not self.start:
            self.loadNewGraph = True

    def exportTeams(self):
        for team in self.teams:
            sample = 0
            with open(os.path.join(csv_path, team + '.csv'), 'w',
                      newline='') as csvfileout:
                writer = csv.DictWriter(csvfileout,
                                        fieldnames=['Sample', 'Force'])
                writer.writeheader()
                for samples in self.teams[team]:
                    writer.writerow({'Sample': sample, 'Force': samples})
                    sample += 1
            csvfileout.close()

    def get_force(self):
        self.ser.flushOutput()
        self.ser.flushInput()
        output = self.sio.readline()
        print(output)

        if 'Exiting' not in output and len(output) in range(10, 12):
            end = output.rfind(',kg')
            value = output[0:end]
        else:
            value = self.oldforce / 9.81
        return value

    def updateforce(self):
        self.grid.removeWidget(self.chartView)
        if self.start:
            # Generate some random force values for testing
            #self.force = random.randrange(1,5000,1)
            #self.force += 0.01

            self.force = round(float(self.get_force()) * 9.81, 2)
            self.forcelcd.display(self.force)
            self.oldforce = self.force

            # Update team dictionary and CSV file
            if self.currentteam[0].name():
                self.teams[self.currentteam[0].name()].append(self.force)

                start = time.time()
                with open(os.path.join(csv_path,
                                       self.currentteam[0].name() + ".csv"),
                          "a+",
                          newline='') as csvfile:
                    writer = csv.DictWriter(csvfile,
                                            fieldnames=['Sample', 'Force'])
                    csvfile.seek(0)

                    writer.writerow({
                        'Sample': self.currentteam[0].samples,
                        'Force': self.force
                    })
                    self.currentteam[0].samples += 1
                    csvfile.close()
                end = time.time()
                print(end - start)

        # New max force found, update the force label and list
            if self.force > self.maxforce:
                self.maxforce = self.force
                self.maxforcetxt.setText("Maximum Force: %.2f N" % self.force)
                self.currentteam[0].setForce(self.force)

        if not self.start and self.loadNewGraph:
            data = QSplineSeries()
            data.setName(self.currentteam[0].name())

            with open(os.path.join(csv_path,
                                   self.currentteam[0].name() + '.csv'),
                      "r",
                      newline='') as file:
                for line in file:
                    if "Sample" not in line:
                        s = line.split(",")
                        data.append(float(s[0]), float(s[1]))
                file.close()

            maxForceline = QLineSeries()
            maxForceline.setName("Maxiumum Force")
            maxForceline.append(0.0, self.currentteam[0].force())
            maxForceline.append(self.currentteam[0].samples,
                                self.currentteam[0].force())

            force_chart = QChart()
            force_chart.addSeries(data)
            force_chart.addSeries(maxForceline)
            force_chart.setToolTip("{}".format(self.maxforce))
            force_chart.setTitle("Force vs. Time Graph for {}".format(
                self.currentteam[0].name()))
            force_chart.createDefaultAxes()
            force_chart.axisY().setRange(0, self.currentteam[0].force() + 10)
            force_chart.setTheme(2)
            self.chartView = QChartView(force_chart)
            self.chartView.setRenderHint(QPainter.Antialiasing)
            # self.grid.removeWidget(self.chartView)
            self.grid.addWidget(self.chartView, 1, 1, 1, 5)
            print(self.grid.children())
            self.chartView.show()
            self.loadNewGraph = False

        QtCore.QTimer.singleShot(200, lambda: self.updateforce())
Exemple #4
0
class Gps(QWidget):
    def __init__(self, parent):

        super(Gps, self).__init__(parent)

        self.arguments = Arg_Class()

        self.latValue = 5.0
        self.longValue = 3.0
        self.rollValue = 0.0
        self.pitchValue = 0.0
        self.gForceValue = 0.0

        self.latLCD = QLCDNumber(self)
        self.latLCD.display(self.latValue)
        self.latLCD.setFrameShape(QFrame.NoFrame)
        self.latLCD.setSegmentStyle(QLCDNumber.Flat)
        self.latLCD.move(0, 30)
        self.latLCD.resize(70, 50)
        self.latLCD.hide()

        self.latLabel = QLabel(self)
        self.latLabel.setText("lat: ")
        self.latLabel.move(0, 20)
        self.latLabel.hide()

        self.longLCD = QLCDNumber(self)
        self.longLCD.display(self.longValue)
        self.longLCD.setFrameShape(QFrame.NoFrame)
        self.longLCD.setSegmentStyle(QLCDNumber.Flat)
        self.longLCD.move(100, 30)
        self.longLCD.resize(70, 50)
        self.longLCD.hide()

        self.longLabel = QLabel(self)
        self.longLabel.setText("long: ")
        self.longLabel.move(100, 20)
        self.longLabel.hide()

        self.rollLCD = QLCDNumber(self)
        self.rollLCD.display(self.rollValue)
        self.rollLCD.setFrameShape(QFrame.NoFrame)
        self.rollLCD.setSegmentStyle(QLCDNumber.Flat)
        self.rollLCD.move(200, 30)
        self.rollLCD.resize(70, 50)
        self.rollLCD.hide()

        self.rollLabel = QLabel(self)
        self.rollLabel.setText("Roll: ")
        self.rollLabel.move(200, 20)
        self.rollLabel.hide()

        self.pitchLCD = QLCDNumber(self)
        self.pitchLCD.display(self.pitchValue)
        self.pitchLCD.setFrameShape(QFrame.NoFrame)
        self.pitchLCD.setSegmentStyle(QLCDNumber.Flat)
        self.pitchLCD.move(300, 30)
        self.pitchLCD.resize(70, 50)
        self.pitchLCD.hide()

        self.pitchLabel = QLabel(self)
        self.pitchLabel.setText("Pitch: ")
        self.pitchLabel.move(300, 20)
        self.pitchLabel.hide()

        self.gForceLCD = QLCDNumber(self)
        self.gForceLCD.display(self.gForceValue)
        self.gForceLCD.setFrameShape(QFrame.NoFrame)
        self.gForceLCD.setSegmentStyle(QLCDNumber.Flat)
        self.gForceLCD.move(0, 100)
        self.gForceLCD.resize(70, 50)
        self.gForceLCD.hide()

        self.gForceLabel = QLabel(self)
        self.gForceLabel.setText("gForce: ")
        self.gForceLabel.move(0, 100)
        self.gForceLabel.hide()

        self.latLCD.show()
        self.latLabel.show()
        self.longLCD.show()
        self.longLabel.show()
        self.rollLCD.show()
        self.rollLabel.show()
        self.pitchLCD.show()
        self.pitchLabel.show()
        self.gForceLCD.show()
        self.gForceLabel.show()

    @pyqtSlot(float)
    def lat_update(self, value):
        self.latLCD.display(value)
        self.latValue = value
        self.update()

    @pyqtSlot(float)
    def long_update(self, value):
        self.longLCD.display(value)
        self.longValue = value
        self.update()

    @pyqtSlot(float)
    def roll_update(self, value):
        self.rollLCD.display(value)
        self.rollValue = value
        self.update()

    @pyqtSlot(float)
    def pitch_update(self, value):
        self.pitchLCD.display(value)
        self.pitchValue = value
        self.update()

    @pyqtSlot(float)
    def gForce_update(self, value):
        self.gForceLCD.display(value)
        self.gForceValue = value
        self.update()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setPen(Qt.white)
Exemple #5
0
class Error(QWidget):
    def __init__(self, parent):

        super(Error, self).__init__(parent)

        self.arguments = Arg_Class()

        self.rpmCutValue = 0
        self.rpmCutValuePrev = 0
        self.cutFlag = 0

        self.DCLValue = 0
        self.errorCodePL = 0  # post low
        self.errorCodePH = 0  # post high
        self.errorCodeRL = 0  # run low
        self.errorCodeRH = 0  # run high

        self.DCLGauge = QLCDNumber(self)
        self.DCLGauge.display(str(self.DCLValue).zfill(1))
        self.DCLGauge.move(200, 0)
        self.DCLGauge.resize(80, 80)
        self.DCLGauge.setFrameShape(QFrame.NoFrame)
        self.DCLGauge.setSegmentStyle(QLCDNumber.Flat)

        self.DCLlabel = QLabel(self)
        self.DCLlabel.setText("DCL: ")
        self.DCLlabel.move(200, 0)

        self.PLErrorGauge = QLCDNumber(self)
        self.PLErrorGauge.display(str(self.errorCodePL).zfill(1))
        self.PLErrorGauge.move(0, 0)
        self.PLErrorGauge.resize(80, 80)
        self.PLErrorGauge.setFrameShape(QFrame.NoFrame)
        self.PLErrorGauge.setSegmentStyle(QLCDNumber.Flat)

        self.PHErrorGauge = QLCDNumber(self)
        self.PHErrorGauge.display(str(self.errorCodePH).zfill(1))
        self.PHErrorGauge.move(20, 0)
        self.PHErrorGauge.resize(80, 80)
        self.PHErrorGauge.setFrameShape(QFrame.NoFrame)
        self.PHErrorGauge.setSegmentStyle(QLCDNumber.Flat)

        self.RLErrorGauge = QLCDNumber(self)
        self.RLErrorGauge.display(str(self.errorCodeRL).zfill(1))
        self.RLErrorGauge.move(40, 0)
        self.RLErrorGauge.resize(80, 80)
        self.RLErrorGauge.setFrameShape(QFrame.NoFrame)
        self.RLErrorGauge.setSegmentStyle(QLCDNumber.Flat)

        self.RHErrorGauge = QLCDNumber(self)
        self.RHErrorGauge.display(str(self.errorCodeRH).zfill(1))
        self.RHErrorGauge.move(60, 0)
        self.RHErrorGauge.resize(80, 80)
        self.RHErrorGauge.setFrameShape(QFrame.NoFrame)
        self.RHErrorGauge.setSegmentStyle(QLCDNumber.Flat)

        self.errorlabel = QLabel(self)
        self.errorlabel.setText("Error code: ")
        self.errorlabel.move(0, 0)

        self.rpmCutGauge = QLCDNumber(self)
        self.rpmCutGauge.display(str(self.DCLValue).zfill(1))
        self.rpmCutGauge.move(300, 0)
        self.rpmCutGauge.resize(100, 100)
        self.rpmCutGauge.setFrameShape(QFrame.NoFrame)
        self.rpmCutGauge.setSegmentStyle(QLCDNumber.Flat)
        self.rpmCutGauge.hide()

        self.rpmCutLabel = QLabel(self)
        self.rpmCutLabel.setText("RPM Before Cut: ")
        self.rpmCutLabel.move(300, 0)
        self.rpmCutLabel.hide()

    @pyqtSlot(float)
    def DCL_update(self, value):
        self.DCLGauge.display(value)

    @pyqtSlot(float)
    def RPMCut_update(self, value):
        rpmCutValue = value
        if value > 10 and self.cutFlag == 0:
            self.rpmCutGauge.hide()
            #self.rpmCutGauge.display(value)
            self.rpmCutValuePrev = value
        else:
            self.rpmCutGauge.display(self.rpmCutValuePrev)
            self.rpmCutGauge.show()
            self.rpmCutLabel.show()
            self.cutFlag = 1

    @pyqtSlot(int, int, int, int)
    def error_update(self, value1, value2, value3, value4):
        self.PLErrorGauge.display(value1)
        self.PHErrorGauge.display(value2)
        self.RLErrorGauge.display(value3)
        self.RHErrorGauge.display(value4)
Exemple #6
0
class Main(QMainWindow):
    def __init__(self, x, y, btn_size, bombs):
        super().__init__()
        self.start_time = 0
        self.buttons = []
        self.timer = None
        self.colors = {
            '1': '#0000ff',
            '2': '#00ff00',
            '3': '#ff0000',
            '4': '#00007b',
            '5': '#7b0000',
            '6': '#007b7b',
            '7': '#000000',
            '8': '#7b7b7b'
        }
        self.SMILE_DEFAULT = ":)"
        self.SMILE_WIN = ":D"
        self.SMILE_LOSE = "X("
        self.modes = {
            (9, 9, 10): "Новичок",
            (16, 16, 40): "Эксперт",
            (16, 30, 99): "Бывалый",
        }

        self.setWindowTitle("Сапёр))")
        self.init_ui(x, y, btn_size, bombs)

        self.lcd_smile = QPushButton(self)
        self.lcd_smile.setGeometry(self.size().width() // 2 - 25, 26, 50, 50)
        self.lcd_smile.setText(self.SMILE_DEFAULT)
        self.lcd_smile.setFont(
            QtGui.QFont("MS Shell Dlg 2", 14, QtGui.QFont.Bold))
        self.lcd_smile.clicked.connect(self.restart)

        self.lcd_bombs = QLCDNumber(self)
        self.lcd_bombs.display(self.lcd_bombs_num)
        self.lcd_bombs.setGeometry(10, 26, 80, 50)
        self.lcd_bombs.setStyleSheet('color: red; background-color: black')
        self.lcd_bombs.setDigitCount(3)
        self.lcd_bombs.setSegmentStyle(2)

        self.lcd_step = QLCDNumber(self)
        self.lcd_step.display(0)
        self.lcd_step.setGeometry(self.size().width() - 90, 26, 80, 50)
        self.lcd_step.setStyleSheet('color: red; background-color: black')
        self.lcd_step.setDigitCount(3)
        self.lcd_step.setSegmentStyle(2)
        if not OptionsFile().read()[2]:
            self.lcd_step.hide()

        self.menubar = QtWidgets.QMenuBar(self)
        self.setMenuBar(self.menubar)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))

        self.settings = QtWidgets.QMenu(self.menubar)
        self.settings.setTitle('Настройки')

        self.results = QtWidgets.QMenu(self)
        self.results.setTitle("Результаты")

        self.records = QtWidgets.QAction(self)
        self.records.setText("Рекорды")
        self.results.addAction(self.records)

        self.statisctics = QtWidgets.QAction(self)
        self.statisctics.setText("Статистика")
        self.results.addAction(self.statisctics)

        self.difficulty = QtWidgets.QAction(self)
        self.difficulty.setText("Сложность")
        self.settings.addAction(self.difficulty)

        self.options = QtWidgets.QAction(self)
        self.options.setText("Геймплей")
        self.settings.addAction(self.options)

        self.menubar.addAction(self.settings.menuAction())
        self.menubar.addAction(self.results.menuAction())

        self.difficulty.triggered.connect(self.change_difficulty)
        self.records.triggered.connect(self.records_click)
        self.options.triggered.connect(self.gameplay_settings)
        self.statisctics.triggered.connect(self.stats)

    # перерисовка поля
    def init_ui(self, x, y, size, bombs):
        self.setGeometry(300, 300, x * size, y * size + 86)
        self.setFixedSize(x * size, y * size + 86)
        self.rows, self.cols, self.btn_size, self.bombs = y, x, size, bombs
        self.lcd_bombs_num = bombs

        if self.buttons:
            for l in self.buttons:
                for b in l:
                    b.hide()
            self.lcd_bombs.display(bombs)
            self.lcd_step.display(0)
            self.lcd_smile.setGeometry(self.size().width() // 2 - 25, 26, 50,
                                       50)
            self.lcd_step.setGeometry(self.size().width() - 90, 26, 80, 50)
            self.buttons = []
            if self.timer is not None:
                self.timer.stop()

        for i in range(self.rows):
            line = []
            for j in range(self.cols):
                button = QPushButton('', self)
                button.setGeometry(j * self.btn_size, i * self.btn_size + 86,
                                   self.btn_size, self.btn_size)
                button.setFont(
                    QtGui.QFont("MS Shell Dlg 2", 10, QtGui.QFont.Bold))
                button.clicked.connect(partial(self.move, i, j))
                button.show()
                line.append(button)
            self.buttons.append(line)

        self.field = GameField(y, x, bombs)
        self.mode = self.modes[(y, x,
                                bombs)] if (y, x,
                                            bombs) in self.modes else "Особый"

    # смена режима сложности
    def change_difficulty(self):
        clicked, rows, cols, bombs = DifficultyWindow().get_values()
        if clicked:
            self.init_ui(cols, rows, self.btn_size, bombs)

    # нажатие на кнопку поля
    def move(self, row, col):
        if not self.field.generated:
            self.field.generate_field(row, col)
            self.stopwatch()
        elif self.field.get_field()[row][col] == self.field.cell["flag"]:
            return
        else:
            self.field.open(row, col, "o")

        self.update_field()

    # отображение массива GameField на кнопочное поле
    def update_field(self):
        if self.field.det in (0, 1):
            for i in range(self.rows):
                for j in range(self.cols):
                    symbol = self.field.get_field()[i][j]
                    if symbol in [
                            self.field.cell[i]
                            for i in ["flag", "untouched", "question"]
                    ]:
                        self.buttons[i][j].setText(symbol)
                    elif symbol:
                        if self.buttons[i][j].isEnabled():
                            self.buttons[i][j].setEnabled(False)
                            self.buttons[i][j].setStyleSheet(
                                'color: rgb(204, 204, 204)')
                        if symbol.isdigit(
                        ) and not self.buttons[i][j].text().isdigit():
                            self.buttons[i][j].setText(symbol)
                            self.buttons[i][j].setStyleSheet(
                                f'color: {self.colors[symbol]}')

            if self.field.det == 1:
                # Победа
                flags, win = 0, 1
                for r, c in self.field.b_coords:
                    if self.field.get_field()[r][c] == self.field.cell["flag"]:
                        flags += 1
                    self.buttons[r][c].setText(self.field.cell["flag"])
                self.lcd_smile.setText(self.SMILE_WIN)
                self.lcd_bombs.display(0)
                self.show_win_dialog()
                GameStat().update_stats(self.mode, win, flags, flags,
                                        self.lcd_step.intValue())

        elif self.field.det == -1:
            # Поражение
            flags, defused, win = 0, 0, 0
            for i in range(self.rows):
                for j in range(self.cols):
                    if self.field.get_field()[i][j] == self.field.cell["flag"]:
                        flags += 1
                        if (i, j) in self.field.b_coords:
                            defused += 1
                        else:
                            self.buttons[i][j].setStyleSheet('color: red')
                    else:
                        if (i, j) in self.field.b_coords:
                            self.buttons[i][j].setText("X")
            self.lcd_smile.setText(self.SMILE_LOSE)
            GameStat().update_stats(self.mode, win, flags, defused,
                                    self.lcd_step.intValue())

    # Нажатие на смайлик - заново
    def restart(self):
        self.field = GameField(self.rows, self.cols, self.bombs)
        for i in range(self.rows):
            for j in range(self.cols):
                self.buttons[i][j].setText("")
                self.buttons[i][j].setStyleSheet('')
                self.buttons[i][j].setEnabled(True)
        self.lcd_step.display(0)
        self.lcd_bombs_num = self.bombs
        self.lcd_bombs.display(self.lcd_bombs_num)
        self.lcd_smile.setText(self.SMILE_DEFAULT)
        self.timer.stop()

    # Запуск секундомера
    def stopwatch(self):
        self.timer = QtCore.QTimer(self)
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.update_timer)
        self.timer.start()
        self.start_time = time.time()

    # Обновление дисплея времени
    def update_timer(self):
        if self.field.det != 0:
            self.timer.stop()
        self.lcd_step.display(round(time.time() - self.start_time))

    # Обработка нажатия правой кнопкой мыши
    def mousePressEvent(self, event):
        if not self.field.generated:
            return
        if self.lcd_bombs_num == 0:
            return
        if event.button() == QtCore.Qt.RightButton:
            x, y = event.x(), event.y()
            if y < 0:
                return
            row, col = (y - 86) // self.btn_size, x // self.btn_size
            if self.buttons[row][col].text().isdigit():
                return
            self.field.open(row, col, mode="f")
            if self.field.get_field()[row][col] == self.field.cell["flag"]:
                self.lcd_bombs_num -= 1
            elif self.lcd_bombs_num < self.bombs:
                self.lcd_bombs_num += 1
            self.lcd_bombs.display(self.lcd_bombs_num)
            self.update_field()

    # Показать диалоговое окно с победой
    def show_win_dialog(self):
        time = self.lcd_step.intValue()
        wd = WinDialog(self.mode, self.lcd_step.intValue())
        name = wd.show()
        GameStat().put_record(self.mode, name, time)

    # Показать диалоговое окно с таблицей рекордов
    def records_click(self):
        RecordWindow().show()

    # Показать диалоговое окно со статистикой
    def stats(self):
        StatsDialog().show()

    # Показать диалоговое окно с опциями и изменить видимость дисплея времени
    def gameplay_settings(self):
        args = OptionsWindow().show()
        time = args[2]
        if not time:
            self.lcd_step.hide()
        else:
            self.lcd_step.show()
Exemple #7
0
class UiLoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.password = ""
        self.ip = "0.0.0.0:5555"
        self.sockIn = network.connect_InSocket(address='0.0.0.0', port=5556)
        self.sockOut = network.connect_OutSocket(address=self.ip.split(':')[0], port=int(self.ip.split(':')[1]))
        self.time_block, self.chance = read_time()
        self.login_password_admin, self.login_password_manager, self.banned_admin = self.get_admin_manager()

    def disconnect_server(self):
        network.alive = False
        network.close_sock(self.sockIn)
        network.close_sock(self.sockOut)

    def closeEvent(self, QCloseEvent):
        self.disconnect_server()

    def get_admin_manager(self):
        msg = json.dumps({"key": "login"})
        network.sock_send(self.sockOut, msg)
        try:
            self.sockIn.settimeout(2)
            data, address = network.read_sock(self.sockIn)
            self.sockIn.settimeout(None)
        except socket.timeout:
            self.info_label.setText('Сервер отключен! Проверьте соединение')
            self.info_label.resize(self.info_label.sizeHint())
            return [{}, {}, {}]
        msg = json.loads(data)
        return msg

    def bad_try_login(self, login, password, time):
        msg = json.dumps({"key": "bad_try_login",
                          "login": str(login),
                          "password": str(password),
                          "time": str(time)})
        network.sock_send(self.sockOut, msg)
        try:
            self.sockIn.settimeout(2)
            data, address = network.read_sock(self.sockIn)
            self.sockIn.settimeout(None)
        except socket.timeout:
            self.info_label.setText('Сервер отключен! Проверьте соединение')
            self.info_label.resize(self.info_label.sizeHint())
            return [{}, {}, {}]
        msg = json.loads(data)

    def initUI(self):
        self.setGeometry(400, 400, 300, 180)
        self.setWindowTitle('Вход в систему')

        self.lcdNumber = QLCDNumber(self)
        self.lcdNumber.setGeometry(QRect(10, 140, 100, 30))
        self.lcdNumber.setFrameShape(QFrame.Box)

        self.info_label = QLabel(self)
        self.info_label.move(10, 90)
        self.info_label.resize(self.info_label.sizeHint())
        self.info_label.setStyleSheet('color: red')

        self.login = QLabel("Логин:", self)
        self.login.move(10, 10)
        self.login.resize(self.login.sizeHint())

        self.password = QLabel("Пароль:", self)
        self.password.move(10, 40)
        self.password.resize(self.password.sizeHint())

        self.login_line_edit = QLineEdit(self)
        self.login_line_edit.move(65, 10)
        self.login_line_edit.resize(200, 20)


        self.password_line_edit = QLineEdit(self)
        self.password_line_edit.move(65, 40)
        self.password_line_edit.resize(200, 20)
        self.password_line_edit.setEchoMode(QLineEdit.Password)

        self.go_in = QPushButton("Войти", self)
        self.go_in.move(60, 60)
        self.go_in.resize(100, 30)
        self.go_in.pressed.connect(self.log_in_system)

        self.back = QPushButton("Отмена", self)
        self.back.move(150, 60)
        self.back.resize(100, 30)
        self.back.pressed.connect(lambda: self.close())

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showTime)
        self.lcdNumber.hide()

    def showTime(self):
        if self.begin == datetime.strptime(str(self.time_block[-8:]), '%H:%M:%S'):
            self.timer.stop()
            self.lcdNumber.hide()
            self.info_label.setText("Вы опять можете войти в систему")
            self.info_label.setStyleSheet('color: green')
            return
        self.begin = self.begin + timedelta(seconds=1)
        showing_time = datetime.strptime(str(self.time_block[-8:]), '%H:%M:%S') - \
                       datetime.strptime(str(self.begin.strftime('%Y-%m-%d %H:%M:%S').split()[1]),
                                       '%H:%M:%S')

        self.lcdNumber.display(str(showing_time).split()[0])

    def check_time(self, time_block):
        time_ = time_block
        now = str(list(str(datetime.now()).split("."))[0])
        date_block = str(list(str(time_block).split())[0]).split("-")
        date_now = str(list(str(now).split())[0]).split("-")
        time_block = str(list(str(time_block).split())[1]).split(":")
        time_now = str(list(str(now).split())[1]).split(":")
        if (date_block[0] > date_now[0]) or (date_block[0] >= date_now[0] and date_block[1] > date_now[1]) or (date_block[0] >= date_now[0] and date_block[1] >= date_now[1] and date_block[2] >= date_now[2]):
            if (time_block[0] > time_now[0]) or (time_block[0] >= time_now[0] and time_block[1] > time_now[1]) or (time_block[0] >= time_now[0] and time_block[1] >= time_now[1] and time_block[2] > time_now[2]):
                return time_
            else:
                return "0000-00-00 00:00:00"
        else:
            return "0000-00-00 00:00:00"

    def add_one_minute(self, time):
        date_block = str(list(str(time).split())[0]).split("-")
        time_block = str(list(str(time).split())[1]).split(":")
        if int(time_block[1]) + 1 < 60:
            time_block[1] = str(int(time_block[1]) + 1) if len(str(int(time_block[1]) + 1)) == 2 else "0" + str(int(time_block[1]) + 1)
        elif int(time_block[0]) + 1 < 24:
            time_block[0] = str(int(time_block[0]) + 1) if len(str(int(time_block[0]) + 1)) == 2 else "0" + str(int(time_block[0]) + 1)
        elif int(date_block[2]) + 1 < 31:
            date_block[2] = str(int(date_block[2]) + 1) if len(str(int(date_block[2]) + 1)) == 2 else "0" + str(int(date_block[2]) + 1)
        return f"{date_block[0]}-{date_block[1]}-{date_block[2]} {time_block[0]}:{time_block[1]}:{time_block[2]}"

    def log_in_system(self):
        login = self.login_line_edit.text()
        password = self.password_line_edit.text()
        self.time_block = self.check_time(self.time_block)
        if self.time_block[:10] != "0000-00-00":
            self.info_label.setText("Подождите вход в систему пока недоступен")
            self.info_label.resize(self.info_label.sizeHint())
            self.info_label.setStyleSheet('color: red')
            self.lcdNumber.show()
            self.turn_on_timer()
            return
        self.login_password_admin, self.login_password_manager, self.banned_admin = self.get_admin_manager()

        if self.login_password_admin == {} and self.login_password_manager == {} and self.banned_admin == {}:
            self.info_label.setText('Сервер отключен! Проверьте соединение')
            self.info_label.resize(self.info_label.sizeHint())
            self.info_label.setStyleSheet('color: red')
            return
        if login in self.login_password_admin.keys() and str(self.login_password_admin[login]) == str(password) and \
                login not in self.banned_admin.keys():
            self.disconnect_server()
            time_block = str(list(str(datetime.now()).split("."))[0])
            chance = "3"
            write_time(time_block, chance)
            self.Window = UiAdministratorWindow(login)
            self.Window.show()
            UiLoginWindow.close(self)
            msg = QMessageBox()
            msg.setWindowTitle("Информация")
            msg.setText("Добро пожаловать")
            msg.setInformativeText("Вы вошли в систему как администратор")
            result = msg.setStandardButtons(QMessageBox.Ok)
            retval = msg.exec_()
        elif login in self.login_password_manager.keys() and str(self.login_password_manager[login]) == str(password):
            self.disconnect_server()
            time_block = str(list(str(datetime.now()).split("."))[0])
            chance = "3"
            write_time(time_block, chance)
            self.Window = UiManagerWindow(login)
            self.Window.show()
            UiLoginWindow.close(self)
            msg = QMessageBox()
            msg.setWindowTitle("Информация")
            msg.setText("Добро пожаловать")
            msg.setInformativeText("Вы вошли в систему как управляющий гостиницей")
            result = msg.setStandardButtons(QMessageBox.Ok)
            retval = msg.exec_()
        else:
            if login in self.banned_admin.keys() and \
                    login in self.login_password_admin.keys() and self.login_password_admin[login] == password:
                if self.banned_admin[login]:
                    self.time_and_chances()
                    if self.chance != "3":
                        self.info_label.setText(f"Профиль заблокирован\nПричина: {self.banned_admin[login]}\nКоличество оставшихся попыток: {self.chance}")
                        self.bad_try_login(login, password, datetime.now())
                    else:
                        self.info_label.setText("Подождите вход в систему пока недоступен")
                        self.lcdNumber.show()
                        self.turn_on_timer()
                    self.info_label.setStyleSheet('color: red')
                    self.info_label.resize(self.info_label.sizeHint())
                else:
                    self.time_and_chances()
                    if self.chance != "3":
                        self.info_label.setText(f"Профиль заблокирован\nКоличество оставшихся попыток: {self.chance}")
                        self.bad_try_login(login, password, datetime.now())
                    else:
                        self.info_label.setText("Подождите вход в систему пока недоступен")
                        self.lcdNumber.show()
                        self.turn_on_timer()
                    self.info_label.setStyleSheet('color: red')
                    self.info_label.resize(self.info_label.sizeHint())
            else:
                self.time_and_chances()
                if self.chance != "3":
                    self.info_label.setText(f"Профиль или пароль введены неверно\nКоличество оставшихся попыток: {self.chance}")
                    self.bad_try_login(login, password, datetime.now())
                else:
                    self.info_label.setText("Подождите вход в систему пока недоступен")
                    self.lcdNumber.show()
                    self.turn_on_timer()
                self.info_label.setStyleSheet('color: red')
                self.info_label.resize(self.info_label.sizeHint())

    def time_and_chances(self):
        self.chance = str(int(self.chance) - 1)
        if self.chance == "0":
            self.time_block = self.add_one_minute(str(list(str(datetime.now()).split("."))[0]))
            self.chance = "3"
        write_time(self.time_block, self.chance)

    def turn_on_timer(self):
        self.timer.start(1000)
        self.begin = datetime.strptime(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S').split()[1]),
                                       '%H:%M:%S')
Exemple #8
0
class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        self.tmr = QTimer()
        self.tmr.timeout.connect(self.on_timer)
        self.alarm_class = Alarm(0, 0)
        self.status = False
        self.h_m_list = [None, None]
        self.color_frame = (0, 0, 0)
        self.old_pos = None
        self.text = ['00', '00']
        self.initUI()

    def initUI(self):
        # Генерация окна
        self.setWindowTitle('Clock')
        self.setGeometry(100, 100, 260, 160)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setObjectName('MainWidget')
        self.setStyleSheet("#MainWidget {background-color: #272727;}")

        # Кнопка закрытие окна
        self.btn_close = QPushButton(self, clicked=self.close)
        self.btn_close.setIcon(QtGui.QIcon(QtGui.QPixmap('pngs/cross.png')))
        self.btn_close.setFlat(True)
        self.btn_close.resize(17, 17)
        self.btn_close.move(242, 1)
        self.btn_close.show()

        # Кнопка возрата в general
        self.btn_gn = QPushButton(self, clicked=self.general)
        self.btn_gn.setIcon(QtGui.QIcon(QtGui.QPixmap('pngs/back.png')))
        self.btn_gn.setFlat(True)
        self.btn_gn.resize(20, 20)
        self.btn_gn.move(1, 1)
        self.btn_gn.show()

        # Кнопка входа в settings
        self.btn_st = QPushButton(self, clicked=self.settings)
        self.btn_st.setIcon(QtGui.QIcon(QtGui.QPixmap("pngs/gear.png")))
        self.btn_st.setFlat(True)
        self.btn_st.resize(15, 15)
        self.btn_st.move(3, 3)
        self.btn_st.show()

        # Кнопка будильника
        self.alarmB = QPushButton(self, clicked=self.alarm_st)
        self.alarmB.setIcon(QtGui.QIcon(QtGui.QPixmap("pngs/alarmN.png")))
        self.alarmB.setFlat(True)
        self.alarmB.resize(25, 25)
        self.alarmB.move(204, 39)
        self.alarmB.show()

        # Кнопка включения будильника
        self.alVKL = QPushButton('Включить', self, clicked=self.alarm_status)
        self.alVKL.resize(65, 20)
        self.alVKL.setObjectName('a')
        self.alVKL.setStyleSheet(
            "#a {background-color: white; border-radius: 2px;}")
        self.alVKL.move(98, 110)

        # Синхронизация системного времени
        self.sinT = QPushButton('Синхронизация\nсистемного\nвремени',
                                self,
                                clicked=set_server_time)
        self.sinT.resize(90, 50)
        self.sinT.move(120, 28)

        # Дисплей для будильника
        self.lcdA = QLCDNumber(self)
        self.lcdA.resize(150, 75)
        self.lcdA.move(55, 30)
        self.lcdA.setSegmentStyle(QLCDNumber.Flat)
        self.lcdA.setObjectName("LCDA")
        self.lcdA.setStyleSheet(
            "#LCDA {background-image: url(pngs/фон.png); border: 2px solid #4c4c4c;}"
        )
        self.lcdA.display(':'.join(self.text))

        # Слайдер выбора часа
        self.sldH = QSlider(Qt.Vertical, self)
        self.sldH.setMaximum(23)
        self.sldH.move(46, 30)
        self.sldH.resize(9, 75)
        self.sldH.valueChanged.connect(self.slider)

        # Слайдер выбора минут
        self.sldM = QSlider(Qt.Vertical, self)
        self.sldM.setMaximum(59)
        self.sldM.move(206, 30)
        self.sldM.resize(9, 75)
        self.sldM.valueChanged.connect(self.slider2)

        # Дисплей часов
        self.lcd = QLCDNumber(self)
        self.lcd.resize(150, 75)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.move(55, 40)
        self.lcd.display(make_time_for_lcd())
        self.lcd.setObjectName("LCD")
        self.lcd.setStyleSheet(
            "#LCD {background-image: url(pngs/фон.png); border: 2px solid #4c4c4c;}"
        )

        # Комбобокс для стилизации
        self.combo = QComboBox(self)
        self.combo.setStyleSheet('border-radius: 3px, 3px, 2px, 1px;')
        self.combo.resize(75, 20)
        self.combo.addItems([
            "Stylization", "Color", "Olds", "Matrix", "Sofa", "Low Poly",
            "Anime", "Pony", "Савок"
        ])
        self.combo.activated[str].connect(self.onActivated)
        self.combo.move(30, 30)

        # Кнопка отключения будильника
        self.gm = QPushButton('ОТКЛЮЧИТЬ\nБУДИЛЬНИК',
                              self,
                              clicked=self.play_stop)
        self.gm.setObjectName('x')
        self.gm.setStyleSheet("#x {background-color: rgb(0, 255, 0);}")
        self.gm.resize(90, 50)
        self.gm.move(85, 55)

        self.general()

    # Сцена часов
    def general(self):
        try:
            self.btn_st.show()
            self.btn_gn.hide()
            self.combo.hide()
            self.alarmB.show()
            self.lcd.show()
            self.sldH.hide()
            self.sldM.hide()
            self.lcdA.hide()
            self.alVKL.hide()
            self.sinT.hide()
            self.gm.hide()
        except AttributeError:
            pass

    # Сцена настроек
    def settings(self):
        self.btn_gn.show()
        self.btn_st.hide()
        self.combo.show()
        self.alarmB.hide()
        self.lcd.hide()
        self.sldH.hide()
        self.sldM.hide()
        self.lcdA.hide()
        self.alVKL.hide()
        self.sinT.show()
        self.gm.hide()

    def alarm_st(self):
        self.btn_gn.show()
        self.btn_st.hide()
        self.alarmB.hide()
        self.lcd.hide()
        self.sldH.show()
        self.sldM.show()
        self.sldH.setValue(get_local_time()['hours'])
        self.sldM.setValue(get_local_time()['minutes'])
        self.lcdA.show()
        self.alVKL.show()
        self.sinT.hide()

    def good_morning(self):
        self.gm.show()
        self.btn_gn.hide()
        self.btn_st.hide()
        self.alarmB.hide()
        self.lcd.hide()
        self.sldH.hide()
        self.sldM.hide()
        self.lcdA.hide()
        self.alVKL.hide()
        self.sinT.hide()

    def play_stop(self):
        self.alarm_class.stop_sound()
        self.alarm_status()
        self.general()

    # Изменение фона окна
    def palette(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.setStyleSheet("#MainWidget {background-color: %s;}" %
                               color.name())
            self.paintEvent(self, clr=self.hex_to_rgb(color.name()))

    # рисование окна
    def paintEvent(self, event: QtGui.QPaintEvent, clr=(0, 0, 0)):
        painter = QtGui.QPainter(self)
        painter.setPen(
            QtGui.QPen(
                QtGui.QColor(int(fabs(clr[0] - 75)), int(fabs(clr[1] - 75)),
                             int(fabs(clr[2] - 75))), 2))
        painter.drawRect(self.rect())

    # нужна для перемещёния окна
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.old_pos = event.pos()

    # вызывается всякий раз, когда мышь перемещается
    def mouseMoveEvent(self, event):
        if not self.old_pos:
            return
        delta = event.pos() - self.old_pos
        self.move(self.pos() + delta)

    # перевод их hex в rgb
    def hex_to_rgb(self, value):
        value = value.lstrip('#')
        lv = len(value)
        return tuple(
            int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

    def onActivated(self, val):
        backgrounds = {
            'Stylization': '#272727',
            'Olds': 'pngs/olds.png',
            'Matrix': 'pngs/matrix.png',
            'Sofa': 'pngs/диван.jpg',
            'Low Poly': 'pngs/bg.png',
            "Anime": 'pngs/anime.jpg',
            "Pony": 'pngs/pony.jpg',
            "Савок": 'pngs/фоник.png'
        }
        if val == 'Color':
            self.palette()
        elif val == 'Stylization':
            self.setStyleSheet("#MainWidget {background-color: #272727;}")
        elif val != 'Color':
            self.setStyleSheet("#MainWidget {background-image: url(%s);}" %
                               backgrounds[val])
            self.paintEvent(self)

    def slider(self, n):
        self.h_m_list[0] = n
        if len(str(n)) == 1:
            n = '0' + str(n)
        self.text[0] = str(n)
        self.lcdA.display(':'.join(self.text))

    def slider2(self, n):
        self.h_m_list[1] = n
        if len(str(n)) == 1:
            n = '0' + str(n)
        self.text[1] = str(n)
        self.lcdA.display(':'.join(self.text))

    def on_timer(self):
        """ timer handler """
        self.lcd.display(make_time_for_lcd())
        if self.status:
            t = get_local_time()
            if t['hours'] == self.h_m_list[0] and t[
                    'minutes'] == self.h_m_list[1]:
                self.alarm_class.start_sound()
                self.good_morning()

    def alarm_status(self):
        if not self.status:
            self.status = True
            self.alarmB.setIcon(QtGui.QIcon(QtGui.QPixmap("pngs/alarmA.png")))
            self.alVKL.setText('Выключить')
            self.alarm_class.set(self.h_m_list[0], self.h_m_list[1])
        elif self.status:
            self.status = False
            self.alarmB.setIcon(QtGui.QIcon(QtGui.QPixmap("pngs/alarmN.png")))
            self.alVKL.setText('Включить')
        self.alarm_class.tracked = self.status
class Example(QWidget):
    def __init__(self):  # инициализация всех переменных для дальнейшей работы
        super().__init__()
        self.letters_coords = ['А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'К']
        self.left_buttons = []
        self.open_ships = []
        self.check_our = []
        self.all = []
        self.wrong = []
        self.IQ = [(1, 2), (1, 4), (1, 6), (1, 8), (1, 10), (2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (3, 2), (3, 4),
                   (3, 6), (3, 8), (3, 10), (4, 1), (4, 3), (4, 5), (4, 7), (4, 9), (5, 2), (5, 4), (5, 6), (5, 8),
                   (5, 10), (6, 1), (6, 3), (6, 5), (6, 7), (6, 9), (7, 2), (7, 4), (7, 6), (7, 8), (7, 10), (8, 1),
                   (8, 3), (8, 5), (8, 7), (8, 9), (9, 2), (9, 4), (9, 6), (9, 8), (9, 10), (10, 1), (10, 3), (10, 5),
                   (10, 7), (10, 9)]
        self.open_our_ships = []
        self.computer_buttons = []
        self.color_buttons = []
        self.user_color_buttons = []
        self.dict_left = {}
        self.check_ship = []
        self.local = {}
        self.count = 0
        self.us_open = []
        self.local_comp = {}
        self.dict_right = {}
        self.all_btn_coords = []
        self.color_and_open_comp = []
        self.color_computer_buttons = []

        self.con = sqlite3.connect("sea_battle_game.db")

        self.check = False
        self.ships = {1: [], 2: [], 3: [], 4: []}
        self.k = [[False] * 10 for i in range(10)]
        self.copy_k = [[False] * 10 for i in range(10)]

        self.name, ok_pressed = QInputDialog.getText(self, "Введите имя",  # получение никнэйма игрока
                                                     "<p style='color: #2C5545;' style='font: italic bold 30px;'> "
                                                     "Введите своё "
                                                     "имя.")
        while not ok_pressed or self.name == '':
            self.name, ok_pressed = QInputDialog.getText(self, "Введите имя",
                                                         "<p style='color: #2C5545;' style='font: italic bold 30px;'> Введите "
                                                         "своё имя.")

        else:
            self.initUI()

    def initUI(self):  # Дизайн нашего приложения. Поля компьютера и игрока, другие виджеты
        self.setGeometry(400, 150, 1000, 800)
        self.setWindowTitle('Морской бой')
        for i in range(1, 11):  # генерирование полей
            for j in range(1, 11):
                self.btn = QPushButton('', self)
                self.btn.setStyleSheet("background-color: #5096AF")
                self.btn.resize(40, 40)
                self.btn.move(40 * i, 40 * j + 110)
                self.left_buttons.append(self.btn)
                self.dict_left[i, j] = self.btn
                self.local[self.btn] = (i, j)
                self.btn.clicked.connect(self.run)

                self.btn = QPushButton('', self)
                self.btn.setStyleSheet("background-color: #5096AF")
                self.btn.resize(40, 40)
                self.btn.move(40 * i + 510, 40 * j + 110)
                self.computer_buttons.append(self.btn)
                self.dict_right[i, j] = self.btn
                self.local_comp[self.btn] = (i, j)
                self.btn.clicked.connect(self.run)
                self.btn.setEnabled(False)

        self.btn = QPushButton('Выйти из игры', self)
        self.btn.setStyleSheet("background-color: #F0E891")
        self.btn.setFont(QtGui.QFont('Arial', 11, QtGui.QFont.Bold))
        self.btn.move(425, 700)
        self.btn.resize(150, 50)
        self.btn.clicked.connect(self.quit)

        self.timer = QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.displayTime)

        self.u = []
        for i in self.IQ:
            self.u.append(self.dict_left[i])

        self.copy_dict_right = self.dict_right.copy()
        self.copy_dict_left = self.dict_left.copy()
        for i in range(1, 11):
            self.label = QLabel(self)
            self.label.setText(str(i))
            self.label.move(13, 40 * i + 115)
            self.label.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

            self.label_computer = QLabel(self)
            self.label_computer.setText(str(i))
            self.label_computer.move(523, 40 * i + 115)
            self.label_computer.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

            self.label_letters = QLabel(self)
            self.label_letters.setStyleSheet("color: red")
            self.label_letters.setText(self.letters_coords[i - 1])
            self.label_letters.move(40 * i + 10, 122)
            self.label_letters.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

            self.label_computer_letters = QLabel(self)
            self.label_computer_letters.setStyleSheet("color: red")
            self.label_computer_letters.setText(self.letters_coords[i - 1])
            self.label_computer_letters.move(40 * i + 520, 122)
            self.label_computer_letters.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

        self.label = QLabel(self)
        self.label.setText("Ваше поле:")
        self.label.move(150, 70)
        self.label.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

        self.label_time = QLabel(self)
        self.label_time.setStyleSheet("color: #E59E1F;")
        self.label_time.setText("")
        self.label_time.move(315, 15)
        self.label_time.resize(500, 50)
        self.label_time.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

        self.label = QLabel(self)
        self.label.setText("Поле компьютера:")
        self.label.move(630, 70)
        self.label.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

        self.btn_start_game = QPushButton('Начинаем игру!', self)
        self.btn_start_game.setFont(QtGui.QFont('Arial', 10, QtGui.QFont.Bold))
        self.btn_start_game.resize(150, 50)
        self.btn_start_game.move(420, 50)
        self.btn_start_game.clicked.connect(self.start_game)
        self.btn_start_game.hide()

        self.btn_clear = QPushButton('Очистить поле', self)
        self.btn_clear.setFont(QtGui.QFont('Arial', 11, QtGui.QFont.Bold))
        self.btn_clear.resize(150, 50)
        self.btn_clear.move(200, 700)
        self.btn_clear.clicked.connect(self.clear_polygon)
        self.btn_clear.setStyleSheet('background-color: #FCB4D5;')

        self.remaining_cells = QLCDNumber(self)
        self.remaining_cells.resize(150, 50)
        self.remaining_cells.move(500, 600)
        self.remaining_cells.setStyleSheet('background-color: #F0AA00;')

        self.label = QLabel(self)
        self.label.setText("Закрашено клеток(из 20): ")
        self.label.move(180, 610)
        self.label.setFont(QtGui.QFont('Arial', 15, QtGui.QFont.Bold))

        self.btn_generation_ships = QPushButton('Сгенерировать корабли', self)
        self.btn_generation_ships.setFont(QtGui.QFont('Arial', 10, QtGui.QFont.Bold))
        self.btn_generation_ships.resize(230, 50)
        self.btn_generation_ships.move(120, 20)
        self.btn_generation_ships.clicked.connect(self.generate)

        self.btn_miss_motion = QPushButton('Пропустить ход', self)
        self.btn_miss_motion.setStyleSheet('background-color: #FCB4D5;')
        self.btn_miss_motion.setFont(QtGui.QFont('Arial', 11, QtGui.QFont.Bold))
        self.btn_miss_motion.move(200, 700)
        self.btn_miss_motion.resize(170, 50)
        self.btn_miss_motion.clicked.connect(self.miss_move)
        self.btn_miss_motion.hide()

        self.btn_show_sql = QPushButton('Показать все результаты', self)
        self.btn_show_sql.setFont(QtGui.QFont('Arial', 10, QtGui.QFont.Bold))
        self.btn_show_sql.setStyleSheet('background-color: #BEF574;')  # EEDC82
        self.btn_show_sql.resize(230, 50)
        self.btn_show_sql.move(650, 700)
        self.btn_show_sql.clicked.connect(self.show_sql_table)

    def show_sql_table(self): # функция вызова новой формы
        dialog = Show_results()
        dialog.exec()

    def quit(self):  # функция выхода из программы
        sys.exit(0)

    def generate(self):
        self.ships = {1: 4, 2: 3, 3: 2, 4: 1}
        self.dict_left = self.copy_dict_left.copy()
        self.dict_right = self.copy_dict_right.copy()
        self.color_buttons = []
        self.user_color_buttons = []
        self.remaining_cells.display(20)
        for i in self.left_buttons:
            i.setStyleSheet("background-color: #5096AF")
        generation_ships(self, self.dict_left)
        self.remaining_cells.setStyleSheet("background-color: #CEFF1D")
        self.btn_start_game.setStyleSheet("background-color: #CEFF1D")
        self.btn_start_game.show()

    def clear_polygon(self):  # Очистка поля игрока
        for i in self.user_color_buttons:
            self.copy_dict_left[i].setStyleSheet("background-color: #5096AF")
        self.user_color_buttons.clear()
        self.color_buttons.clear()
        self.remaining_cells.display(0)
        self.ships = {1: [], 2: [], 3: [], 4: []}
        self.k = [[False] * 10 for i in range(10)]
        self.copy_k = [[False] * 10 for i in range(10)]
        self.btn_start_game.hide()
        self.remaining_cells.setStyleSheet('background-color: #F0AA00;')

    def displayTime(self):  # Таймер, отображающий время партии
        now = QDateTime.currentDateTime().toString()
        time = now.split()[3].split(':')
        hour = int(time[0])
        minutes = int(time[1])
        seconds = int(time[2])
        self.now_seconds = hour * 3600 + minutes * 60 + seconds
        self.res_time = self.now_seconds - self.all_seconds
        if len(str(self.res_time)) == 1:
            self.label_time.setText('С начала игры прошло: 0:0' + str(self.res_time))
        else:
            if self.res_time <= 59:
                self.label_time.setText('С начала игры прошло: 0:' + str(self.res_time))
            else:
                if len(str(self.res_time % 60)) == 1:
                    self.label_time.setText(f'С начала игры прошло: {self.res_time // 60}:0{self.res_time % 60}')
                else:
                    self.label_time.setText(f'С начала игры прошло: {self.res_time // 60}:{self.res_time % 60}')

    def start_game(self):  # начало игры
        self.count_ship = []
        if len(self.user_color_buttons) == 20:
            count_ships(self, self.k)
            count_ships(self, self.copy_k)
            self.ships[1] = self.count_ship.count(1)
            self.ships[2] = self.count_ship.count(2)
            self.ships[3] = self.count_ship.count(3)
            self.ships[4] = self.count_ship.count(4)
            if self.ships == {1: 4, 2: 3, 3: 2, 4: 1} or not self.fl:
                self.btn_miss_motion.show()
                self.btn_show_sql.move(280, 620)
                self.now = QDateTime.currentDateTime().toString()
                time = self.now.split()[3].split(':')
                hour = int(time[0])
                minutes = int(time[1])
                seconds = int(time[2])
                self.all_seconds = hour * 3600 + minutes * 60 + seconds
                self.timer.start()
                self.label_time.show()
                self.btn_clear.hide()
                self.btn_start_game.hide()
                for i in range(len(self.left_buttons)):
                    self.left_buttons[i].setEnabled(False)
                self.remaining_cells.hide()
                self.label.move(550, 551)
                self.label.resize(400, 200)
                self.computer_ships = {1: 4, 2: 3, 3: 2, 4: 1}
                self.label.setAlignment(QtCore.Qt.AlignCenter)
                self.label.setText(
                    f"У компьютера осталось:\n{self.computer_ships[4]} линкор\n"
                    f"{self.computer_ships[3]} "
                    f"эсминца\n"
                    f"{self.computer_ships[2]} крейсера\n{self.computer_ships[1]} катера")

                generation_ships(self, self.dict_right)
                self.btn_generation_ships.hide()

                for i in self.computer_buttons:
                    i.setEnabled(True)
            else:
                QMessageBox.critical(self, "Error...", f"<p style='color: red;' style='font: italic bold 16px;'> "
                                                       f"Неправильное количество "
                                                       f"нужных кораблей! Должно быть: "
                                                       f"1 - 4-клеточный, 2 - 3-клеточных, 3 - 2-клеточных, "
                                                       f"4 - 1-клеточных",
                                     QMessageBox.Ok)
        else:
            QMessageBox.critical(self, "Error...", f"<p style='color: red;' style='font: italic bold 16px;'> "
                                                   f"Невозможно "
                                                   f"начать игру! Количество "
                                                   f"закрашенных клеток не "
                                                   f"соответствует нужному — "
                                                   f"20. У Вас "
                                                   f"закрашено: {len(self.color_buttons)}",
                                 QMessageBox.Ok)

    def miss_move(self):  # функция пропустить ход
        comp_motion(self, True)

    def run(self):  # основная функция программы, отвечающая за выстрелы игрока и компьютера
        self.fl = True
        if self.sender() in self.left_buttons:
            n = self.left_buttons.index(self.sender())
            self.coord = self.local[self.sender()]
            self.flag = False
            if n in self.color_buttons:
                self.flag = True
                self.color_buttons.remove(n)
                self.user_color_buttons.remove(self.local[self.left_buttons[n]])
                self.left_buttons[n].setStyleSheet("background-color: #5096AF")
                self.k[self.coord[0] - 1][self.coord[1] - 1] = False
                self.copy_k[self.coord[1] - 1][self.coord[0] - 1] = False
                self.remaining_cells.display(len(self.color_buttons))
                if self.remaining_cells.value() == 20:
                    self.remaining_cells.setStyleSheet("background-color: #CEFF1D")
                    self.btn_start_game.setStyleSheet("background-color: #CEFF1D")
                    self.btn_start_game.show()
                else:
                    self.remaining_cells.setStyleSheet('background-color: #F0AA00;')
                    self.btn_start_game.hide()
            if len(self.color_buttons) == 0 and not self.flag:
                self.color_buttons.append(n)
                self.user_color_buttons.append(self.local[self.left_buttons[n]])
                self.k[self.coord[0] - 1][self.coord[1] - 1] = True
                self.copy_k[self.coord[1] - 1][self.coord[0] - 1] = True
                self.left_buttons[n].setStyleSheet("background-color: black")
                self.remaining_cells.display(len(self.color_buttons))
            elif len(self.color_buttons) >= 1 and not self.flag:
                self.color_buttons.sort()
                self.check = False
                if n % 10 != 0 and n % 10 != 9:
                    for i in self.color_buttons:
                        if n == i + 11 or n == i - 11 or n == i - 9 or n == i + 9:
                            self.check = True
                            break
                elif n % 10 == 0:
                    for i in self.color_buttons:
                        if n == i - 11 or n == i + 9:
                            self.check = True
                            break
                elif n % 10 == 9:
                    for i in self.color_buttons:
                        if n == i + 11 or n == i - 9:
                            self.check = True
                            break

                if not self.check:
                    if n not in self.color_buttons:
                        self.ch = False
                        self.k[self.coord[0] - 1][self.coord[1] - 1] = True
                        self.copy_k[self.coord[1] - 1][self.coord[0] - 1] = True
                        check_ships(self, self.k)
                        check_ships(self, self.copy_k)
                        if not self.ch:
                            self.all_btn_coords.append(self.coord)
                            self.color_buttons.append(n)
                            self.user_color_buttons.append(self.local[self.left_buttons[n]])
                            self.left_buttons[n].setStyleSheet("background-color: black")
                            self.remaining_cells.display(len(self.color_buttons))
                            if self.remaining_cells.value() == 20:
                                self.remaining_cells.setStyleSheet("background-color: #CEFF1D")
                                self.btn_start_game.setStyleSheet("background-color: #CEFF1D")
                                self.btn_start_game.show()
                            else:
                                self.remaining_cells.setStyleSheet('background-color: #F0AA00;')
                                self.btn_start_game.hide()
                            self.ch = False

        elif self.sender() in self.computer_buttons:
            buttonReply = ''
            cell = self.local_comp[self.sender()]
            if cell in self.color_computer_buttons:
                if cell in self.check_ship:
                    a = self.check_ship.index(cell)
                    del self.check_ship[a]
                self.sender().setStyleSheet('background-color: red')
                self.sender().setEnabled(False)
                self.open_ships.append(cell)
                self.color_and_open_comp.append(cell)
                if (cell[0] - 1, cell[1]) in self.color_computer_buttons and (
                        cell[0] - 1, cell[1]) not in self.open_ships:
                    self.check_ship.append((cell[0] - 1, cell[1]))
                if (cell[0] + 1, cell[1]) in self.color_computer_buttons and (
                        cell[0] + 1, cell[1]) not in self.open_ships:
                    self.check_ship.append((cell[0] + 1, cell[1]))
                if (cell[0], cell[1] - 1) in self.color_computer_buttons and (
                        cell[0], cell[1] - 1) not in self.open_ships:
                    self.check_ship.append((cell[0], cell[1] - 1))
                if (cell[0], cell[1] + 1) in self.color_computer_buttons and (
                        cell[0], cell[1] + 1) not in self.open_ships:
                    self.check_ship.append((cell[0], cell[1] + 1))
                if len(self.check_ship) == 0:
                    self.count = 0
                    for i in self.open_ships:
                        self.count += 1
                        check_neighbour(self, i, self.copy_dict_right, 'paint')
                    self.computer_ships[self.count] -= 1
                    if self.computer_ships[4] == 1:
                        link = f'{self.computer_ships[4]} линкор'
                    else:
                        link = f'{self.computer_ships[4]} линкоров ✅'

                    if self.computer_ships[3] == 2:
                        esm = f'{self.computer_ships[3]} эсминца'
                    elif self.computer_ships[3] == 1:
                        esm = f'{self.computer_ships[3]} эсминец'
                    else:
                        esm = f'{self.computer_ships[3]} эсминцев ✅'

                    if self.computer_ships[2] == 3 or self.computer_ships[2] == 2:
                        kreis = f'{self.computer_ships[2]} крейсера'
                    elif self.computer_ships[2] == 1:
                        kreis = f'{self.computer_ships[2]} крейсер'
                    else:
                        kreis = f'{self.computer_ships[2]} крейсеров ✅'

                    if self.computer_ships[1] == 4 or self.computer_ships[1] == 3 or self.computer_ships[1] == 2:
                        kater = f'{self.computer_ships[1]} катера'
                    elif self.computer_ships[1] == 1:
                        kater = f'{self.computer_ships[1]} катер'
                    else:
                        kater = f'{self.computer_ships[1]} катеров ✅'
                    self.label.setText(
                        f"У компьютера осталось:\n{link}\n"
                        f"{esm}"
                        f"\n"
                        f"{kreis}\n{kater}")
                    self.open_ships = []
                if len(self.color_and_open_comp) == 20:
                    self.timer.stop()
                    time = self.label_time.text().split()[4]
                    buttonReply = QMessageBox.question(self, 'Победа!!!', "<p style='color: green;' style='font: "
                                                                          "italic bold 25px;'> Вы "
                                                                          "выиграли!!!😎\nХотите начать игру заново?",
                                                       QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                    if buttonReply == QMessageBox.Yes:
                        cur = self.con.cursor()
                        cur.execute(f"INSERT INTO all_games(nickname,result,time_game,world_time) VALUES('{self.name}',"
                                    f"'Победа игрока', '{time}', '{self.now}');")
                        self.con.commit()
                        clear_for_new_game(self)

                    if buttonReply == QMessageBox.No:
                        cur = self.con.cursor()
                        cur.execute(f"INSERT INTO all_games(nickname,result,time_game,world_time) VALUES('{self.name}',"
                                    f"'Победа игрока', '{time}', '{self.now}');")
                        self.con.commit()
                        clear_for_new_game(self)
                        self.con.close()
                        sys.exit(0)
            else:
                check = True
                self.sender().setStyleSheet('background-color: white')
                self.sender().setEnabled(False)
                comp_motion(self, check)