Exemple #1
0
 def extract_xml_from_zip(self):
     """
     извлекает выписки из ЕГРН на земельные участки из архива zip, сохраняя исходный архив, удаляя промежуточные
     архивы и файлы ЭЦП
     """
     self.textBrowser.append("Идёт извлечение выписок xml из архивов...")
     directory = get_settings('folder_in_xml')
     files = os.listdir(directory)
     zipfiles = list(filter(lambda x: x.endswith('.zip'), files))
     extract_all_zipfiles(zipfiles, directory)
     new_files = os.listdir(directory)
     new_zipfiles = list(filter(lambda x: x.endswith('.zip'), new_files))
     for i in new_zipfiles:
         if i in zipfiles:
             new_zipfiles.remove(i)
     extract_all_zipfiles(new_zipfiles, directory)
     result_files = os.listdir(directory)
     sig_files = list(filter(lambda x: x.endswith('.sig'), result_files))
     for sf in sig_files:
         os.remove(directory + '//' + sf)
     for zf in new_zipfiles:
         if zf not in zipfiles:
             os.remove(directory + '//' + zf)
     self.textBrowser.append("Извлечение выписок xml из архивов завершено.")
     self.textBrowser.append(
         "------------------------------------------------------------------------------------"
         "---------------------------")
Exemple #2
0
 def rename_xml(self):
     """
     переименовывает выписки из ЕГРН на земельные участки в формате: кадастровый номер---дата получения выписки
     """
     self.textBrowser.append("Идёт переименование выписок xml...")
     directory = get_settings('folder_in_xml')
     result_files = os.listdir(directory)
     pb = 0
     self.progressBar.setValue(0)
     count_successful_files = 0
     count_unsupported_files = 0
     xmlfiles = list(filter(lambda x: x.endswith('.xml'), result_files))
     for file_name in xmlfiles:
         xml_file_path = directory + "\\" + file_name
         real_estate_object = None
         if AbstractRealEstateObject.create_a_real_estate_object(
                 xml_file_path):
             real_estate_object = AbstractRealEstateObject.create_a_real_estate_object(
                 xml_file_path)
         if real_estate_object is not None:
             parcel_kn = real_estate_object.parent_cad_number
             extract_date = real_estate_object.extract_date
             pkn = re.sub(':', '-', parcel_kn)
             ed = re.sub('\.', '-', extract_date)
             new_name = pkn + '---' + ed + '.xml'
             new_path = directory + '//' + new_name
             if file_name != new_name:
                 if not os.path.exists(new_path):
                     os.rename(directory + '//' + file_name, new_path)
                 else:
                     for num in range(2, 100):
                         new_path_double = directory + '//' + pkn + '---' + ed + ' (' + str(
                             num) + ')' + '.xml'
                         if not os.path.exists(new_path_double):
                             os.rename(directory + '//' + file_name,
                                       new_path_double)
                             break
                 count_successful_files += 1
         else:
             count_unsupported_files += 1
         pb += 1
         self.progressBar.setValue((pb / len(xmlfiles)) * 100)
     files_do_not_require_renaming = len(
         xmlfiles) - count_successful_files - count_unsupported_files
     self.textBrowser.append("Готово!")
     if files_do_not_require_renaming > 0:
         self.textBrowser.append('Для ' +
                                 str(files_do_not_require_renaming) +
                                 ' xml-файлов переименование '
                                 'не требуется')
     self.textBrowser.append("Переименовано " +
                             str(count_successful_files) + ' xml-файлов')
     if count_unsupported_files > 0:
         self.textBrowser.append("Не удалось прочитать " +
                                 str(count_unsupported_files) +
                                 ' xml-файлов')
     self.textBrowser.append(
         "------------------------------------------------------------------------------------"
         "---------------------------")
Exemple #3
0
def video_resize(size, ship=[[[0]]], draw=True):
    vo.set_screen_size(size[0], size[1])  # refreshes window size
    # refreshes location of visible assets and the game itself
    vo.refresh_loc_coords(
        vo.get_window_size(size[0], size[1])[2],
        vo.get_window_size(size[0], size[1])[3], lg.get_zustand())
    if draw:
        # displays the menu on the game window
        vo.draw_screen(lg.get_zustand(), lg.get_background(),
                       lg.get_language(), ship, resource_path,
                       lg.get_task_number(), lg.get_settings())
Exemple #4
0
 def start_conv(self):
     """
     запускает конвертирование набора выписок на земельные участки из формата xml в выбранные форматы файлов
     """
     directory = get_settings('folder_in_xml')
     starting_xmlfiles = list(
         filter(lambda x: x.endswith('.xml'), os.listdir(directory)))
     if self.radioButton_zip.isChecked(
     ) is False and self.radioButton_xml.isChecked() is False:
         QMessageBox.warning(
             self, 'Ошибка',
             "Необходимо выбрать формат обрабатываемых файлов (xml или zip)"
         )
         return False
     elif self.radioButton_xml.isChecked() is True and len(
             starting_xmlfiles) == 0:
         QMessageBox.warning(
             self, 'Ошибка',
             "В указанной папке нет выписок из ЕГРН в формате XML")
         return False
     elif self.radioButton_zip.isChecked():
         self.extract_xml_from_zip()
     if self.checkBoxRename.isChecked():
         self.rename_xml()
     if self.checkBoxExcel.isChecked() or self.checkBoxShape.isChecked():
         xmlfiles = list(
             filter(lambda x: x.endswith('.xml'), os.listdir(directory)))
         self.textBrowser.append(
             "Идёт получение данных из выписок XML и запись в выбранные форматы файлов..."
         )
         start_time = time.time()
         now = datetime.datetime.now()
         directory_out = get_settings('folder_out_xml')
         if self.checkBoxExcel.isChecked():
             wb = Workbook()
             ws = wb.active
             fill_1 = PatternFill(fill_type='solid',
                                  start_color='c1c1c1',
                                  end_color='c2c2c2')
             font_1 = Font(name='Calibri',
                           size=11,
                           bold=True,
                           italic=False,
                           vertAlign=None,
                           underline='none',
                           strike=False,
                           color='FF000000')
             #  описание стиля границы ячейки в таблице MS Excel
             border_1 = Border(left=Side(border_style='thin',
                                         color='FF000000'),
                               right=Side(border_style='thin',
                                          color='FF000000'),
                               top=Side(border_style='thin',
                                        color='FF000000'),
                               bottom=Side(border_style='thin',
                                           color='FF000000'),
                               diagonal=Side(border_style='thin',
                                             color='FF000000'),
                               diagonal_direction=0,
                               outline=Side(border_style='thin',
                                            color='FF000000'),
                               vertical=Side(border_style='thin',
                                             color='FF000000'),
                               horizontal=Side(border_style='thin',
                                               color='FF000000'))
             ws['A1'] = 'Кадастровый номер'
             ws['B1'] = 'Кадастровый номер единого землепользования'
             ws['C1'] = 'Площадь, м2'
             ws['D1'] = 'Адрес'
             ws['E1'] = 'Статус'
             ws['F1'] = 'Категория земель'
             ws['G1'] = 'Вид разрешенного использования (по документу)'
             ws['H1'] = 'Правообладатель'
             ws['I1'] = 'Вид права, номер и дата регистрации'
             ws['J1'] = 'Ограничения прав и обременения'
             ws['K1'] = 'Вид ограничения (обременения), номер и дата регистрации, срок действия'
             ws['L1'] = 'Особые отметки'
             ws['M1'] = 'Дата постановки на кад. учёт'
             ws['N1'] = 'Дата получения сведений'
             ws['O1'] = 'КН расположенных в пределах ЗУ или ОКС объектов недвижимости'
             ws['P1'] = 'Кадастровая стоимость, руб.'
             ws['Q1'] = 'Вид объекта недвижимости'
             for cell_obj in ws['A1':'Q1']:
                 for cell in cell_obj:
                     cell.fill = fill_1
                     cell.font = font_1
             ws.column_dimensions['A'].width = 18
             ws.column_dimensions['B'].width = 19
             ws.column_dimensions['C'].width = 10
             ws.column_dimensions['D'].width = 35
             ws.column_dimensions['E'].width = 16
             ws.column_dimensions['F'].width = 23
             ws.column_dimensions['G'].width = 37
             ws.column_dimensions['H'].width = 37
             ws.column_dimensions['I'].width = 45
             ws.column_dimensions['J'].width = 45
             ws.column_dimensions['K'].width = 45
             ws.column_dimensions['L'].width = 45
             ws.column_dimensions['M'].width = 14
             ws.column_dimensions['N'].width = 14
             ws.column_dimensions['O'].width = 18
             ws.column_dimensions['P'].width = 14
             ws.column_dimensions['Q'].width = 20
             row_numb = 1
         if self.checkBoxShape.isChecked():
             shp_wr = shapefile.Writer(directory_out + "\\" +
                                       'real_estate_objects_EGRN_' +
                                       now.strftime("%d_%m_%Y  %H-%M"),
                                       shapeType=shapefile.POLYGON,
                                       encoding="cp1251")
             shp_wr.field('CadNumber', 'C', size=20)
             shp_wr.field('SnglUseCN', 'C', size=20)
             shp_wr.field('NumOfCont', 'C', size=20)
             shp_wr.field('Area', 'N', 20, 2)
             shp_wr.field('Note', 'C', size=255)
             shp_wr.field('Parcel_St', 'C', size=255)
             shp_wr.field('Category', 'C', size=255)
             shp_wr.field('ByDoc', 'C', size=255)
             shp_wr.field('Owner', 'C', size=255)
             shp_wr.field('OwnRightN', 'C', size=255)
             shp_wr.field('Encumbr', 'C', size=255)
             shp_wr.field('EncRightN', 'C', size=255)
             shp_wr.field('Special', 'C', size=255)
             shp_wr.field('DatOfCreat', 'D')
             shp_wr.field('DateOfGet', 'D')
             shp_wr.field('EstateObjs', 'C', size=255)
             shp_wr.field('CadastCost', 'C', size=50)
             shp_wr.field('Type', 'C', size=60)
         xml_errors = []
         pb = 0
         count_successful_files = 0
         self.progressBar.setValue(0)
         for xml_file in xmlfiles:
             xml_file_path = directory + "\\" + xml_file
             real_estate_object = None
             if AbstractRealEstateObject.create_a_real_estate_object(
                     xml_file_path):
                 real_estate_object = AbstractRealEstateObject.create_a_real_estate_object(
                     xml_file_path)
             if real_estate_object is not None:
                 parent_cad_number = real_estate_object.parent_cad_number
                 entry_parcels = real_estate_object.entry_parcels
                 area = real_estate_object.area
                 #  с помощью регулярных выражений удаляем из строк символы табуляции, новой строки
                 #  и возврата каретки
                 pattern = "^\s+|\n|\r|\s+$"
                 address = re.sub(pattern, '', real_estate_object.address)
                 status = re.sub(pattern, '', real_estate_object.status)
                 category = real_estate_object.category
                 permitted_use_by_doc = re.sub(
                     pattern, '', real_estate_object.permitted_use_by_doc)
                 owner = re.sub(pattern, '', real_estate_object.owner)
                 own_name_reg_numb_date = real_estate_object.own_name_reg_numb_date
                 encumbrances = re.sub(pattern, '',
                                       real_estate_object.encumbrances)
                 encumbrances_name_reg_numb_date_duration = real_estate_object.encumbrances_name_reg_numb_date_duration
                 special_notes = re.sub(pattern, '',
                                        real_estate_object.special_notes)
                 date_of_cadastral_reg = real_estate_object.date_of_cadastral_reg
                 extract_date = real_estate_object.extract_date
                 estate_objects = real_estate_object.estate_objects
                 cadastral_cost = real_estate_object.cadastral_cost
                 real_estate_object_type = real_estate_object.type
                 if self.checkBoxReplace.isChecked():
                     address = to_shorten_a_long_name(address)
                     permitted_use_by_doc = to_shorten_a_long_name(
                         permitted_use_by_doc)
                     owner = to_shorten_a_long_name(owner)
                     encumbrances = to_shorten_a_long_name(encumbrances)
                     special_notes = to_shorten_a_long_name(special_notes)
                 if self.checkBoxShape.isChecked():
                     geometry = real_estate_object.geometry
                     if geometry != {}:
                         for key, value in geometry.items():
                             shp_wr.poly(value)
                             inverted_date_of_cadastral_reg = date_of_cadastral_reg.split(
                                 ".")[::-1]
                             if inverted_date_of_cadastral_reg != ['']:
                                 year1, month1, day1 = inverted_date_of_cadastral_reg
                             else:
                                 year1, month1, day1 = 1, 1, 1
                             inverted_extract_date = extract_date.split(
                                 ".")[::-1]
                             if inverted_extract_date != ['']:
                                 year2, month2, day2 = inverted_extract_date
                             else:
                                 year2, month2, day2 = 1, 1, 1
                             if re.search(r'\(', key):
                                 shp_cad_number = key[:key.index('(')]
                                 num_of_cont = key[key.index('('):]
                             elif not re.search(":", key):
                                 shp_cad_number = parent_cad_number
                                 num_of_cont = key
                             else:
                                 shp_cad_number = key
                                 num_of_cont = ''
                             if parent_cad_number == shp_cad_number:
                                 shp_parent_cad_number = ''
                             else:
                                 shp_parent_cad_number = parent_cad_number
                             shp_wr.record(
                                 shp_cad_number,
                                 shp_parent_cad_number, num_of_cont,
                                 float(area), address, status, category,
                                 permitted_use_by_doc, owner,
                                 own_name_reg_numb_date, encumbrances,
                                 encumbrances_name_reg_numb_date_duration,
                                 special_notes,
                                 datetime.date(int(year1), int(month1),
                                               int(day1)),
                                 datetime.date(int(year2), int(month2),
                                               int(day2)), estate_objects,
                                 cadastral_cost, real_estate_object_type)
                     else:
                         self.textBrowser.append(
                             f'Выписка {xml_file} не содержит координат границ'
                         )
                 if self.checkBoxExcel.isChecked():
                     if not entry_parcels:
                         row_numb += 1
                         ws['A' + str(row_numb)] = parent_cad_number
                         ws['B' + str(row_numb)] = '-'
                         ws['C' + str(row_numb)] = area
                         ws['D' + str(row_numb)] = address
                         ws['E' + str(row_numb)] = status
                         ws['F' + str(row_numb)] = category
                         ws['G' + str(row_numb)] = permitted_use_by_doc
                         ws['H' + str(row_numb)] = owner
                         ws['I' + str(row_numb)] = own_name_reg_numb_date
                         ws['J' + str(row_numb)] = encumbrances
                         ws['K' + str(
                             row_numb
                         )] = encumbrances_name_reg_numb_date_duration
                         ws['L' + str(row_numb)] = special_notes
                         ws['M' + str(row_numb)] = date_of_cadastral_reg
                         ws['N' + str(row_numb)] = extract_date
                         ws['O' + str(row_numb)] = estate_objects
                         ws['P' + str(row_numb)] = cadastral_cost
                         ws['Q' + str(row_numb)] = real_estate_object_type
                     else:
                         for parcel_cad_number in entry_parcels:
                             row_numb += 1
                             ws['A' + str(row_numb)] = parcel_cad_number
                             ws['B' + str(row_numb)] = parent_cad_number
                             ws['C' + str(row_numb)] = area
                             ws['D' + str(row_numb)] = address
                             ws['E' + str(row_numb)] = status
                             ws['F' + str(row_numb)] = category
                             ws['G' + str(row_numb)] = permitted_use_by_doc
                             ws['H' + str(row_numb)] = owner
                             ws['I' +
                                str(row_numb)] = own_name_reg_numb_date
                             ws['J' + str(row_numb)] = encumbrances
                             ws['K' + str(
                                 row_numb
                             )] = encumbrances_name_reg_numb_date_duration
                             ws['L' + str(row_numb)] = special_notes
                             ws['M' + str(row_numb)] = date_of_cadastral_reg
                             ws['N' + str(row_numb)] = extract_date
                             ws['O' + str(row_numb)] = estate_objects
                             ws['P' + str(row_numb)] = cadastral_cost
                             ws['Q' +
                                str(row_numb)] = real_estate_object_type
                 if self.checkBoxShape.isChecked():
                     pass
                 count_successful_files += 1
             else:
                 xml_errors.append(xml_file_path)
             pb += 1
             self.progressBar.setValue((pb / len(xmlfiles)) * 100)
         if self.checkBoxExcel.isChecked():
             for cell_obj in ws['A1':'Q' + str(row_numb)]:
                 for cell in cell_obj:
                     cell.border = border_1
                     cell.alignment = Alignment(
                         wrapText=True
                     )  # задаёт выравнивание "перенос по словам"
             wb.save(directory_out + "\\" +
                     now.strftime("%d_%m_%Y  %H-%M") +
                     " real_estate_objects_EGRN.xlsx")
         if self.checkBoxShape.isChecked():
             shp_wr.close()
         self.textBrowser.append(
             "Получение данных из выписок XML завершено!" + chr(13) +
             "Результат сохранён в папке " + directory_out)
         sec = round(float("%s" % (time.time() - start_time)))
         if sec == 0:
             sec = 1
         self.textBrowser.append("Успешно обработано " +
                                 str(count_successful_files) +
                                 " файлов за " + str(sec) + " сек.")
         if len(xml_errors) > 0:
             self.textBrowser.append("Не обработано " +
                                     str(len(xml_errors)) + " файлов:")
             for err_file in xml_errors:
                 self.textBrowser.append(err_file)
         self.textBrowser.append(
             "----------------------------------------------------------------------------------"
             "-----------------------------")
Exemple #5
0
def game_loop(settings, running, win, again):
    """
    game loop, allowing for game to be played

    :param settings: bool; settings loop will be running
    :param running: bool; game is running
    :param win: int; player that is currently winning
    :param again: bool; game will be starting again after this game
    :return: bool, bool, int, bool; bools for loop management
    """
    def set_settings():
        """
        activates settings loop allowing for visual changes to be made by the user
        """
        # updates bools to start settings loop
        nonlocal settings
        nonlocal running
        running = False
        settings = True
        lg.set_aufgabe("main")  # opens main page in menu
        lg.set_zustand("settings")  # sets current loop to current loop

    while running:  # game loop allowing the game to be played

        for event in pg.event.get(
        ):  # goes through every input occuring while game window is in focus

            if event.type == MOUSEBUTTONDOWN:  # button on mouse was pressed
                # gets the size of one virtual field
                field_size = vo.get_window_size(vo.get_screen_size()[0],
                                                vo.get_screen_size()[1])[2]
                button = lg.do_button_mouse_ingame(event.pos[0], event.pos[1],
                                                   field_size,
                                                   vo.get_buttons()[1], gaf(),
                                                   resource_path, save_game)
                try:
                    # gets coordiantes of the clicked field, whether a field was hit, and the hit field
                    xcoord, ycoord, hit_check, xcoord_2, ycoord_2 = button
                except ValueError:
                    # instead puts control values for hit fields if none were hit
                    xcoord, ycoord, hit_check, xcoord_2, ycoord_2 = (-1, -1,
                                                                     False, -1,
                                                                     -1)
                    if button == "end":
                        settings = running = False
                        win = 1
                    elif button == "settings":
                        set_settings()
                except TypeError:
                    # instead puts control values for hit fields if none were hit
                    xcoord, ycoord, hit_check, xcoord_2, ycoord_2 = (-1, -1,
                                                                     False, -1,
                                                                     -1)
                if hit_check:
                    # executes hit if a field was hit
                    do_hit_player_input(xcoord_2, ycoord_2)
                if -1 not in pl.get_last_click():  # checks for control value
                    vo.unclick(pl.get_last_click()
                               )  # unclicks previously clicked field
                pl.set_angeklicktes_feld(xcoord,
                                         ycoord)  # refreshes clicked field
                # displays the game on the game window
                vo.draw_screen(lg.get_zustand(), lg.get_background(),
                               lg.get_language(), sh.get_ship(), resource_path,
                               lg.get_task_number(), lg.get_settings())
                if running:
                    running, win = sh.check_ship_status(
                    )  # checks whether all ships of one player have been destroyed

            elif event.type == KEYDOWN:  # button on keyboard was pressed
                if event.key == K_ESCAPE:  # escape button was pressed
                    set_settings()
                else:
                    try:
                        # gets coordinates of the selected field
                        xcoord, ycoord = lg.do_button_ingame_keyboard(
                            event.key, resource_path)
                    except TypeError:
                        # sets coordinates to -1 when no field is selected yet
                        xcoord, ycoord = -1, -1

                    if xcoord != -1 and ycoord != -1:
                        # clicks a new field
                        hit_small_field(1, xcoord, ycoord, resource_path,
                                        lg.get_sound_volume(),
                                        lg.get_language())
                        do_hit_player_input(
                            xcoord, ycoord)  # hits a field from a player input

                # displays the game on the game window
                vo.draw_screen(lg.get_zustand(), lg.get_background(),
                               lg.get_language(), sh.get_ship(), resource_path,
                               lg.get_task_number(), lg.get_settings())
                running, win = sh.check_ship_status(
                )  # checks whether all ships of one player have been destroyed

            elif event.type == VIDEORESIZE:  # checks whether the size of the window got adjusted
                video_resize(event.size, sh.get_ship())

            elif event.type == pg.QUIT:  # checks whether the wndow has been closed
                # ends the program
                settings = running = again = False
                win = 2  # sets win to 2, what is used to mark that no player has won the game

    return settings, running, win, again
Exemple #6
0
def setting(settings, running, win, again):
    """
    settings loop in game, allowing for settings to change that only effect the game visually

    :param settings: bool; settings loop is running
    :param running: bool; game loop will be running
    :param win: int; player that is currently winning
    :param again: bool; game will be starting again after this game
    :return: bool, bool, int, bool; updated bools for loop management
    """
    num = 0
    other_num = 0
    while settings and lg.get_zustand(
    ) != "end":  # settings loop enabling setting changes in game

        for event in pg.event.get(
        ):  # goes through every input occuring while game window is in focus

            if event.type == MOUSEBUTTONDOWN:  # mouse button was clicked
                # gets size of one virtual field
                field_size, orientation = vo.get_window_size(
                    vo.get_screen_size()[0],
                    vo.get_screen_size()[1])[2:]
                # executes feature of pressed button if there is one
                button = lg.do_button_start(event.pos[0], event.pos[1],
                                            field_size,
                                            vo.get_buttons()[0], resource_path)
                if button == "end":
                    settings = running = False
                    win = 1
                if lg.get_aufgabe(
                ) == "volume":  # checks whether a slider is on the screen
                    for slider in vo.get_slides():  # goes through every slider
                        try:
                            if slider.button_rect.collidepoint(
                                    event.pos
                            ):  # checks whether the slider is pressed
                                slider.hit = True  # sets hit to true, so that it will be moved
                        except AttributeError:
                            pass
                # displays the menu on the game window
                vo.draw_screen(lg.get_zustand(), lg.get_background(),
                               lg.get_language(), sh.get_ship(), resource_path,
                               lg.get_task_number(), lg.get_settings())
                other_num = num  # refreshes control number used to fix bug with sliders

            elif event.type == MOUSEBUTTONUP and num != other_num + 1:  # checks whether a mouse button was lifted
                for slider in vo.get_slides():  # goes through every slider
                    slider.hit = False  # sets hit to false, so that it won't be moved
                # displays the menu on the game window
                vo.draw_screen(lg.get_zustand(), lg.get_background(),
                               lg.get_language(), sh.get_ship(), resource_path,
                               lg.get_task_number(), lg.get_settings())

            elif event.type == VIDEORESIZE:  # window size has been adjusted
                video_resize(event.size, sh.get_ship())

            elif event.type == pg.QUIT:  # ueberprueft, ob das Fenster geschlossen wurde
                # ends the program
                settings = running = again = False
                win = 2

        if lg.get_aufgabe(
        ) == "volume":  # checks whether a slider is on the screen
            for slider in vo.get_slides():  # goes through every slider
                if slider.hit:  # checks, whether it is hit
                    # moves the slider and thus changes the value of it
                    slider.move(
                        vo.get_window_size(vo.get_screen_size()[0],
                                           vo.get_screen_size()[1])[2])
                    # displays the volume settings on the game window
                    vo.draw_screen(lg.get_zustand(), lg.get_background(),
                                   lg.get_language(), sh.get_ship(),
                                   resource_path, lg.get_task_number(),
                                   lg.get_settings())

        elif lg.get_aufgabe() == "stats":
            update_statistics()
            # displays the statistics on the game window
            vo.draw_screen(lg.get_zustand(), lg.get_background(),
                           lg.get_language(), sh.get_ship(), resource_path,
                           lg.get_task_number(), lg.get_settings())
            lg.set_aufgabe("statistics")

        if lg.get_zustand() == "ingame":  # game has been started
            settings = False  # continues the game
            running = True
        # continues counting, used to fix a bug instantly having a mousebuttonup event after mousebuttondown
        num += 1
        if num > 254:
            num = 0

        try:
            music.set_volume(lg.get_music_volume()
                             )  # adjusts the volume of the music playing
        except NameError:  # music has not been found
            pass

    return settings, running, win, again
Exemple #7
0
def begins(begin, request, running, settings, win, again):
    """
    loop running at the beginning of the game

    shows a menu,
    settings can be changed that impact the next game and are saved for future games

    :param begin: bool; setings loop is running
    :param request: bool; request loop will run
    :param running: bool; game loop will run
    :param settings: bool; settings loop in game will run
    :param win: int; current winner of the game
    :param again: bool; game is repeated from the begin loop to allow for another game to b played
    :return: bool, bool, bool, int, bool; updated bools for loop management
    """
    global start_time
    # displays the menu on the game window
    vo.refresh_loc_coords(
        vo.get_window_size(vo.get_screen_size()[0],
                           vo.get_screen_size()[1])[2],
        vo.get_window_size(vo.get_screen_size()[0],
                           vo.get_screen_size()[1])[3], lg.get_zustand())
    vo.draw_screen(lg.get_zustand(), lg.get_background(), lg.get_language(),
                   [[[0]]], resource_path, lg.get_task_number(),
                   lg.get_settings())
    num = 0
    other_num = 0
    while begin and lg.get_zustand(
    ) != "end":  # begin loop is running and settings can be changed

        for event in pg.event.get(
        ):  # goes through every input occuring while game window is in focus

            if event.type == MOUSEBUTTONDOWN:  # mouse button was clicked
                # gets size of one field and orientation
                field_size, orientation = vo.get_window_size(
                    vo.get_screen_size()[0],
                    vo.get_screen_size()[1])[2:]
                # executes feature of pressed button if there is one
                button = lg.do_button_start(event.pos[0], event.pos[1],
                                            field_size,
                                            vo.get_buttons()[0], resource_path)
                if button == "end":
                    begin = settings = running = request = again = False
                # displays the menu on the game window
                if lg.get_zustand() != "ingame":
                    vo.draw_screen(lg.get_zustand(), lg.get_background(),
                                   lg.get_language(), [[[0]]], resource_path,
                                   lg.get_task_number(), lg.get_settings())
                if lg.get_aufgabe(
                ) == "volume":  # checks whether a slider is on the screen
                    for slider in vo.get_slides():  # goes through every slider
                        try:
                            if slider.button_rect.collidepoint(
                                    event.pos
                            ):  # checks whether the slider is pressed
                                slider.hit = True  # sets hit to true, so that it will be moved
                        except AttributeError:
                            pass
                    other_num = num  # refreshes control number used to fix bug with sliders

            elif event.type == MOUSEBUTTONUP and num != other_num + 1:  # checks whether a mouse button was lifted
                for slider in vo.get_slides():  # goes through every slider
                    slider.hit = False  # sets hit to false, so that it won't be moved
                # displays the menu on the game window
                vo.draw_screen(lg.get_zustand(), lg.get_background(),
                               lg.get_language(), [[[0]]], resource_path,
                               lg.get_task_number(), lg.get_settings())

            elif event.type == VIDEORESIZE:  # window size has been adjusted
                video_resize(event.size)

            elif event.type == pg.QUIT:  # window was closed
                # ends the program
                running = begin = settings = request = again = False
                win = 2

        if lg.get_aufgabe() == "stats":
            update_statistics()
            # displays the statistics on the game window
            vo.draw_screen(lg.get_zustand(), lg.get_background(),
                           lg.get_language(), [[[0]]], resource_path,
                           lg.get_task_number(), lg.get_settings())
            lg.set_aufgabe("statistics")

        elif lg.get_aufgabe(
        ) == "volume":  # checks whether a slider is on the screen
            for slider in vo.get_slides():  # goes through every slider
                if slider.hit:  # checks, whether it is hit
                    # moves the slider and thus changes the value of it
                    slider.move(
                        vo.get_window_size(vo.get_screen_size()[0],
                                           vo.get_screen_size()[1])[2])
                    # displays the volume settings on the game window
                    vo.draw_screen(lg.get_zustand(), lg.get_background(),
                                   lg.get_language(), [[[0]]], resource_path,
                                   lg.get_task_number(), lg.get_settings())

        # continues counting, used to fix a bug instantly having a mousebuttonup event after mousebuttondown
        num += 1
        if num > 254:
            num = 0

        if lg.get_zustand() == "request":  # game has been started
            begin = False  # starts the game

        try:
            music.set_volume(lg.get_music_volume()
                             )  # adjusts the volume of the music playing
        except NameError:  # music could not be found
            pass

    return request, running, settings, win, again