コード例 #1
0
    def __init__(self, display):
        mytheme = pygame_menu.Theme(
            background_color=(0, 0, 0, 0),  # transparent background
            title_background_color=(4, 47, 126),
            title_font_shadow=True,
            widget_padding=25,
        )
        self.display = display
        self.menu = pygame_menu.Menu(
            "Pause",
            display.screen_size,
            display.screen_size,
            theme=mytheme,
        )

        self.menu.add.button("Resume", self.on_resume)
        self.menu.add.button("Quit", self.on_quit)
コード例 #2
0
 def __init__(self, bgColor: tuple[int, int,
                                   int], font: str, intro_image: str,
              textColor: tuple[int, int, int], width: int, height: int):
     """Создание темы с конфертацией изображения под формат и всеми настройками."""
     self.myImage = pygame_menu.baseimage.BaseImage(
         image_path=intro_image,
         drawing_mode=pygame_menu.baseimage.IMAGE_MODE_FILL)
     self.myTheme = pygame_menu.Theme(
         background_color=self.myImage,
         title_background_color=(76, 36, 25),
         title_font_shadow=True,
         widget_padding=25,
         widget_font="Arial",
         focus_background_color=(217, 140, 63),
         selection_color=(217, 178, 63),
         title_font_color=(217, 178, 63),
         widget_font_color=(217, 178, 63),
         title_bar_style=pygame_menu.widgets.MENUBAR_STYLE_UNDERLINE)
コード例 #3
0
    def __init__(self) -> None:
        """
        Constructor.
        """
        self.surface = create_example_window('Example - Dynamic Widget Update',
                                             (640, 480), flags=pygame.NOFRAME)

        # Create app theme and menu
        theme = pygame_menu.Theme()

        theme.background_color = (0, 0, 0)
        theme.scrollbar_cursor = pygame_menu.locals.CURSOR_HAND
        theme.title_bar_style = pygame_menu.widgets.MENUBAR_STYLE_TITLE_ONLY
        theme.title_close_button_cursor = pygame_menu.locals.CURSOR_HAND
        theme.title_floating = True
        theme.widget_selection_effect = pygame_menu.widgets.NoneSelection()

        # Load the SS image
        base_img = pygame_menu.BaseImage(SOLAR_SYSTEM_IMG, frombase64=True)

        # Create planets
        self.planets = {
            'sun': Planet(
                base_img.copy().crop(1, 1, 237, 238),
                'The Sun is the Solar System\'s star and by far its most massive '
                'component. Its large mass (332,900 Earth masses), which comprises '
                '99.86% of all the mass in the Solar System, produces temperatures '
                'and densities in its core high enough to sustain nuclear fusion '
                'of hydrogen into helium, making it a main-sequence star. This '
                'releases an enormous amount of energy, mostly radiated into space '
                'as electromagnetic radiation peaking in visible light.',
                'https://en.wikipedia.org/wiki/Sun',
                radius=0,
                period=0,
                fontsize=theme.widget_font_size * 1.25
            ),
            'mercury': Planet(
                base_img.copy().crop(239, 16, 50, 50),
                'Mercury (0.4 AU from the Sun) is the closest planet to the Sun '
                'and on average, all seven other planets. The smallest planet in '
                'the Solar System (0.055 Mo), Mercury has no natural satellites. '
                'Besides impact craters, its only known geological features are '
                'lobed ridges or rupes that were probably produced by a period of '
                'contraction early in its history. Mercury\'s very tenuous '
                'atmosphere consists of atoms blasted off its surface by the solar '
                'wind. Its relatively large iron core and thin mantle have not yet '
                'been adequately explained. Hypotheses include that its outer '
                'layers were stripped off by a giant impact, or that it was '
                'prevented from fully accreting by the young Sun\'s energy.',
                'https://en.wikipedia.org/wiki/Mercury_(planet)',
                radius=0.4,
                period=0.24,
                fontsize=theme.widget_font_size * 0.5
            ),
            'venus': Planet(
                base_img.copy().crop(238, 156, 82, 82),
                'Venus (0.7 AU from the Sun) is close in size to Earth (0.815 Mo) '
                'and, like Earth, has a thick silicate mantle around an iron core, '
                'a substantial atmosphere, and evidence of internal geological '
                'activity. It is much drier than Earth, and its atmosphere is '
                'ninety times as dense. Venus has no natural satellites. It is '
                'the hottest planet, with surface temperatures over 400 °C (752 '
                '°F), most likely due to the amount of greenhouse gases in the '
                'atmosphere. No definitive evidence of current geological '
                'activity has been detected on Venus, but it has no magnetic '
                'field that would prevent depletion of its substantial atmosphere, '
                'which suggests that its atmosphere is being replenished by '
                'volcanic eruptions.',
                'https://en.wikipedia.org/wiki/Venus',
                radius=0.7,
                period=0.615,
                fontsize=theme.widget_font_size * 0.6
            ),
            'earth': Planet(
                base_img.copy().crop(441, 148, 89, 89),
                'Earth (1 AU from the Sun) is the largest and densest of the inner '
                'planets, the only one known to have current geological activity, '
                'and the only place where life is known to exist. Its liquid '
                'hydrosphere is unique among the terrestrial planets, and it is '
                'the only planet where plate tectonics has been observed. Earth\'s '
                'atmosphere is radically different from those of the other planets, '
                'having been altered by the presence of life to contain 21% free '
                'oxygen. It has one natural satellite, the Moon, the only large '
                'satellite of a terrestrial planet in the Solar System.',
                'https://en.wikipedia.org/wiki/Earth',
                radius=1,
                period=1,
                fontsize=theme.widget_font_size * 0.85
            ),
            'moon': Planet(
                base_img.copy().crop(247, 86, 64, 64),
                'The Moon is Earth\'s only proper natural satellite. It is one '
                'quarter the diameter of Earth (comparable to the width of '
                'Australia) making it the largest natural satellite in the Solar '
                'System relative to the size of its planet. It is the fifth '
                'largest satellite in the Solar System and is larger than any '
                'dwarf planet. The Moon orbits Earth at an average lunar distance '
                'of 384,400 km (238,900 mi), or 1.28 light-seconds. Its '
                'gravitational influence produces Earth\'s tides and slightly '
                'lengthens Earth\'s day.',
                'https://en.wikipedia.org/wiki/Moon',
                radius=0.35,
                period=0.2,
                fontsize=theme.widget_font_size * 0.5
            ),
            'mars': Planet(
                base_img.copy().crop(535, 170, 69, 69),
                'Mars (1.5 AU from the Sun) is smaller than Earth and Venus (0.107 '
                'Mo). It has an atmosphere of mostly carbon dioxide with a '
                'surface pressure of 6.1 millibars (roughly 0.6% of that of Earth'
                '). Its surface, peppered with vast volcanoes, such as Olympus '
                'Mons, and rift valleys, such as Valles Marineris, shows '
                'geological activity that may have persisted until as recently '
                'as 2 million years ago. Its red colour comes from iron oxide '
                '(rust) in its soil. Mars has two tiny natural satellites (Deimos '
                'and Phobos) thought to be either captured asteroids, or ejected '
                'debris from a massive impact early in Mars\'s history.',
                'https://en.wikipedia.org/wiki/Mars',
                radius=1.25,
                period=1.880,
                fontsize=theme.widget_font_size * 0.95
            ),
            'jupiter': Planet(
                base_img.copy().crop(322, 89, 118, 118),
                'Jupiter (5.2 AU), at 318 Mo, is 2.5 times the mass of all the '
                'other planets put together. It is composed largely of hydrogen '
                'and helium. Jupiter\'s strong internal heat creates semi-permanent '
                'features in its atmosphere, such as cloud bands and the Great '
                'Red Spot. Jupiter has 79 known satellites. The four largest, '
                'Ganymede, Callisto, Io, and Europa, show similarities to the '
                'terrestrial planets, such as volcanism and internal heating. '
                'Ganymede, the largest satellite in the Solar System, is larger '
                'than Mercury.',
                'https://en.wikipedia.org/wiki/Jupiter',
                radius=1.75,
                period=11.862,
                fontsize=theme.widget_font_size * 1.1
            ),
            'uranus': Planet(
                base_img.copy().crop(525, 83, 83, 83),
                'Uranus (19.2 AU), at 14 Mo, is the lightest of the outer '
                'planets. Uniquely among the planets, it orbits the Sun on its '
                'side; its axial tilt is over ninety degrees to the ecliptic. It '
                'has a much colder core than the other giant planets and radiates '
                'very little heat into space. Uranus has 27 known satellites, the '
                'largest ones being Titania, Oberon, Umbriel, Ariel, and Miranda.',
                'https://en.wikipedia.org/wiki/Uranus',
                radius=2,
                period=84.0205,
                fontsize=theme.widget_font_size
            ),
            'neptune': Planet(
                base_img.copy().crop(448, 1, 92, 92),
                'Neptune (30.1 AU), though slightly smaller than Uranus, is more '
                'massive (17 Mo) and hence more dense. It radiates more internal '
                'heat, but not as much as Jupiter or Saturn. Neptune has 14 known '
                'satellites. The largest, Triton, is geologically active, with '
                'geysers of liquid nitrogen. Triton is the only large satellite '
                'with a retrograde orbit. Neptune is accompanied in its orbit by '
                'several minor planets, termed Neptune trojans, that are in 1:1 '
                'resonance with it.',
                'https://en.wikipedia.org/wiki/Neptune',
                radius=2.25,
                period=164.8,
                fontsize=theme.widget_font_size
            ),
        }

        self.menu = pygame_menu.Menu('Solar System', 640, 480,
                                     onclose=pygame_menu.events.EXIT,
                                     theme=theme, mouse_motion_selection=True)

        # Configure planets and add them to the Menu
        for p in self.planets.keys():
            planet: 'Planet' = self.planets[p]

            # Configure planet
            planet.name = str(p).capitalize()

            # Create submenu for given planet
            submenu = pygame_menu.Menu(planet.name + ' Info', 640, 480, theme=theme,
                                       mouse_motion_selection=True, center_content=False)
            submenu_area_deco = submenu.get_scrollarea().get_decorator()
            submenu_area_deco.add_callable(self.draw_universe_background)

            # Add go back button with a background image
            submenu.add.vertical_margin(150)
            go_back = submenu.add.button('Back to Menu', pygame_menu.events.BACK,
                                         cursor=pygame_menu.locals.CURSOR_HAND)
            go_back_img = planet.image.copy().resize(150, 150)
            # Get color from figure's center pixel
            go_back_color = go_back_img.get_at((100, 100), ignore_alpha=True)
            go_back.get_decorator().add_baseimage(0, 0, go_back_img, centered=True)
            go_back_selection = pygame_menu.widgets.HighlightSelection(border_width=2)
            go_back.set_selection_effect(go_back_selection.set_color(go_back_color))

            # Description
            submenu.add.vertical_margin(75)
            submenu.add.label('Description', align=pygame_menu.locals.ALIGN_LEFT,
                              font_name=pygame_menu.font.FONT_OPEN_SANS_BOLD,
                              margin=(5, 10))
            label = submenu.add.label(planet.info, max_char=70,
                                      align=pygame_menu.locals.ALIGN_LEFT,
                                      margin=(29, 1), font_size=20,
                                      font_name=pygame_menu.font.FONT_PT_SERIF,
                                      font_color=(255, 255, 255), padding=0)
            for line in label:
                line.set_max_width(565)
            submenu.add.url(planet.url, align=pygame_menu.locals.ALIGN_LEFT,
                            margin=(20, 1), font_size=20,
                            font_name=pygame_menu.font.FONT_PT_SERIF)
            submenu.add.vertical_margin(40)  # Bottom margin

            # Create advanced button
            planet.image.scale(0.35, 0.35)
            button = self.menu.add.button(planet.name, submenu,
                                          font_size=planet.fontsize)
            button.set_cursor(pygame_menu.locals.CURSOR_HAND)
            button.set_float()
            button.get_decorator().add_baseimage(0, 2, planet.image, centered=True)
            button.set_attribute('planet', planet)
            button.add_draw_callback(self.rotate_planet)
            button_selection = pygame_menu.widgets.LeftArrowSelection(arrow_size=(20, 30),
                                                                      blink_ms=1000)
            button.set_selection_effect(button_selection.set_color(go_back_color))

            # Set random times
            button.set_attribute('t', random.random() * 2 * math.pi)

            # Save button reference to object
            planet.button = button

        # Add draw stars as Menu's decoration
        self.menu.get_scrollarea().get_decorator().add_callable(self.draw_universe_background)

        # Set update event
        self.menu.set_onupdate(self.process_events)

        # Initialize stars random colors
        self.stars = []
        for i in range(100):
            self.add_star()

        # Set the nebulas
        nebula = pygame_menu.BaseImage(NEBULA_IMG, frombase64=True,
                                       drawing_mode=pygame_menu.baseimage.IMAGE_MODE_SIMPLE)
        self.nebulas = [
            nebula.copy().set_drawing_offset((150, 400)).scale2x().set_alpha(25),
            nebula.copy().set_drawing_offset((500, 50)).scale(3, 3).rotate(90).set_alpha(50).pick_channels('b'),
            nebula.copy().set_drawing_offset((50, 100)).scale2x().rotate(175).set_alpha(75).pick_channels('r')
        ]
        for nebula in self.nebulas:
            nebula.set_drawing_position(pygame_menu.locals.POSITION_CENTER)
            nebula.checkpoint()  # Because rotation method works from checkpointed surface
            nebula.set_attribute('delta_angle', 0.25 * random.randint(-1, 1) * random.random())

        # Add shooting stars
        self.shooting_stars = []
        for i in range(3):
            self.add_shooting_star()

        # Update values
        self.rotation_velocity = 0.0003
コード例 #4
0
    def __init__(self) -> None:
        """
        Constructor.
        """
        self.surface = create_example_window('Example - Calculator',
                                             (320, 480))

        # Configure theme
        theme = pygame_menu.Theme()

        theme.background_color = (43, 43, 43)
        theme.title_background_color = (43, 43, 43)
        theme.title_bar_style = pygame_menu.widgets.MENUBAR_STYLE_SIMPLE
        theme.title_close_button_cursor = pygame_menu.locals.CURSOR_HAND
        theme.title_font_size = 35
        theme.widget_alignment = pygame_menu.locals.ALIGN_LEFT
        theme.widget_background_color = None
        theme.widget_font = pygame_menu.font.FONT_DIGITAL
        theme.widget_font_color = (255, 255, 255)
        theme.widget_font_size = 40
        theme.widget_padding = 0
        theme.widget_selection_effect = \
            pygame_menu.widgets.HighlightSelection(1, 0, 0).set_color((120, 120, 120))

        self.menu = pygame_menu.Menu(
            '',
            320,
            480,
            center_content=False,
            mouse_motion_selection=True,
            onclose=pygame_menu.events.EXIT,
            overflow=False,
            theme=theme,
        )
        menu_deco = self.menu.get_scrollarea().get_decorator()

        # Add the layout
        self.menu.add.vertical_margin(40)
        menu_deco.add_rectangle(10,
                                88,
                                300,
                                55, (60, 63, 65),
                                use_center_positioning=False)
        self.screen = self.menu.add.label('0',
                                          background_color=None,
                                          margin=(10, 0),
                                          selectable=True,
                                          selection_effect=None)
        self.menu.add.vertical_margin(20)

        cursor = pygame_menu.locals.CURSOR_HAND

        # Add horizontal frames
        f1 = self.menu.add.frame_h(299, 54, margin=(10, 0))
        b1 = f1.pack(
            self.menu.add.button('1', lambda: self._press(1), cursor=cursor))
        b2 = f1.pack(self.menu.add.button('2',
                                          lambda: self._press(2),
                                          cursor=cursor),
                     align=pygame_menu.locals.ALIGN_CENTER)
        b3 = f1.pack(self.menu.add.button('3',
                                          lambda: self._press(3),
                                          cursor=cursor),
                     align=pygame_menu.locals.ALIGN_RIGHT)
        self.menu.add.vertical_margin(10)

        f2 = self.menu.add.frame_h(299, 54, margin=(10, 0))
        b4 = f2.pack(
            self.menu.add.button('4', lambda: self._press(4), cursor=cursor))
        b5 = f2.pack(self.menu.add.button('5',
                                          lambda: self._press(5),
                                          cursor=cursor),
                     align=pygame_menu.locals.ALIGN_CENTER)
        b6 = f2.pack(self.menu.add.button('6',
                                          lambda: self._press(6),
                                          cursor=cursor),
                     align=pygame_menu.locals.ALIGN_RIGHT)
        self.menu.add.vertical_margin(10)

        f3 = self.menu.add.frame_h(299, 54, margin=(10, 0))
        b7 = f3.pack(
            self.menu.add.button('7', lambda: self._press(7), cursor=cursor))
        b8 = f3.pack(self.menu.add.button('8',
                                          lambda: self._press(8),
                                          cursor=cursor),
                     align=pygame_menu.locals.ALIGN_CENTER)
        b9 = f3.pack(self.menu.add.button('9',
                                          lambda: self._press(9),
                                          cursor=cursor),
                     align=pygame_menu.locals.ALIGN_RIGHT)
        self.menu.add.vertical_margin(10)

        f4 = self.menu.add.frame_h(299, 54, margin=(10, 0))
        b0 = f4.pack(
            self.menu.add.button('0', lambda: self._press(0), cursor=cursor))
        b_plus = f4.pack(self.menu.add.button('+',
                                              lambda: self._press('+'),
                                              cursor=cursor),
                         align=pygame_menu.locals.ALIGN_CENTER)
        b_minus = f4.pack(self.menu.add.button('-',
                                               lambda: self._press('-'),
                                               cursor=cursor),
                          align=pygame_menu.locals.ALIGN_RIGHT)
        self.menu.add.vertical_margin(10)

        f5 = self.menu.add.frame_h(299, 54, margin=(10, 0))
        b_times = f5.pack(
            self.menu.add.button('x', lambda: self._press('x'), cursor=cursor))
        b_div = f5.pack(self.menu.add.button('/',
                                             lambda: self._press('/'),
                                             cursor=cursor),
                        align=pygame_menu.locals.ALIGN_CENTER)
        beq = f5.pack(self.menu.add.button('=',
                                           lambda: self._press('='),
                                           cursor=cursor),
                      align=pygame_menu.locals.ALIGN_RIGHT)

        # Add decorator for each object
        for widget in (b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, beq, b_plus,
                       b_minus, b_times, b_div):
            w_deco = widget.get_decorator()
            if widget != beq:
                w_deco.add_rectangle(-37, -27, 74, 54, (15, 15, 15))
                on_layer = w_deco.add_rectangle(-37, -27, 74, 54, (84, 84, 84))
            else:
                w_deco.add_rectangle(-37, -27, 74, 54, (38, 96, 103))
                on_layer = w_deco.add_rectangle(-37, -27, 74, 54,
                                                (40, 171, 187))
            w_deco.disable(on_layer)
            widget.set_attribute('on_layer', on_layer)

            def widget_select(sel: bool, wid: 'pygame_menu.widgets.Widget', _):
                """
                Function triggered if widget is selected
                """
                lay = wid.get_attribute('on_layer')
                if sel:
                    wid.get_decorator().enable(lay)
                else:
                    wid.get_decorator().disable(lay)

            widget.set_onselect(widget_select)
            widget.set_padding((2, 19, 0, 23))
            widget._keyboard_enabled = False

        self.prev = ''
        self.curr = ''
        self.op = ''

        self.menu.set_onupdate(self.process_events)
        self.menu.set_onwindowmouseleave(
            lambda m: self.screen.select(update_menu=True))
コード例 #5
0
ファイル: timer_clock.py プロジェクト: zinede13/pygame-menu
def main(test: bool = False) -> None:
    """
    Main program.

    :param test: Indicate function is being tested
    :return: None
    """

    # -------------------------------------------------------------------------
    # Init
    # -------------------------------------------------------------------------

    # Write help message on console
    for m in HELP:
        print(m)

    # Create window
    global surface
    surface = create_example_window('Example - Timer Clock', (W_SIZE, H_SIZE))

    # Main timer and game clock
    clock = pygame.time.Clock()
    global timer
    timer = [0]
    dt = 1.0 / FPS
    timer_font = pygame_menu.font.get_font(pygame_menu.font.FONT_NEVIS, 100)

    # -------------------------------------------------------------------------
    # Create menus: Timer
    # -------------------------------------------------------------------------

    timer_theme = pygame_menu.themes.THEME_DARK.copy()  # Create a new copy
    timer_theme.background_color = (0, 0, 0, 180)  # Enable transparency

    # Timer
    timer_menu = pygame_menu.Menu(height=400,
                                  onclose=pygame_menu.events.RESET,
                                  theme=timer_theme,
                                  title='Timer Menu',
                                  width=600)

    # Add widgets
    timer_menu.add.button('Reset timer', reset_timer)

    # Adds a selector (element that can handle functions)
    timer_menu.add.selector(
        title='Change color ',
        items=[
            ('Random', (-1, -1,
                        -1)),  # Values of selector, call to change_color_bg
            ('Default', (128, 0, 128)),
            ('Black', (0, 0, 0)),
            ('Blue', (12, 12, 200))
        ],
        default=1,  # Optional parameter that sets default item of selector
        onchange=change_color_bg,  # Action when changing element with left/right
        onreturn=change_color_bg,  # Action when pressing return on an element
        # Optional parameters to change_color_bg function
        write_on_console=True)
    timer_menu.add.button('Update game object',
                          TestCallClassMethod().update_game_settings)
    timer_menu.add.button('Return to Menu', pygame_menu.events.BACK)
    timer_menu.add.button('Close Menu', pygame_menu.events.CLOSE)

    # -------------------------------------------------------------------------
    # Create menus: Help
    # -------------------------------------------------------------------------
    help_theme = pygame_menu.Theme(
        background_color=(30, 50, 107, 190),  # 75% opacity
        title_background_color=(120, 45, 30, 190),
        title_font=pygame_menu.font.FONT_FRANCHISE,
        title_font_size=60,
        widget_font=pygame_menu.font.FONT_FRANCHISE,
        widget_font_color=(170, 170, 170),
        widget_font_size=45,
        widget_shadow=False,
        widget_shadow_position=pygame_menu.locals.POSITION_SOUTHEAST)

    help_menu = pygame_menu.Menu(
        height=600,  # Fullscreen
        theme=help_theme,
        title='Help',
        width=800)
    for m in HELP:
        help_menu.add.label(m, align=pygame_menu.locals.ALIGN_CENTER)
    help_menu.add.vertical_margin(25)
    help_menu.add.button('Return to Menu', pygame_menu.events.BACK)

    # -------------------------------------------------------------------------
    # Create menus: About
    # -------------------------------------------------------------------------
    about_theme = pygame_menu.themes.THEME_DARK.copy()
    about_theme.widget_font = pygame_menu.font.FONT_NEVIS
    about_theme.title_font = pygame_menu.font.FONT_8BIT
    about_theme.title_offset = (5, -2)
    about_theme.widget_offset = (0, 0.14)

    about_menu = pygame_menu.Menu(center_content=False,
                                  height=400,
                                  mouse_visible=False,
                                  theme=about_theme,
                                  title='About',
                                  width=600)
    for m in ABOUT:
        about_menu.add.label(m, margin=(0, 0))
    about_menu.add.label('')
    about_menu.add.button('Return to Menu', pygame_menu.events.BACK)

    # -------------------------------------------------------------------------
    # Create menus: Main menu
    # -------------------------------------------------------------------------
    main_menu = pygame_menu.Menu(enabled=False,
                                 height=400,
                                 theme=pygame_menu.themes.THEME_DARK,
                                 title='Main Menu',
                                 width=600)

    main_menu.add.button(timer_menu.get_title(),
                         timer_menu)  # Add timer submenu
    main_menu.add.button(help_menu.get_title(), help_menu)  # Add help submenu
    main_menu.add.button(about_menu.get_title(),
                         about_menu)  # Add about submenu
    main_menu.add.button('Exit', pygame_menu.events.EXIT)  # Add exit function

    # -------------------------------------------------------------------------
    # Main loop
    # -------------------------------------------------------------------------
    while True:

        # Tick clock
        clock.tick(FPS)
        timer[0] += dt

        # Title is evaluated at current level as the title of the base pointer object (main_menu)
        # can change if user opens submenus
        current_menu = main_menu.get_current()
        if current_menu.get_title() != 'Main Menu' or not main_menu.is_enabled(
        ):
            # Draw timer
            surface.fill(COLOR_BACKGROUND)
            time_string = str(datetime.timedelta(seconds=int(timer[0])))
            time_blit = timer_font.render(time_string, True, (255, 255, 255))
            time_blit_size = time_blit.get_size()
            surface.blit(time_blit, (int(W_SIZE / 2 - time_blit_size[0] / 2),
                                     int(H_SIZE / 2 - time_blit_size[1] / 2)))
        else:
            # Background color if the menu is enabled and timer is hidden
            surface.fill((40, 0, 40))

        # Application events
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE and current_menu.get_title(
                ) == 'Main Menu':
                    main_menu.toggle()

        if main_menu.is_enabled():
            main_menu.draw(surface)
            main_menu.update(events)

        # Flip surface
        pygame.display.flip()

        # At first loop returns
        if test:
            break
コード例 #6
0
if pygame.key.get_pressed == pygame.K_m:
    VOLUME = pygame.mixer.music.get_volume()- 0.1
    pygame.mixer.music.set_volume(VOLUME) 
if pygame.key.get_pressed == pygame.K_p:
    VOLUME = pygame.mixer.music.get_volume()+ 0.1
    pygame.mixer.music.set_volume(VOLUME) 
pygame.mixer.music.get_volume


########################### menu #####################

font = pygame_menu.font.FONT_8BIT
surface = pygame.display.set_mode((1200, 800))
title=pygame_menu.widgets.MENUBAR_STYLE_NONE
my_theme= pygame_menu.Theme(widget_font=font,
                            background_color=(0, 0, 0, 0),
                            title_bar_style=pygame_menu.widgets.MENUBAR_STYLE_NONE,
                            title_font=font,title_offset=(380,100))
menu = pygame_menu.Menu(800, 1200, 'Swear Square', theme=my_theme)
menu.add.button('Play', start_the_game)
menu.add.button('About',credit)
menu.add.button('Settings', sett)
menu.add.button('Quit', pygame_menu.events.EXIT)





############################# About #############
about_theme= pygame_menu.Theme(widget_font=font,
                               background_color=(0, 0, 0, 0),
                               title_bar_style=pygame_menu.widgets.MENUBAR_STYLE_NONE,
コード例 #7
0
    def test_vfill(self) -> None:
        """
        Test VFill widget.
        """
        menu = MenuUtils.generic_menu()
        b = menu.add.button('nice')  # Add button
        bh = b.get_height()
        self.assertEqual(menu.get_height(widget=True), bh)
        self.assertEqual(menu.get_size(widget=True), b.get_size())

        # Now add 1 vfill, this should use all available height
        vf1 = menu.add.vertical_fill()
        self.assertEqual(vf1.get_width(), 0)
        self.assertEqual(vf1.get_height(),
                         menu.get_height(inner=True) - bh - 1)
        self.assertEqual(
            menu.get_height(inner=True) - 1, menu.get_height(widget=True))
        self.assertEqual(menu.get_size(widget=True),
                         (b.get_width(), bh + vf1.get_height()))

        # Add another vfill, now both vfills should have the same height
        vf2 = menu.add.vertical_fill()
        self.assertEqual(vf1.get_height(),
                         vf2.get_height() + 1)  # Second vfill removes 1px
        self.assertEqual(
            menu.get_height(inner=True) - 1, menu.get_height(widget=True))

        # Test another menu, but with interlaced buttons and vfills
        menu = MenuUtils.generic_menu()
        b1 = menu.add.button(1)
        vf1 = menu.add.vertical_fill()
        menu.add.button(2)
        vf2 = menu.add.vertical_fill()
        menu.add.button(3)
        vf3 = menu.add.vertical_fill()
        menu.add.button(4)
        self.assertEqual(vf1.get_width(), 0)
        self.assertEqual(vf1.get_height(), vf2.get_height())
        self.assertEqual(vf2.get_height(), vf3.get_height() + 1)
        prev_height = vf1.get_height()

        # Now, if more buttons are added, the height of previous vills should be zero
        added_last = []
        for i in range(5, 10):
            b = menu.add.button(i)
            added_last.append(b)
        self.assertEqual(vf1.get_height(), 0)
        self.assertEqual(vf2.get_height(), 0)
        self.assertEqual(vf3.get_height(), 0)

        # Removing buttons should also update vfills
        for b in added_last:
            menu.remove_widget(b)
        self.assertEqual(vf1.get_height(), prev_height)

        # Hiding vfill should also update
        vfill_total = vf1.get_height() + vf2.get_height() + vf3.get_height()
        vf2.hide()
        vfill_total_after = vf1.get_height() + vf3.get_height()
        self.assertEqual(vf1.get_height(), vf3.get_height() + 1)
        self.assertEqual(vfill_total, vfill_total_after - 1)
        vf2.show()
        self.assertEqual(
            vfill_total,
            vf1.get_height() + vf2.get_height() + vf3.get_height())

        # Hiding a button should also affect vfills
        vf1_height_prev = vf1.get_height()
        b1_height = math.ceil(b1.get_height() / 3)
        b1.hide()
        self.assertEqual(vf1.get_height(), vf1_height_prev + b1_height)
        b1.show()
        self.assertEqual(vf1.get_height(), vf1_height_prev)

        # Test min height
        menu = MenuUtils.generic_menu()
        b = menu.add.button(1)
        v = menu.add.vertical_fill(10)
        self.assertEqual(v.get_height(),
                         menu.get_height(inner=True) - b.get_height() - 1)
        for i in range(20):
            menu.add.button(i)
        self.assertEqual(v.get_height(), 10)

        # Test widget alignment
        menu = MenuUtils.generic_menu(theme=pygame_menu.Theme(
            widget_alignment=pygame_menu.locals.ALIGN_LEFT))

        # Now add 1 vfill, this should use all available height
        vf1 = menu.add.vertical_fill()
        self.assertEqual(menu.get_size(widget=True), (0, vf1.get_height()))
        self.assertEqual(vf1.get_height(), menu.get_height(inner=True) - 1)

        # Add button, this should change widget size width
        b = menu.add.button('nice')  # Add button
        self.assertEqual(menu.get_size(widget=True),
                         (b.get_width(), b.get_height() + vf1.get_height()))

        # Now add 1 vfill, this should use all available height
        vf2 = menu.add.vertical_fill()
        self.assertEqual(menu.get_size(widget=True),
                         (b.get_width(), b.get_height() + vf1.get_height() +
                          vf2.get_height()))