def main(test: bool = False) -> None: """ Main program. :param test: Indicate function is being tested :return: None """ # ------------------------------------------------------------------------- # Globals # ------------------------------------------------------------------------- global main_menu global sound global surface # ------------------------------------------------------------------------- # Create window # ------------------------------------------------------------------------- surface = create_example_window('Example - Image Background', WINDOW_SIZE) clock = pygame.time.Clock() # ------------------------------------------------------------------------- # Create menus: Main menu # ------------------------------------------------------------------------- main_menu_theme = pygame_menu.themes.THEME_ORANGE.copy() main_menu_theme.set_background_color_opacity(0.5) # 50% opacity main_menu = pygame_menu.Menu( height=WINDOW_SIZE[1] * 0.7, onclose=pygame_menu.events.EXIT, # User press ESC button theme=main_menu_theme, title='Epic Menu', width=WINDOW_SIZE[0] * 0.8) widget_colors_theme = pygame_menu.themes.THEME_ORANGE.copy() widget_colors_theme.widget_font_size = 20 widget_colors_theme.set_background_color_opacity(0.5) # 50% opacity widget_colors = pygame_menu.Menu(height=WINDOW_SIZE[1] * 0.7, theme=widget_colors_theme, title='Widget backgrounds', width=WINDOW_SIZE[0] * 0.8) button_image = pygame_menu.BaseImage( pygame_menu.baseimage.IMAGE_EXAMPLE_CARBON_FIBER) widget_colors.add.button('Opaque color button', background_color=(100, 100, 100)) widget_colors.add.button('Transparent color button', background_color=(50, 50, 50, 200), font_size=40) widget_colors.add.button( 'Transparent background inflate to selection effect', background_color=(50, 50, 50, 200), margin=(0, 15)).background_inflate_to_selection_effect() widget_colors.add.button( 'Background inflate + font background color', background_color=(50, 50, 50, 200), font_background_color=(200, 200, 200)).background_inflate_to_selection_effect() widget_colors.add.button( 'This inflates background to match selection effect', background_color=button_image, font_color=(255, 255, 255), font_size=15).selection_expand_background = True widget_colors.add.button( 'This is already inflated to match selection effect', background_color=button_image, font_color=(255, 255, 255), font_size=15).background_inflate_to_selection_effect() main_menu.add.button('Test different widget colors', widget_colors) main_menu.add.button('Another fancy button', lambda: print('This button has been pressed')) main_menu.add.button('Quit', pygame_menu.events.EXIT) # ------------------------------------------------------------------------- # Main loop # ------------------------------------------------------------------------- while True: # Tick clock.tick(FPS) # Main menu main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS) # Flip surface pygame.display.flip() # At first loop returns if test: break
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- """ import sys sys.path.insert(0, '../../') sys.path.insert(0, '../../../') import pygame_menu from pygame_menu.examples import create_example_window surface = create_example_window('Example - Test', (400, 400)) theme = pygame_menu.themes.THEME_DARK.copy() theme.title_font_size = 35 theme.widget_selection_effect.zero_margin() theme.widget_font_size = 25 menu = pygame_menu.Menu(column_min_width=400, height=400, theme=theme, title='Color entry', onclose=pygame_menu.events.CLOSE, width=400) # Paste here the example menu.add.button('rr')
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) goback = submenu.add.button('Back to Menu', pygame_menu.events.BACK, cursor=pygame_menu.locals.CURSOR_HAND) goback_img = planet.image.copy().resize(150, 150) goback_color = goback_img.get_at( (100, 100), ignore_alpha=True) # Get color from the figure's center pixel goback.get_decorator().add_baseimage(0, 0, goback_img, centered=True) goback_selection = pygame_menu.widgets.HighlightSelection( border_width=2) goback.set_selection_effect( goback_selection.set_color(goback_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)) labl = submenu.add.label(planet.info, max_char=70, align=pygame_menu.locals.ALIGN_LEFT, margin=(20, 1), font_size=20, font_name=pygame_menu.font.FONT_PT_SERIF, font_color=(255, 255, 255)) for line in labl: line.set_max_width(580) 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, 0, 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(goback_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
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))
def __init__(self) -> None: """ Constructor. """ self.surface = create_example_window('Example - Dynamic Widget Update', (640, 480), flags=pygame.NOFRAME) # Load image default_image = pygame_menu.BaseImage( image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_PYGAME_MENU).scale( 0.2, 0.2) # Set theme theme = pygame_menu.themes.THEME_DEFAULT.copy() theme.title_bar_style = pygame_menu.widgets.MENUBAR_STYLE_UNDERLINE_TITLE theme.title_close_button_cursor = pygame_menu.locals.CURSOR_HAND theme.title_font_color = (35, 35, 35) # This dict stores the values of the widgets to be changed dynamically self.modes = { 1: { 'image': default_image.copy(), 'label': { 'color': theme.widget_font_color, 'size': theme.widget_font_size, 'text': 'The first one is very epic' } }, 2: { 'image': default_image.copy().to_bw(), 'label': { 'color': (0, 0, 0), 'size': 20, 'text': 'This other one is also epic, but fancy' } }, 3: { 'image': default_image.copy().flip(False, True).pick_channels('r'), 'label': { 'color': (255, 0, 0), 'size': 45, 'text': 'YOU D I E D' } } } # Create menus self.menu = pygame_menu.Menu(height=480, onclose=pygame_menu.events.CLOSE, theme=theme, title='Everything is dynamic now', width=640) self.selector_widget = self.menu.add.selector( title='Pick one option: ', items=[('The first', 1), ('The second', 2), ('The final mode', 3)], onchange=self._on_selector_change) self.image_widget = self.menu.add.image( image_path=self.modes[1]['image'], padding=(25, 0, 0, 0) # top, right, bottom, left ) self.item_description_widget = self.menu.add.label(title='') self.quit_button = self.menu.add.button('Quit', pygame_menu.events.EXIT) self.quit_button_fake = self.menu.add.button('You cannot quit', self.fake_quit, font_color=(255, 255, 255)) self.quit_button_fake.add_draw_callback(self.animate_quit_button) # Update the widgets based on selected value from selector # get_value returns selected item tuple and index, so [0][1] means the second object from ('The first', 1) tuple self._update_from_selection(int( self.selector_widget.get_value()[0][1]))
def main(test: bool = False) -> None: """ Main function. :param test: Indicate function is being tested :return: None """ scr_size = (400, 600) screen = create_example_window('Example - Scrollbar', scr_size) world = make_world(int(scr_size[0] * 4), scr_size[1] * 3) screen.fill((120, 90, 130)) thick_h = 20 thick_v = 40 # Horizontal ScrollBar sb_h = ScrollBar(scr_size[0] - thick_v, (50, world.get_width() - scr_size[0] + thick_v), slider_pad=2, page_ctrl_thick=thick_h, onchange=h_changed) sb_h.set_shadow(color=(0, 0, 0), position=_locals.POSITION_SOUTHEAST) sb_h.set_controls(False) sb_h.set_position(0, scr_size[1] - thick_h) sb_h.set_page_step(scr_size[0] - thick_v) # Vertical ScrollBar # noinspection PyArgumentEqualDefault sb_v = ScrollBar(scr_size[1] - thick_h, (0, world.get_height() - scr_size[1] + thick_h), '', _locals.ORIENTATION_VERTICAL, 6, (135, 193, 180), thick_v, (253, 246, 220), onchange=v_changed) sb_v.set_shadow(color=(52, 54, 56), position=_locals.POSITION_NORTHWEST, offset=4) sb_v.set_controls(False) sb_v.set_position(scr_size[0] - thick_v, 0) sb_v.set_page_step(scr_size[1] - thick_h) clock = pygame.time.Clock() # ------------------------------------------------------------------------- # Main loop # ------------------------------------------------------------------------- while True: # Clock tick clock.tick(60) # Application events events = pygame.event.get() for event in events: if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_h: sb_h.set_value(100) if event.type == pygame.KEYDOWN and event.key == pygame.K_v: sb_v.set_value(200) sb_h.update([event]) sb_h.draw(screen) sb_v.update([event]) sb_v.draw(screen) trunc_world_orig = (sb_h.get_value(), sb_v.get_value()) trunc_world = (scr_size[0] - thick_v, scr_size[1] - thick_h) # noinspection PyTypeChecker screen.blit(world, (0, 0), (trunc_world_orig, trunc_world)) pygame.display.update() # At first loop returns if test: break
def main(test: bool = False) -> None: """ Main program. :param test: Indicate function is being tested :return: None """ # ------------------------------------------------------------------------- # Globals # ------------------------------------------------------------------------- global clock global main_menu global surface # ------------------------------------------------------------------------- # Create window # ------------------------------------------------------------------------- surface = create_example_window('Example - Game Selector', WINDOW_SIZE) clock = pygame.time.Clock() # ------------------------------------------------------------------------- # Create menus: Play Menu # ------------------------------------------------------------------------- play_menu = pygame_menu.Menu(height=WINDOW_SIZE[1] * 0.7, title='Play Menu', width=WINDOW_SIZE[0] * 0.75) submenu_theme = pygame_menu.themes.THEME_DEFAULT.copy() submenu_theme.widget_font_size = 15 play_submenu = pygame_menu.Menu(height=WINDOW_SIZE[1] * 0.5, theme=submenu_theme, title='Submenu', width=WINDOW_SIZE[0] * 0.7) for i in range(30): play_submenu.add.button('Back {0}'.format(i), pygame_menu.events.BACK) play_submenu.add.button('Return to main menu', pygame_menu.events.RESET) play_menu.add.button( 'Start', # When pressing return -> play(DIFFICULTY[0], font) play_function, DIFFICULTY, pygame.font.Font(pygame_menu.font.FONT_FRANCHISE, 30)) play_menu.add.selector('Select difficulty ', [('1 - Easy', 'EASY'), ('2 - Medium', 'MEDIUM'), ('3 - Hard', 'HARD')], onchange=change_difficulty, selector_id='select_difficulty') play_menu.add.button('Another menu', play_submenu) play_menu.add.button('Return to main menu', pygame_menu.events.BACK) # ------------------------------------------------------------------------- # Create menus:About # ------------------------------------------------------------------------- about_theme = pygame_menu.themes.THEME_DEFAULT.copy() about_theme.widget_margin = (0, 0) about_menu = pygame_menu.Menu(height=WINDOW_SIZE[1] * 0.6, theme=about_theme, title='About', width=WINDOW_SIZE[0] * 0.6) for m in ABOUT: about_menu.add.label(m, align=pygame_menu.locals.ALIGN_LEFT, font_size=20) about_menu.add.vertical_margin(30) about_menu.add.button('Return to menu', pygame_menu.events.BACK) # ------------------------------------------------------------------------- # Create menus: Main # ------------------------------------------------------------------------- main_theme = pygame_menu.themes.THEME_DEFAULT.copy() main_menu = pygame_menu.Menu(height=WINDOW_SIZE[1] * 0.6, theme=main_theme, title='Main Menu', width=WINDOW_SIZE[0] * 0.6) main_menu.add.button('Play', play_menu) main_menu.add.button('About', about_menu) main_menu.add.button('Quit', pygame_menu.events.EXIT) # ------------------------------------------------------------------------- # Main loop # ------------------------------------------------------------------------- while True: # Tick clock.tick(FPS) # Paint background main_background() # Application events events = pygame.event.get() for event in events: if event.type == pygame.QUIT: exit() # Main menu if main_menu.is_enabled(): main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS) # Flip surface pygame.display.flip() # At first loop returns if test: break
def main(test: bool = False) -> None: """ Main program. :param test: Indicate function is being tested :return: None """ # ------------------------------------------------------------------------- # Globals # ------------------------------------------------------------------------- global main_menu global sound global surface # ------------------------------------------------------------------------- # Create window # ------------------------------------------------------------------------- surface = create_example_window('Example - Multi Input', WINDOW_SIZE) clock = pygame.time.Clock() # ------------------------------------------------------------------------- # Set sounds # ------------------------------------------------------------------------- sound = pygame_menu.sound.Sound() # Load example sounds sound.load_example_sounds() # Disable a sound sound.set_sound(pygame_menu.sound.SOUND_TYPE_ERROR, None) # ------------------------------------------------------------------------- # Create menus: Settings # ------------------------------------------------------------------------- settings_menu_theme = pygame_menu.themes.THEME_ORANGE.copy() settings_menu_theme.title_offset = (5, -2) settings_menu_theme.widget_alignment = pygame_menu.locals.ALIGN_LEFT settings_menu_theme.widget_font = pygame_menu.font.FONT_OPEN_SANS_LIGHT settings_menu_theme.widget_font_size = 20 settings_menu = pygame_menu.Menu( height=WINDOW_SIZE[1] * 0.85, theme=settings_menu_theme, title='Settings', width=WINDOW_SIZE[0] * 0.9 ) # Add text inputs with different configurations settings_menu.add.text_input( 'First name: ', default='John', onreturn=check_name_test, textinput_id='first_name' ) settings_menu.add.text_input( 'Last name: ', default='Rambo', maxchar=10, textinput_id='last_name', input_underline='.' ) settings_menu.add.text_input( 'Your age: ', default=25, maxchar=3, maxwidth=3, textinput_id='age', input_type=pygame_menu.locals.INPUT_INT, cursor_selection_enable=False ) settings_menu.add.text_input( 'Some long text: ', maxwidth=19, textinput_id='long_text', input_underline='_' ) settings_menu.add.text_input( 'Password: '******'pass', input_underline='_' ) # Selectable items items = [('Easy', 'EASY'), ('Medium', 'MEDIUM'), ('Hard', 'HARD')] # Create selector with 3 difficulty options settings_menu.add.selector( 'Select difficulty:\t', items, selector_id='difficulty', default=1 ) settings_menu.add.selector( 'Select difficulty fancy', items, selector_id='difficulty_fancy', default=1, style='fancy' ) settings_menu.add.dropselect( 'Select difficulty (drop)', items, default=1, dropselect_id='difficulty_drop' ) settings_menu.add.dropselect_multiple( title='Pick 3 colors', items=[('Black', (0, 0, 0)), ('Blue', (0, 0, 255)), ('Cyan', (0, 255, 255)), ('Fuchsia', (255, 0, 255)), ('Green', (0, 255, 0)), ('Red', (255, 0, 0)), ('White', (255, 255, 255)), ('Yellow', (255, 255, 0))], dropselect_multiple_id='pickcolors', max_selected=3, open_middle=True, selection_box_height=6 # How many options show if opened ) # Create switch settings_menu.add.toggle_switch('First Switch', False, toggleswitch_id='first_switch') settings_menu.add.toggle_switch('Other Switch', True, toggleswitch_id='second_switch', state_text=('Apagado', 'Encencido')) def data_fun() -> None: """ Print data of the menu. :return: None """ print('Settings data:') data = settings_menu.get_input_data() for k in data.keys(): print(u'\t{0}\t=>\t{1}'.format(k, data[k])) settings_menu.add.clock(clock_format='%Y/%m/%d %H:%M', title_format='Clock: {0}') settings_menu.add.button('Store data', data_fun, button_id='store') # Call function settings_menu.add.button('Restore original values', settings_menu.reset_value) settings_menu.add.button('Return to main menu', pygame_menu.events.BACK, align=pygame_menu.locals.ALIGN_CENTER) # ------------------------------------------------------------------------- # Create menus: More settings # ------------------------------------------------------------------------- more_settings_menu = pygame_menu.Menu( height=WINDOW_SIZE[1] * 0.85, theme=settings_menu_theme, title='More Settings', width=WINDOW_SIZE[0] * 0.9 ) more_settings_menu.add.image( pygame_menu.baseimage.IMAGE_EXAMPLE_PYGAME_MENU, scale=(0.25, 0.25), align=pygame_menu.locals.ALIGN_CENTER ) more_settings_menu.add.color_input( 'Color 1 RGB: ', color_type='rgb' ) more_settings_menu.add.color_input( 'Color 2 RGB: ', color_type='rgb', default=(255, 0, 0), input_separator='-' ) def print_color(color: Tuple) -> None: """ Test onchange/onreturn. :param color: Color tuple :return: None """ print('Returned color: ', color) more_settings_menu.add.color_input( 'Color in Hex: ', color_type='hex', hex_format='lower', color_id='hex_color', onreturn=print_color ) more_settings_menu.add.vertical_margin(25) more_settings_menu.add.button( 'Return to main menu', pygame_menu.events.BACK, align=pygame_menu.locals.ALIGN_CENTER ) # ------------------------------------------------------------------------- # Create menus: Column buttons # ------------------------------------------------------------------------- button_column_menu_theme = pygame_menu.themes.THEME_ORANGE.copy() button_column_menu_theme.background_color = pygame_menu.BaseImage( image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_GRAY_LINES, drawing_mode=pygame_menu.baseimage.IMAGE_MODE_REPEAT_XY ) button_column_menu_theme.widget_font_size = 25 button_column_menu = pygame_menu.Menu( columns=2, height=WINDOW_SIZE[1] * 0.45, rows=3, theme=button_column_menu_theme, title='Textures+Columns', width=WINDOW_SIZE[0] * 0.9 ) for i in range(4): button_column_menu.add.button('Button {0}'.format(i), pygame_menu.events.BACK) button_column_menu.add.button( 'Return to main menu', pygame_menu.events.BACK, background_color=pygame_menu.BaseImage( image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_METAL ) ).background_inflate_to_selection_effect() # ------------------------------------------------------------------------- # Create menus: Main menu # ------------------------------------------------------------------------- main_menu_theme = pygame_menu.themes.THEME_ORANGE.copy() main_menu_theme.title_font = pygame_menu.font.FONT_COMIC_NEUE main_menu_theme.widget_font = pygame_menu.font.FONT_COMIC_NEUE main_menu_theme.widget_font_size = 30 main_menu = pygame_menu.Menu( height=WINDOW_SIZE[1] * 0.7, onclose=pygame_menu.events.EXIT, # User press ESC button theme=main_menu_theme, title='Main menu', width=WINDOW_SIZE[0] * 0.8 ) main_menu.add.button('Settings', settings_menu) main_menu.add.button('More Settings', more_settings_menu) main_menu.add.button('Menu in textures and columns', button_column_menu) main_menu.add.selector('Menu sounds ', [('Off', False), ('On', True)], onchange=update_menu_sound) main_menu.add.button('Quit', pygame_menu.events.EXIT) # ------------------------------------------------------------------------- # Main loop # ------------------------------------------------------------------------- while True: # Tick clock.tick(FPS) # Paint background main_background() # Main menu main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS) # Flip surface pygame.display.flip() # At first loop returns if test: break
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- """ __all__ = ['main'] import pygame_menu from pygame_menu.examples import create_example_window from random import randrange surface = create_example_window('Example - Dynamic Button Append', (600, 400)) menu = pygame_menu.Menu( height=300, theme=pygame_menu.themes.THEME_BLUE, title='Welcome', width=400 ) def add_dynamic_button() -> None: """ Append a button to the menu on demand. :return: None """ print('Adding a button dynamically')
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 # All the following kwargs are passed 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_shadow=True, widget_font_shadow_position=pygame_menu.locals.POSITION_SOUTHEAST, widget_font_size=45 ) 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
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- """ import pygame_menu from pygame_menu.examples import create_example_window from typing import Tuple, Any surface = create_example_window('Example - Simple', (600, 400)) def set_difficulty(selected: Tuple, value: Any) -> None: """ Set the difficulty of the game. :return: None """ print('Set difficulty to {} ({})'.format(selected[0], value)) def start_the_game() -> None: """ Function that starts a game. This is raised by the menu button, here menu can be disabled, etc.
def main(test: bool = False) -> None: """ Main program. :param test: Indicate function is being tested :return: None """ # ------------------------------------------------------------------------- # Globals # ------------------------------------------------------------------------- global main_menu # global sound global surface # ------------------------------------------------------------------------- # Create window # ------------------------------------------------------------------------- surface = create_example_window('Example - Image Background', WINDOW_SIZE) clock = pygame.time.Clock() all_sound = pygame_menu.sound.Sound() # engine.set_sound(pygame_menu.sound.SOUND_TYPE_CLICK_MOUSE, 'resources/sound/Designer_Stubble.ogg', volume=0.5) all_sound.set_sound(pygame_menu.sound.SOUND_TYPE_OPEN_MENU, 'resources/sound/Amazon.ogg', volume=0.5) # all_sound.play_open_menu() # engine.play_click_mouse() # ------------------------------------------------------------------------- # Create menus: Main menu # ------------------------------------------------------------------------- no_title_theme = pygame_menu.themes.THEME_ORANGE.copy() no_title_theme.background_color = (0, 0, 0, 50) # no_title_theme.title = False no_title_theme.widget_alignment = pygame_menu.locals.ALIGN_LEFT no_title_theme.title_bar_style = pygame_menu.widgets.MENUBAR_STYLE_SIMPLE no_title_theme.widget_padding = 5 no_title_theme_join_game = pygame_menu.themes.THEME_ORANGE.copy() no_title_theme_join_game.background_color = (0, 0, 0, 50) # no_title_theme.title = False no_title_theme_join_game.widget_alignment = pygame_menu.locals.ALIGN_CENTER no_title_theme_join_game.title_bar_style = pygame_menu.widgets.MENUBAR_STYLE_SIMPLE no_title_theme_join_game.widget_padding = 5 main_menu = pygame_menu.Menu( '', WINDOW_SIZE[0] * 0.8, WINDOW_SIZE[1] * 0.7, center_content=False, onclose=pygame_menu.events.EXIT, # User press ESC button theme=no_title_theme, position=[30, 80], ) join_game_menu = pygame_menu.Menu( '', WINDOW_SIZE[0] * 0.8, WINDOW_SIZE[1] * 0.7, center_content=False, onclose=pygame_menu.events.EXIT, # User press ESC button theme=no_title_theme_join_game, position=[30, 80], ) main_menu.add.vertical_margin(10) server_ip = main_menu.add.text_input( 'Server ip address: ', default='0.0.0.0', onreturn=None, textinput_id='server_ip', ) server_port = main_menu.add.text_input( 'Server port#: ', default='1111', onreturn=None, textinput_id='server_port' ) main_menu.add.text_input( 'Create a new game with name: ', default="Amy's game", onreturn=None, textinput_id='new_game' ) main_menu.add.button('Join an existing game', join_game_menu) join_game_menu.add.button("Amy's Game") join_game_menu.add.button("John's Game") join_game_menu.add.button("Dora's Game") main_menu.add.button("Start the game", lambda: print(f"server address: {server_ip.get_value()}:{server_port.get_value()}")) main_menu.add.button('Quit', pygame_menu.events.EXIT) main_menu.set_sound(all_sound, recursive=True) # Apply on menu and all sub-menus # ------------------------------------------------------------------------- # Main loop # ------------------------------------------------------------------------- while True: # Tick clock.tick(FPS) # events = pygame.event.get() # for event in events: # if event.type == pygame.MOUSEBUTTONDOWN: # pass # # if main_menu.is_enabled(): # main_background() # main_menu.update(events) # main_menu.draw(surface) # Main menu main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS) # Flip surface pygame.display.flip() # At first loop returns if test: break