Как сделать меню для игры на питоне
Перейти к содержимому

Как сделать меню для игры на питоне

Создание игр на Python 3 и Pygame: Часть 4

Gigi Sayfan

Gigi Sayfan Jan 18, 2018

Russian (Pусский) translation by Marat Amerov (you can also view the original English article)

Обзор

Это четвёртая из пяти частей туториала, посвящённого созданию игр с помощью Python 3 и Pygame. В третьей части мы углубились в сердце Breakout и узнали, как обрабатывать события, познакомились с основным классом Breakout и увидели, как перемещать разные игровые объекты.

В этой части мы узнаем, как распознавать коллизии и что случается, когда мяч ударяется об разные объекты: ракетку, кирпичи, стены, потолок и пол. Наконец, мы рассмотрим важную тему пользовательского интерфейса и в частности то, как создать меню из собственных кнопок.

Распознавание коллизий

В играх объекты сталкиваются друг с другом, и Breakout не является исключением. В основном с объектами сталкивается мяч. В методе handle_ball_collisions() есть встроенная функция под названием intersect() , которая используется для проверки того, ударился ли мяч об объект, и того, где он столкнулся с объектом.Она возвращает ‘left’, ‘right’, ‘top’, ‘bottom’ или None, если мяч не столкнулся с объектом.

Столкновение мяча с ракеткой

Когда мяч стукается об ракетку, он отскакивает. Если он ударяется о верхнюю часть ракетки, то отражается обратно вверх, но сохраняет тот же компонент горизонтальной скорости.

Но если он ударяется о боковую часть ракетки, то отскакивает в противоположную сторону (влево или вправо) и продолжает движение вниз, пока не столкнётся с полом. В коде используется функция intersect().

Столкновение с полом

Когда ракетка пропускает мяч на пути вниз (или мяч ударяется об ракетку сбоку), то мяч продолжает падать и затем ударяется об пол. В этот момент игрок теряет жизнь и мяч создаётся заново, чтобы игра могла продолжаться. Игра завершается, когда у игрока заканчиваются жизни.

Столкновение с потолком и стенами

Когда мяч ударяется об стены или потолок, он просто отскакивает от них.

Столкновение с кирпичами

Когда мяч ударяется об кирпич, это является основным событием игры Breakout — кирпич исчезает, игрок получает очко, мяч отражается назад и происходят ещё несколько событий (звуковой эффект, а иногда и спецэффект), которые я рассмотрю позже.

Чтобы определить, что мяч ударился об кирпич, код проверят, пересекается ли какой-нибудь из кирпичей с мячом:

Программирование игрового меню

В большинстве игр есть какой-нибудь UI. В Breakout есть простое меню с двумя кнопками, ‘PLAY’ и ‘QUIT’. Меню отображается в начале игры и пропадает, когда игрок нажимает на ‘PLAY’. Давайте посмотрим, как реализуются кнопки и меню, а также как они интегрируются в игру.

Создание кнопок

В Pygame нет встроенной библиотеки UI. Есть сторонние расширения, но для меню я решил создать свои кнопки. Кнопка — это игровой объект, имеющий три состояния: нормальное, выделенное и нажатое. Нормальное состояние — это когда мышь не находится над кнопкой, а выделенное состояние — когда мышь находится над кнопкой, но левая кнопка мыши ещё не нажата. Нажатое состояние — это когда мышь находится над кнопкой и игрок нажал на левую кнопку мыши.

Кнопка реализуется как прямоугольник с фоновым цветом и текст, отображаемый поверх него. Также кнопка получает функцию on_click (по умолчанию являющуюся пустой лямбда-функцией), которая вызывается при нажатии кнопки.

Кнопка обрабатывает собственные события мыши и изменяет своё внутреннее состояние на основании этих событий. Когда кнопка находится в нажатом состоянии и получает событие MOUSEBUTTONUP , это означает, что игрок нажал на кнопку, и вызывается функция on_click() .

Свойство back_color , используемое для отрисовки фонового прямоугольника, всегда возвращает цвет, соответствующий текущему состоянию кнопки, чтобы игроку было ясно, что кнопка активна:

Создание меню

Функция create_menu() создаёт меню с двумя кнопками с текстом ‘PLAY’ и ‘QUIT’. Она имеет две встроенные функции, on_play() и on_quit() , которые она передаёт соответствующей кнопке. Каждая кнопка добавляется в список objects (для отрисовки), а также в поле menu_buttons .

При нажатии кнопки PLAY вызывается функция on_play(), удаляющая кнопки из списка objects , чтобы они больше не отрисовывались. Кроме того, значения булевых полей, которые запускают начало игры — is_game_running и start_level — становятся равными True.

При нажатии кнопки QUIT is_game_running принимает значение False (фактически ставя игру на паузу), а game_over присваивается значение True, что приводит к срабатыванию последовательности завершения игры.

Отображение и сокрытие игрового меню

Отображение и сокрытие меню выполняются неявным образом. Когда кнопки находятся в списке objects , меню видимо; когда они удаляются, оно скрывается. Всё очень просто.

Можно создать встроенное меню с собственной поверхностью, которое рендерит свои подкомпоненты (кнопки и другие объекты), а затем просто добавлять/удалять эти компоненты меню, но для такого простого меню это не требуется.

Подводим итог

В этой части мы рассмотрели распознавание коллизий и то, что происходит, когда мяч сталкивается с разными объектами: ракеткой, кирпичами, стенами, полом и потолком. Также мы создали меню с собственными кнопками, которое можно скрывать и отображать по команде.

В последней части серии мы рассмотрим завершение игры, отслеживание очков и жизней, звуковые эффекты и музыку.

Затем мы разработаем сложную систему спецэффектов, добавляющих в игру немного специй. Наконец, мы обсудим дальнейшее развитие и возможные улучшения.

Creating menus

The pygame_menu.menu.Menu is the base class to draw the graphical items on the screen. It offers many parameters to let you adapt the behavior and the visual aspects of the menu.

The less trivial ones are explained here.

Widget position

By default, the widgets are centered horizontally by theme, included in a virtual rectangle positioned at 0 pixel below the title bar and 0 pixel from the left border ( widget_offset=(0, 0) ).

In the same way, an offset can be defined for the title using the parameter title_offset .

The content of the menu can be centered vertically after all widgets have been added by calling the method pygame_menu.menu.Menu.center_content() :

If the menu size is insufficient to show all of the widgets, horizontal and/or vertical scrollbar(s) will appear automatically.

Column and row

By default, the widgets are arranged in one unique column. But using the columns and rows parameters, it is possible to arrange them in a grid.

The defined grid of columns x rows cells will be completed with the widgets (in order of definition) column by column starting at the top-left corner of the menu.

Also the width of each column can be set using column_max_width and column_min_width Menu parameters.

On-close callback

A callback can be defined using the onclose parameter; it will be called when the menu (end sub-menu) is closing. Closing the menu is the same as disabling it, but with callback firing.

onclose parameter can take one of these three types of values:

  • None , the menu don’t disables if pygame_menu.menu.Menu.close() is called

  • A python callable object (a function, a method) that will be called without any arguments, or with the Menu instance.

  • A specific event of pygame_menu . The possible events are the following:

    Event

    Description

    pygame_menu.events.BACK

    Go back to the previous menu and disable the current

    pygame_menu.events.CLOSE

    Only disables the current menu

    pygame_menu.events.NONE

    The same as onclose=None

    pygame_menu.events.EXIT

    Exit the program (not only the menu)

    pygame_menu.events.RESET

    Go back to the first opened menu and disable the current

Display a menu

The First steps chapter shows the way to display the menu, this method lets pygame-menu managing the event loop by calling the pygame_menu.menu.Menu.mainloop() :

There is a second way that gives more flexibility to the application because the events loop remains managed outside of the menu. In this case the application is in charge to update and draw the menu when it is necessary.

Menu API

Menu can receive many callbacks; callbacks onclose and onreset are fired (if them are callable-type). They can only receive 1 argument maximum, if so, the Menu instance is provided

Menu cannot be copied or deep-copied.

title ( str ) – Title of the Menu

width ( Union [ int , float ]) – Width of the Menu in px

height ( Union [ int , float ]) – Height of the Menu in px

center_content ( bool ) – Auto centers the Menu on the vertical position after a widget is added/deleted

column_max_width ( Union [ int , float , Tuple [ Union [ int , float ], . ], List [ Union [ int , float ]], None ]) – List/Tuple representing the maximum width of each column in px, None equals no limit. For example column_max_width=500 (each column width can be 500px max), or column_max_width=(400,500) (first column 400px, second 500). If 0 uses the Menu width. This method does not resize the widgets, only determines the dynamic width of the column layout

column_min_width ( Union [ int , float , Tuple [ Union [ int , float ], . ], List [ Union [ int , float ]]]) – List/Tuple representing the minimum width of each column in px. For example column_min_width=500 (each column width is 500px min), or column_max_width=(400,500) (first column 400px, second 500). Negative values are not accepted

columns ( int ) – Number of columns

enabled ( bool ) – Menu is enabled. If False the Menu cannot be drawn or updated

joystick_enabled ( bool ) – Enable/disable joystick events on the Menu

keyboard_enabled ( bool ) – Enable/disable keyboard events on the Menu

menu_id ( str ) – ID of the Menu

mouse_enabled ( bool ) – Enable/disable mouse click inside the Menu

mouse_motion_selection ( bool ) – Select widgets using mouse motion. If True menu draws a focus on the selected widget

mouse_visible ( bool ) – Set mouse visible on Menu

onclose ( Union [ MenuAction , Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Event or function executed when closing the Menu. If not None the menu disables and executes the event or function it points to. If a function (callable) is provided it can be both non-argument or single argument (Menu instance)

onreset ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Function executed when resetting the Menu. The function must be non-argument or single argument (Menu instance)

overflow ( Union [ Tuple [ bool , bool ], List [ bool ], bool ]) – Enables overflow on x/y axes. If False then scrollbars will not work and the maximum width/height of the scrollarea is the same as the Menu container. Style: (overflow_x, overflow_y). If False or True the value will be set on both axis

position ( Union [ Tuple [ Union [ int , float ], Union [ int , float ]], List [ Union [ int , float ]], Tuple [ Union [ int , float ], Union [ int , float ], bool ]]) – Position on x-axis and y-axis. If the value is only 2 elements, the position is relative to the window width (thus, values must be 0-100%); else, the third element defines if the position is relative or not. If (x, y, False) the values of (x, y) are in px

rows ( Union [ int , Tuple [ int , . ], List [ int ], None ]) – Number of rows of each column, if there’s only 1 column None can be used for no-limit. Also, a tuple can be provided for defining different number of rows for each column, for example rows=10 (each column can have a maximum 10 widgets), or rows=[2, 3, 5] (first column has 2 widgets, second 3, and third 5)

screen_dimension ( Union [ Tuple [ int , int ], List [ int ], None ]) – List/Tuple representing the dimensions the Menu should reference for sizing/positioning (width, height), if None pygame is queried for the display mode. This value defines the window_size of the Menu

theme ( Theme ) – Menu theme

touchscreen ( bool ) – Enable/disable touch action inside the Menu. Only available on pygame 2

touchscreen_motion_selection ( bool ) – Select widgets using touchscreen motion. If True menu draws a focus on the selected widget

Centers the content of the Menu vertically. This action rewrites widget_offset .

If the height of the widgets is greater than the height of the Menu, the drawing region will cover all Menu inner surface.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Clears all widgets.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

reset ( bool ) – If True the menu full-resets

Closes the current Menu firing onclose callback. If callback=None this method does nothing.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().reset(. ) .

True if the Menu has executed the onclose callback

Check if user event collides the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

event ( Event ) – Pygame event

True if collide

Disables the Menu (doesn’t check events and draw on the surface).

This method does not fire onclose callback. Use Menu.close() instead.

draw ( surface , clear_surface = False ) [source] 

Draw the current Menu into the given surface.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().draw(. )

surface ( Surface ) – Pygame surface to draw the Menu

clear_surface ( bool ) – Clear surface using theme surface_clear_color

Self reference (current)

Enables Menu (can check events and draw).

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Forces current Menu surface cache to update after next drawing call.

This method only updates the surface cache, without forcing re-rendering of all Menu widgets.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

Forces current Menu surface update after next rendering call.

This method is expensive, as menu surface update forces re-rendering of all widgets (because them can change in size, position, etc…).

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

Reset the Menu back to the first opened Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Return the pygame Menu timer.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Pygame clock object

Get the current active Menu. If the user has not opened any submenu the pointer object must be the same as the base. If not, this will return the opened Menu pointer.

Menu object (current)

Return the Menu decorator API.

prev menu decorator may not draw because pygame_menu.widgets.MenuBar and pygame_menu._scrollarea.ScrollArea objects draw over it. If it’s desired to draw a decorator behind widgets, use the ScrollArea decorator, for example: menu.get_scrollarea().get_decorator() .

The menu drawing order is:

Menu background color/image

Menu prev decorator

Menu ScrollArea prev decorator

Menu ScrollArea widgets

Menu ScrollArea post decorator

Menu post decorator

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

get_height ( inner = False , widget = False ) [source] 

Get the Menu height.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

inner ( bool ) – If True returns the available height (menu height minus scroll and menubar)

widget ( bool ) – If True returns the total height used by the widgets

Get selected widget index from the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Selected widget index

get_input_data ( recursive = False ) [source] 

Return input data from a Menu. The results are given as a dict object. The keys are the ID of each element.

With recursive=True it collects also data inside the all sub-menus.

This is applied only to the base Menu (not the currently displayed), for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

recursive ( bool ) – Look in Menu and sub-menus

Return the update mode.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

Returns a string that represents the update status, see pygame_menu.events . Some also indicate which widget updated in the format EVENT_NAME#widget_id

Return menubar widget.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

get_mouseover_widget ( filter_appended = True ) [source] 

Return the mouseover widget on the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

filter_appended ( bool ) – If True return the widget only if it’s appended to the base Menu

Widget object, None if no widget is mouseover

Return the menu position (constructor + translation).

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Position on x-axis and y-axis (x,y) in px

Return the pygame.Rect object of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Return the Menu ScrollArea.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Return the selected widget on the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Widget object, None if no widget is selected

get_size ( inner = False , widget = False ) [source] 

Return the Menu size as a tuple of (width, height) in px.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

inner ( bool ) – If True returns the available (width, height) (menu height minus scroll and menubar)

widget ( bool ) – If True returns the total (width, height) used by the widgets

Tuple of (width, height) in px

Return the Menu sound engine.

get_submenus ( recursive = False ) [source] 

Return the Menu submenus as a tuple.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

recursive ( bool ) – If True return all submenus in a recursive fashion

Return the Menu theme.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Use with caution, changing the theme may affect other menus or widgets if not properly copied.

Return the title of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Get Menu translate on x-axis and y-axis (x, y) in px.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Translation on both axis

get_widget ( widget_id , recursive = False ) [source] 

Return a widget by a given ID from the Menu.

With recursive=True it looks for a widget in the Menu and all sub-menus.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

None is returned if no widget is found.

widget_id ( str ) – Widget ID

recursive ( bool ) – Look in Menu and submenus

Return the Menu widgets as a tuple.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

ids ( Union [ List [ str ], Tuple [ str , . ], None ]) – Widget id list. If None , return all the widgets, otherwise, return the widgets from that list

get_width ( inner = False , widget = False ) [source] 

Get the Menu width.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

inner ( bool ) – If True returns the available width (menu width minus scroll if visible)

widget ( bool ) – If True returns the total width used by the widgets

Return the window size as a tuple of (width, height).

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Window size in px

in_submenu ( menu , recursive = False ) [source] 

Return True if menu is a submenu of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

menu ( Menu ) – Menu to check

recursive ( bool ) – Check recursively

True if menu is in the submenus

Return True if the Menu is enabled.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Menu enabled status

Main loop of the current Menu. In this function, the Menu handle exceptions and draw. The Menu pauses the application and checks pygame events itself.

This method returns until the Menu is updated (a widget status has changed).

The execution of the mainloop is at the current Menu level.

The bgfun callable (if not None) can receive 1 argument maximum, if so, the Menu instance is provided:

Finally, mainloop can be disabled externally if menu.disable() is called.

clear_surface (bool) – If True surface is cleared using theme.surface_clear_color

disable_loop (bool) – If True the mainloop only runs once. Use for running draw and update in a single call

fps_limit (int) – Maximum FPS of the loop. Default equals to theme.fps . If 0 there’s no limit

wait_for_event (bool) – Holds the loop until an event is provided, useful to save CPU power

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().mainloop(. ) .

surface ( Surface ) – Pygame surface to draw the Menu

bgfun ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Background function called on each loop iteration before drawing the Menu

kwargs – Optional keyword arguments

Self reference (current)

move_widget_index ( widget , index = None , render = True , ** kwargs ) [source] 

Move a given widget to a certain index. index can be another widget, a numerical position, or None ; if None the widget is pushed to the last widget list position.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Optional [ Widget ]) – Widget to move. If None the widgets are flipped or reversed and returns None

index ( Union [ Widget , int , None ]) – Target index. It can be a widget, a numerical index, or None ; if None the widget is pushed to the last position

render ( bool ) – Force menu rendering after update

kwargs – Optional keyword arguments

The new indices of the widget and the previous index element

Remove the widget from the Menu. If widget not exists on Menu this method raises a ValueError exception.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Union [ Widget , str ]) – Widget object or Widget ID

Force the current Menu to render. Useful to force widget update.

This method should not be called if the Menu is being drawn as this method is called by pygame_menu.menu.Menu.draw()

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().render(. )

Self reference (current)

Go back in Menu history a certain number of times from the current Menu. This method operates through the current Menu pointer.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().reset(. ) .

total ( int ) – How many menus to go back

Self reference (current)

reset_value ( recursive = False ) [source] 

Reset all widget values to default.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

recursive ( bool ) – Set value recursively

resize ( width , height , screen_dimension = None , position = None ) [source] 

Resize the menu to another width/height

width ( Union [ int , float ]) – Menu width (px)

height ( Union [ int , float ]) – Menu height (px)

screen_dimension ( Union [ Tuple [ int , int ], List [ int ], None ]) – List/Tuple representing the dimensions the Menu should reference for sizing/positioning (width, height), if None pygame is queried for the display mode. This value defines the window_size of the Menu

position ( Union [ Tuple [ Union [ int , float ], Union [ int , float ]], List [ Union [ int , float ]], Tuple [ Union [ int , float ], Union [ int , float ], bool ], None ]) – Position on x-axis and y-axis. If the value is only 2 elements, the position is relative to the window width (thus, values must be 0-100%); else, the third element defines if the position is relative or not. If (x, y, False) the values of (x, y) are in px. If None use the default from the menu constructor

scroll_to_widget ( widget , scroll_parent = True ) [source] 

Scroll the Menu to the given widget.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Optional [ Widget ]) – Widget to request scroll. If None scrolls to the selected widget

scroll_parent ( bool ) – If True parent scroll also scrolls to rect

Select a widget from the Menu. If None unselect the current one.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

widget ( Union [ Widget , str , None ]) – Widget to be selected or Widget ID. If None unselect the current

set_absolute_position ( position_x , position_y ) [source] 

Set the absolute Menu position.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

position_x ( Union [ int , float ]) – Left position of the window

position_y ( Union [ int , float ]) – Top position of the window

Set onbeforeopen callback. Callback is executed before opening the Menu, it receives the current Menu and the next Menu:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onbeforeopen ( Optional [ Callable [[ Menu , Menu ], Any ]]) – Onbeforeopen callback, it can be a function or None

Set onclose callback. Callback can only receive 1 argument maximum (if not None ), if so, the Menu instance is provided:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onclose ( Union [ MenuAction , Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Onclose callback, it can be a function, a pygame-menu event, or None

Set onmouseleave callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onmouseleave ( Union [ Callable [[ Menu , Event ], Any ], Callable [[], Any ], None ]) – Callback executed if user leaves the Menu with the mouse; it can be a function or None

Set onmouseover callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onmouseover ( Union [ Callable [[ Menu , Event ], Any ], Callable [[], Any ], None ]) – Callback executed if user enters the Menu with the mouse; it can be a function or None

Set onreset callback. Callback can only receive 1 argument maximum (if not None ), if so, the Menu instance is provided:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onreset ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Onreset callback, it can be a function or None

Set onupdate callback. Callback is executed before updating the Menu, it receives the event list and the Menu reference; also, onupdate can receive zero arguments:

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

onupdate ( Union [ Callable [[ List [ Event ], Menu ], Any ], Callable [[], Any ], None ]) – Onupdate callback, it can be a function or None

Set onwidgetchange callback. This method is executed if any appended widget changes its value. The callback function receives the following arguments:

onwidgetchange ( Optional [ Callable [[ Menu , Widget ], Any ]]) – Callback executed if an appended widget changes its value

Set onwindowmouseleave callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onwindowmouseleave ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Callback executed if user leaves the window with the mouse; it can be a function or None

Set onwindowmouseover callback. This method is executed in pygame_menu.menu.Menu.update() method. The callback function receives the following arguments:

onwindowmouseover ( Union [ Callable [[ Menu ], Any ], Callable [[], Any ], None ]) – Callback executed if user enters the window with the mouse; it can be a function or None

set_relative_position ( position_x , position_y ) [source] 

Set the Menu position relative to the window.

Menu left position (x) must be between 0 and 100 , if 0 the margin is at the left of the window, if 100 the Menu is at the right of the window.

Menu top position (y) must be between 0 and 100 , if 0 the margin is at the top of the window, if 100 the margin is at the bottom of the window.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

position_x ( Union [ int , float ]) – Left position of the window

position_y ( Union [ int , float ]) – Top position of the window

set_sound ( sound , recursive = False ) [source] 

Add a sound engine to the Menu. If recursive=True , the sound is applied to all submenus.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

sound ( Optional [ Sound ]) – Sound object

recursive ( bool ) – Set the sound engine to all submenus

Set the title of the Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

title ( Any ) – New menu title

offset ( Union [ Tuple [ Union [ int , float ], Union [ int , float ]], List [ Union [ int , float ]], None ]) – If None uses theme offset, else it defines the title offset on x-axis and y-axis (x, y)

Switch between enable/disable Menu.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Translate to (+x, +y) according to the default position.

To revert changes, only set to (0, 0) .

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

x ( Union [ int , float ]) – +X in px

y ( Union [ int , float ]) – +Y in px

Unselects the current widget.

This is applied only to the base Menu (not the currently displayed, stored in _current pointer); for such behaviour apply to pygame_menu.menu.Menu.get_current() object.

Update the status of the Menu using external events. The update event is applied only on the current Menu.

This method should not be used along pygame_menu.menu.Menu.get_current() , for example, menu.get_current().update(. ) .

events ( Union [ List [ Event ], Tuple [ Event ]]) – List of pygame events

True if the menu updated (or a widget)

© Copyright Copyright 2017 Pablo Pizarro R. @ppizarror. Revision 52a823b9 .

Creating start Menu in Pygame

Pygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn’t have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game. The only way to make levels or different menus in pygame is by using functions.

Using Functions As Menus

Functions in Pygame are a way to contain different menus or levels by defining an event type in each function, then calling the functions from their respective container function.

For example, the game function will be called if the player hits the play button on the start menu. So, the start menu function becomes container functions for the game function. The important thing to note is that the start function can’t be called directly from game function. If the game contains different unlockable levels, then the previous level becomes the container function for the next level.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *