Pygame как сделать окно во весь экран

Обновлено: 28.03.2024

Python на практике: используйте pygame для создания начального игрового интерфейса (1)

После изучения Python в течение определенного периода времени ему все еще нужны некоторые практические ссылки для глубокого понимания. В конце концов, я новичок, который только начинает. Позвольте мне начать с нескольких простых игровых проектов, чтобы немного подбодрить себя. Хахаха, давайте не будем говорить об этом, служить.

  • Создайте окно Python с синим фоном
    Сначала используйте pycharm для создания файла проекта. Метод именования лучше всего соотносить с проектом, который вы делаете, как известно из названия.
    Сначала создайте пустое окно pygame и установите его цвет фона (цвет фона можно настроить, а цвет RGB получается через Baidu)

Метод pygame.event.get () используется для обнаружения пользовательских событий и определения операций, выполняемых пользователем.
Метод screen.fill () заполняет экран цветом фона.
Код содержит следующие процессы:

  1. Импорт модуля (модули, которые нам нужно использовать в настройках игры ниже, вот два, модуль pygame содержит функции, необходимые для разработки игры, а модуль sys используется для выхода из игры)
  2. Инициализировать игру и создать экранные объекты (установить свойства экрана)
  3. Откройте игровой цикл (обнаруживайте действия пользователя, обновляйте экран)



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

  • Поместите изображение в центр экрана и установите такой же цвет фона
    Добавьте изображение на экран и создайте класс корабля для управления настройками изображения, см. код.
    ship.py

Примечание. Определите метод __init __ (). (Содержит два формальных параметра: self, screen. Метод __init __ () принимает значения этих формальных параметров и сохраняет их в атрибутах экземпляра, созданных в соответствии с этим классом), __ - два символа подчеркивания, и только один вводится изначально. Давно искал ошибку.


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

Изображение центрируется, а цвет фона не регулируется. При выборе изображения лучше, если фон будет прозрачным. Формат изображения должен быть растровым (т. е. суффикс .Bmp). Конечно, можно также добиться перемещения картинок вверх, вниз, влево и вправо. Я не буду писать их здесь по очереди. Я расскажу об этом в обновленных блогах. На самом деле, в этих блогах нет технический уровень, просто примечание и добавление некоторого понимания., это удобно для использования в будущем, и, кстати, может углубить впечатление.
Один Леле не так хорош, как остальные: писать - это музыка, комментировать - это музыка, видеть - это музыка, музыка - это самое важное.

Setting the display mode in pygame creates a visible image surface on the monitor. This surface can either cover the full screen, or be windowed on platforms that support a window manager. The display surface is nothing more than a standard pygame surface object. There are special functions needed in the pygame.display pygame module to control the display window and screen module to keep the image surface contents updated on the monitor.

Setting the display mode in pygame is an easier task than with most graphic libraries. The advantage is if your display mode is not available, pygame will emulate the display mode that you asked for. Pygame will select a display resolution and color depth that best matches the settings you have requested, then allow you to access the display with the format you have requested. In reality, since the pygame.display pygame module to control the display window and screen module is a binding around the SDL library, SDL is really doing all this work.

There are advantages and disadvantages to setting the display mode in this manner. The advantage is that if your game requires a specific display mode, your game will run on platforms that do not support your requirements. It also makes life easier when you're getting something started, it is always easy to go back later and make the mode selection a little more particular. The disadvantage is that what you request is not always what you will get. There is also a performance penalty when the display mode must be emulated. This tutorial will help you understand the different methods for querying the platforms display capabilities, and setting the display mode for your game.

Setting Basics¶

The first thing to learn about is how to actually set the current display mode. The display mode may be set at any time after the pygame.display pygame module to control the display window and screen module has been initialized. If you have previously set the display mode, setting it again will change the current mode. Setting the display mode is handled with the function pygame.display.set_mode((width, height), flags, depth) Initialize a window or screen for display . The only required argument in this function is a sequence containing the width and height of the new display mode. The depth flag is the requested bits per pixel for the surface. If the given depth is 8, pygame will create a color-mapped surface. When given a higher bit depth, pygame will use a packed color mode. Much more information about depths and color modes can be found in the documentation for the display and surface modules. The default value for depth is 0. When given an argument of 0, pygame will select the best bit depth to use, usually the same as the system's current bit depth. The flags argument lets you control extra features for the display mode. Again, more information about this is found in the pygame reference documents.

How to Decide¶

So how do you select a display mode that is going to work best with your graphic resources and the platform your game is running on? There are several methods for gathering information about the display device. All of these methods must be called after the display module has been initialized, but you likely want to call them before setting the display mode. First, pygame.display.Info() Create a video display information object will return a special object type of VidInfo, which can tell you a lot about the graphics driver capabilities. The function pygame.display.list_modes(depth, flags) Get list of available fullscreen modes can be used to find the supported graphic modes by the system. pygame.display.mode_ok((width, height), flags, depth) Pick the best color depth for a display mode takes the same arguments as set_mode() , but returns the closest matching bit depth to the one you request. Lastly, pygame.display.get_driver() Get the name of the pygame display backend will return the name of the graphics driver selected by pygame.

Just remember the golden rule. Pygame will work with pretty much any display mode you request. Some display modes will need to be emulated, which will slow your game down, since pygame will need to convert every update you make to the "real" display mode. The best bet is to always let pygame choose the best bit depth, and convert all your graphic resources to that format when they are loaded. You let pygame choose it's bit depth by calling set_mode() with no depth argument or a depth of 0, or you can call mode_ok() to find a closest matching bit depth to what you need.

When your display mode is windowed, you usually must match the same bit depth as the desktop. When you are fullscreen, some platforms can switch to any bit depth that best suits your needs. You can find the depth of the current desktop if you get a VidInfo object before ever setting your display mode.

After setting the display mode, you can find out information about it's settings by getting a VidInfo object, or by calling any of the Surface.get* methods on the display surface.

Functions¶

These are the routines you can use to determine the most appropriate display mode. You can find more information about these functions in the display module documentation.

This function takes the exact same arguments as pygame.display.set_mode(). It returns the best available bit depth for the mode you have described. If this returns zero, then the desired display mode is not available without emulation.

Returns a list of supported display modes with the requested depth and flags. An empty list is returned when there are no modes. The flags argument defaults to FULLSCREEN . If you specify your own flags without FULLSCREEN , you will likely get a return value of -1. This means that any display size is fine, since the display will be windowed. Note that the listed modes are sorted largest to smallest.

This function returns an object with many members describing the display device. Printing the VidInfo object will quickly show you all the members and values for this object.

You can test all these flags as simply members of the VidInfo object.

Examples¶

Here are some examples of different methods to init the graphics display. They should help you get an idea of how to go about setting your display mode.

This module offers control over the pygame display. Pygame has a single display Surface that is either contained in a window or runs full screen. Once you create the display you treat it as a regular Surface. Changes are not immediately visible onscreen; you must choose one of the two flipping functions to update the actual display.

The origin of the display, where x = 0 and y = 0, is the top left of the screen. Both axes increase positively towards the bottom right of the screen.

The pygame display can actually be initialized in one of several modes. By default, the display is a basic software driven framebuffer. You can request special modules like automatic scaling or OpenGL support. These are controlled by flags passed to pygame.display.set_mode() .

Pygame can only have a single display active at any time. Creating a new one with pygame.display.set_mode() will close the previous display. To detect the number and size of attached screens, you can use pygame.display.get_desktop_sizes and then select appropriate window size and display index to pass to pygame.display.set_mode() .

For backward compatibility pygame.display allows precise control over the pixel format or display resolutions. This used to be necessary with old grahics cards and CRT screens, but is usually not needed any more. Use the functions pygame.display.mode_ok() , pygame.display.list_modes() , and pygame.display.Info() to query detailed information about the display.

Once the display Surface is created, the functions from this module affect the single existing display. The Surface becomes invalid if the module is uninitialized. If a new display mode is set, the existing Surface will automatically switch to operate on the new display.

When the display mode is set, several events are placed on the pygame event queue. pygame.QUIT is sent when the user has requested the program to shut down. The window will receive pygame.ACTIVEEVENT events as the display gains and loses input focus. If the display is set with the pygame.RESIZABLE flag, pygame.VIDEORESIZE events will be sent when the user adjusts the window dimensions. Hardware displays that draw direct to the screen will get pygame.VIDEOEXPOSE events when portions of the window must be redrawn.

A new windowevent API was introduced in pygame 2.0.1. Check event module docs for more information on that

Some display environments have an option for automatically stretching all windows. When this option is enabled, this automatic stretching distorts the appearance of the pygame window. In the pygame examples directory, there is example code (prevent_display_stretching.py) which shows how to disable this automatic stretching of the pygame display on Microsoft Windows (Vista or newer required).

Initializes the pygame display module. The display module cannot do anything until it is initialized. This is usually handled for you automatically when you call the higher level pygame.init() .

Pygame will select from one of several internal display backends when it is initialized. The display mode will be chosen depending on the platform and permissions of current user. Before the display module is initialized the environment variable SDL_VIDEODRIVER can be set to control which backend is used. The systems with multiple choices are listed here.

On some platforms it is possible to embed the pygame display into an already existing window. To do this, the environment variable SDL_WINDOWID must be set to a string containing the window id or handle. The environment variable is checked when the pygame display is initialized. Be aware that there can be many strange side effects when running in an embedded display.

It is harmless to call this more than once, repeated calls have no effect.

This will shut down the entire display module. This means any active displays will be closed. This will also be handled automatically when the program exits.

It is harmless to call this more than once, repeated calls have no effect.

This function will create a display Surface. The arguments passed in are requests for a display type. The actual created display will be the best possible match supported by the system.

Note that calling this function implicitly initializes pygame.display , if it was not initialized before.

The size argument is a pair of numbers representing the width and height. The flags argument is a collection of additional options. The depth argument represents the number of bits to use for color.

The Surface that gets returned can be drawn to like a regular Surface but changes will eventually be seen on the monitor.

If no size is passed or is set to (0, 0) and pygame uses SDL version 1.2.10 or above, the created Surface will have the same size as the current screen resolution. If only the width or height are set to 0 , the Surface will have the same width or height as the screen resolution. Using a SDL version prior to 1.2.10 will raise an exception.

It is usually best to not pass the depth argument. It will default to the best and fastest color depth for the system. If your game requires a specific color format you can control the depth with this argument. Pygame will emulate an unavailable color depth which can be slow.

When requesting fullscreen display modes, sometimes an exact match for the requested size cannot be made. In these situations pygame will select the closest compatible match. The returned surface will still always match the requested size.

On high resolution displays(4k, 1080p) and tiny graphics games (640x480) show up very small so that they are unplayable. SCALED scales up the window for you. The game thinks it's a 640x480 window, but really it can be bigger. Mouse events are scaled for you, so your game doesn't need to do it. Note that SCALED is considered an experimental API and may change in future releases.

The flags argument controls which type of display you want. There are several to choose from, and you can even combine multiple types using the bitwise or operator, (the pipe "|" character). Here are the display flags you will want to choose from:

New in pygame 2.0.0: SCALED , SHOWN and HIDDEN

By setting the vsync parameter to 1 , it is possible to get a display with vertical sync, but you are not guaranteed to get one. The request only works at all for calls to set_mode() with the pygame.OPENGL or pygame.SCALED flags set, and is still not guaranteed even with one of those set. What you get depends on the hardware and driver configuration of the system pygame is running on. Here is an example usage of a call to set_mode() that may give you a display with vsync:

Vsync behaviour is considered experimental, and may change in future releases.

New in pygame 2.0.0: vsync

The display index 0 means the default display is used. If no display index argument is provided, the default display can be overridden with an environment variable.

Changed in pygame 1.9.5: display argument added

Return a reference to the currently set display Surface. If no display mode has been set this will return None.

This will update the contents of the entire display. If your display mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF on pygame 1, this will wait for a vertical retrace and swap the surfaces.

When using an pygame.OPENGL display mode this will perform a gl buffer swap.

This function is like an optimized version of pygame.display.flip() for software displays. It allows only a portion of the screen to updated, instead of the entire area. If no argument is passed it updates the entire Surface area like pygame.display.flip() .

You can pass the function a single rectangle, or a sequence of rectangles. It is more efficient to pass many rectangles at once than to call update multiple times with single or a partial list of rectangles. If passing a sequence of rectangles it is safe to include None values in the list, which will be skipped.

This call cannot be used on pygame.OPENGL displays and will generate an exception.

Pygame chooses one of many available display backends when it is initialized. This returns the internal name used for the display backend. This can be used to provide limited information about what display capabilities might be accelerated. See the SDL_VIDEODRIVER flags in pygame.display.set_mode() to see some of the common options.

Creates a simple object containing several attributes to describe the current graphics environment. If this is called before pygame.display.set_mode() some platforms can provide information about the default display mode. This can also be called after setting the display mode to verify specific display options were satisfied. The VidInfo object has several attributes:

Creates a dictionary filled with string keys. The strings and values are arbitrarily created by the system. Some systems may have no information and an empty dictionary will be returned. Most platforms will return a "window" key with the value set to the system id for the current display.

New in pygame 1.7.1.

This function returns the sizes of the currrently configured virtual desktops as a list of (x, y) tuples of integers.

The length of the list is not the same as the number of attached monitors, as a desktop can be mirrored across multiple monitors. The desktop sizes do not indicate the maximum monitor resolutions supported by the hardware, but the desktop size configured in the operating system.

In order to fit windows into the desktop as it is currently configured, and to respect the resolution configured by the operating system in fullscreen mode, this function should be used to replace many use cases of pygame.display.list_modes() whenever applicable.

New in pygame 2.0.0.

This function returns a list of possible sizes for a specified color depth. The return value will be an empty list if no display modes are available with the given arguments. A return value of -1 means that any requested size should work (this is likely the case for windowed modes). Mode sizes are sorted from biggest to smallest.

If depth is 0 , the current/best color depth for the display is used. The flags defaults to pygame.FULLSCREEN , but you may need to add additional flags for specific fullscreen modes.

The display index 0 means the default display is used.

Since pygame 2.0, pygame.display.get_desktop_sizes() has taken over some use cases from pygame.display.list_modes() :

To find a suitable size for non-fullscreen windows, it is preferable to use pygame.display.get_desktop_sizes() to get the size of the current desktop, and to then choose a smaller window size. This way, the window is guaranteed to fit, even when the monitor is configured to a lower resolution than the maximum supported by the hardware.

To avoid changing the physical monitor resolution, it is also preferable to use pygame.display.get_desktop_sizes() to determine the fullscreen resolution. Developers are strongly advised to default to the current physical monitor resolution unless the user explicitly requests a different one (e.g. in an options menu or configuration file).

Changed in pygame 1.9.5: display argument added

This function uses the same arguments as pygame.display.set_mode() . It is used to determine if a requested display mode is available. It will return 0 if the display mode cannot be set. Otherwise it will return a pixel depth that best matches the display asked for.

Usually the depth argument is not passed, but some platforms can support multiple display depths. If passed it will hint to which depth is a better match.

The function will return 0 if the passed display flags cannot be set.

The display index 0 means the default display is used.

Changed in pygame 1.9.5: display argument added

After calling pygame.display.set_mode() with the pygame.OPENGL flag, it is a good idea to check the value of any requested OpenGL attributes. See pygame.display.gl_set_attribute() for a list of valid flags.

When calling pygame.display.set_mode() with the pygame.OPENGL flag, Pygame automatically handles setting the OpenGL attributes like color and double-buffering. OpenGL offers several other attributes you may want control over. Pass one of these attributes as the flag, and its appropriate value. This must be called before pygame.display.set_mode() .

Many settings are the requested minimum. Creating a window with an OpenGL context will fail if OpenGL cannot provide the requested attribute, but it may for example give you a stencil buffer even if you request none, or it may give you a larger one than requested.

Whether to enable multisampling anti-aliasing. Defaults to 0 (disabled).

Set GL_MULTISAMPLESAMPLES to a value above 0 to control the amount of anti-aliasing. A typical value is 2 or 3.

Minimum bit size of the stencil buffer. Defaults to 0.

Minimum bit size of the depth buffer. Defaults to 16.

1 enables stereo 3D. Defaults to 0.

Minimum bit size of the frame buffer. Defaults to 0.

New in pygame 2.0.0: Additional attributes:

Sets the OpenGL profile to one of these values:

Set to 1 to require hardware acceleration, or 0 to force software render. By default, both are allowed.

Returns True when the display Surface is considered actively renderable on the screen and may be visible to the user. This is the default state immediately after pygame.display.set_mode() . This method may return True even if the application is fully hidden behind another application window.

This will return False if the display Surface has been iconified or minimized (either via pygame.display.iconify() or via an OS specific method such as the minimize-icon available on most desktops).

The method can also return False for other reasons without the application being explicitly iconified or minimized by the user. A notable example being if the user has multiple virtual desktops and the display Surface is not on the active virtual desktop.

This function returning True is unrelated to whether the application has input focus. Please see pygame.key.get_focused() and pygame.mouse.get_focused() for APIs related to input focus.

Request the window for the display surface be iconified or hidden. Not all systems and displays support an iconified display. The function will return True if successful.

When the display is iconified pygame.display.get_active() will return False . The event queue should receive an ACTIVEEVENT event when the window has been iconified. Additionally, the event queue also recieves a WINDOWEVENT_MINIMIZED event when the window has been iconified on pygame 2.

Switches the display window between windowed and fullscreen modes. Display driver support is not great when using pygame 1, but with pygame 2 it is the most reliable method to switch to and from fullscreen.

Supported display drivers in pygame 1:

  • x11 (Linux/Unix)

  • wayland (Linux/Unix)

Supported display drivers in pygame 2:

  • windows (Windows)

  • x11 (Linux/Unix)

  • wayland (Linux/Unix)

  • cocoa (OSX/Mac)

Set the red, green, and blue gamma values on the display hardware. If the green and blue arguments are not passed, they will both be the same as red. Not all systems and hardware support gamma ramps, if the function succeeds it will return True .

A gamma value of 1.0 creates a linear color table. Lower values will darken the display and higher values will brighten.

Set the red, green, and blue gamma ramps with an explicit lookup table. Each argument should be sequence of 256 integers. The integers should range between 0 and 0xffff . Not all systems and hardware support gamma ramps, if the function succeeds it will return True .

Sets the runtime icon the system will use to represent the display window. All windows default to a simple pygame logo for the window icon.

Note that calling this function implicitly initializes pygame.display , if it was not initialized before.

You can pass any surface, but most systems want a smaller image around 32x32. The image can have colorkey transparency which will be passed to the system.

Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set.

If the display has a window title, this function will change the name on the window. Some systems support an alternate shorter title to be used for minimized displays.

Returns the title and icontitle for the display Surface. These will often be the same value.

Returns the number of available displays. This is always 1 if pygame.get_sdl_version() get the version number of SDL returns a major version number below 2.

New in pygame 1.9.5.

Returns the size of the window initialized with pygame.display.set_mode() Initialize a window or screen for display . This may differ from the size of the display surface if SCALED is used.

New in pygame 2.0.0.

Return whether screensaver is allowed to run whilst the app is running. Default is False . By default pygame does not allow the screensaver during game play.

Some platforms do not have a screensaver or support disabling the screensaver. Please see pygame.display.set_allow_screensaver() Set whether the screensaver may run for caveats with screensaver support.

New in pygame 2.0.0.

Change whether screensavers should be allowed whilst the app is running. The default is False. By default pygame does not allow the screensaver during game play.

If the screensaver has been disallowed due to this function, it will automatically be allowed to run when pygame.quit() uninitialize all pygame modules is called.

It is possible to influence the default value via the environment variable SDL_HINT_VIDEO_ALLOW_SCREENSAVER , which can be set to either 0 (disable) or 1 (enable).

Disabling screensaver is subject to platform support. When platform support is absent, this function will silently appear to work even though the screensaver state is unchanged. The lack of feedback is due to SDL not providing any supported method for determining whether it supports changing the screensaver state. SDL_HINT_VIDEO_ALLOW_SCREENSAVER is available in SDL 2.0.2 or later. SDL1.2 does not implement this.

Я только начинал новую игру с pygame на python 3.6.5 на ПК с Windows 10, когда у меня был действительно сумасшедший глюк, который я не мог решить. Это мой код, я потом объясню свою проблему.

Поэтому, когда я запускал этот код, pygame работал как обычно, создавая полноэкранное черное окно. Затем появилась мышь, и когда я нажал клавишу A. Когда я это сделал, я не смог выйти из окна pygame. Я перешел в диспетчер задач Control + Alt + Delete, и он показал мне рабочий стол. Графика прошла немного менее реалистично, и экран увеличился. Единственный способ выбраться – это пойти на диспетчер задач и завершить задачу python. Затем он вернулся к нормальному рабочему столу. Я посмотрел на другой проект: pygame fullscreen mode exit Я попробовал это решение, но оно не сработало. Я продолжал пытаться найти решение для странного рабочего стола, но не мог. Буду признателен за помощь!

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

Код по-прежнему работает в бесконечном цикле, поэтому вы должны завершить его в диспетчере задач.

Нажатие кнопки A ничего не делает, потому что ваш код не проверяет правильность:

Ваш рабочий стол странный, потому что вы сделали pygame, чтобы изменить свою видеокарту на разрешение 800×600, что не является вашим родным разрешением для рабочего стола.

Все правильно, и код ведет себя так же, как вы его написали.

Я запускаю код с изменением выше, и он правильно вышел, когда я нажал A

Я обнаружил много проблем с вашим кодом. Вот несколько решений:

Первая проблема заключается в том, что вы используете event.type где вам нужно использовать event.key .

Второй event.type необходимо изменить на event.key .

Вторая проблема заключается в том, что K_a должен иметь префикс с pygame. , как это:

Ваш рабочий стол выглядел все нечетким, потому что приложение PyGame работало с разрешением 800x600 , что меньше, чем у большинства мониторов. Окно PyGame было открыто, пока вы его не закрыли. Пока окно открыто, пользовательское разрешение остается.

Модуль, используемый для управления окном и отображением экрана в Pygame.

Примечание. Чтобы адаптироваться к контексту, в этом документе отображение иногда переводится как «отображение», а иногда как «интерфейс отображения».

функция

  • pygame.display.init () - Инициализирует модуль дисплея
  • pygame.display.quit () - Завершить отображение модуля
  • pygame.display.get_init () - Если дисплейный модуль был инициализирован, вернуть True
  • pygame.display.set_mode () - Инициализирует окно или экран для отображения
  • pygame.display.get_surface () - Получить текущий отображаемый объект Surface
  • pygame.display.flip () - Обновляет весь объект Surface для отображения на экране
  • pygame.display.update () - Обновляет часть отображения интерфейса программного обеспечения
  • pygame.display.get_driver () - Получить имя серверной части дисплея Pygame
  • pygame.display.Info () - Создать информационный объект об интерфейсе дисплея
  • pygame.display.get_wm_info () - Получить информацию о текущей оконной системе
  • pygame.display.list_modes () - получает разрешение, которое можно использовать в полноэкранном режиме
  • pygame.display.mode_ok () - Выбрать наиболее подходящую глубину цвета для режима отображения
  • pygame.display.gl_get_attribute () - Получить значение атрибута текущего интерфейса отображения OpenGL
  • pygame.display.gl_set_attribute () - Установить значение атрибута OpenGL для текущего режима отображения
  • pygame.display.get_active () - возвращает True, когда текущий интерфейс дисплея отображается на экране
  • pygame.display.iconify () - Свернуть отображаемый объект Surface
  • pygame.display.toggle_fullscreen () - переключение между полноэкранным и оконным режимами
  • pygame.display.set_gamma () - Изменяет гамма-рампу, отображаемую оборудованием
  • pygame.display.set_gamma_ramp () - настраивает и изменяет гамма-рампу, отображаемую оборудованием
  • pygame.display.set_icon () - Изменить значок окна отображения
  • pygame.display.set_caption() — Set the current window caption
  • pygame.display.get_caption() — Get the current window caption
  • pygame.display.set_palette() — Set the display color palette for indexed displays

Этот модуль предоставляет различные функции для управления интерфейсом отображения Pygame (display). Pygame's Surface Объект может отображаться в виде окна или в полноэкранном режиме. Когда вы создаете и отображаете обычный Surface После объекта изменения на объекте не будут немедленно отражены на видимом экране.Вы должны выбрать функцию переворота, чтобы отобразить измененный экран.

Отображаемое начало координат - это положение (x = 0, y = 0) и верхнего левого угла экрана. Ось координат увеличивается в правом нижнем углу.

На самом деле отображение Pygame можно инициализировать несколькими способами. По умолчанию дисплей действует как программный буфер кадра. Кроме того, вы можете использовать специальные модули, поддерживающие аппаратное ускорение и OpenGL. Они контролируются передачей параметра flags в pygame.display.set_mode ().

Pygame допускает только один интерфейс отображения в любое время. Новый интерфейс отображения, созданный с помощью pygame.display.set_mode (), автоматически заменит старый. Если вам нужно точно контролировать формат пикселей или разрешение экрана, используйте pygame.display.mode_ok (), pygame.display.list_modes () и pygame.display.Info () для запроса информации об интерфейсе дисплея.

однажды Surface Создается интерфейс отображения объекта, и функция этого модуля влияет только на текущий интерфейс отображения. Если модуль не инициализирован, Surface Объект также станет «нелегальным». Если установлен новый режим отображения, текущий Surface Объект автоматически переключится на новый интерфейс отображения.

Когда установлен новый режим отображения, несколько связанных событий будут помещены в очередь событий Pygame. Когда используется для закрытия программы, будет отправлено событие pygame.QUIT; когда интерфейс дисплея получает и теряет фокус, окно получит событие pygame.ACTIVEEVENT; если интерфейс дисплея установлен с флагом pygame.RESIZABLE, тогда, когда пользователь регулирует размер окна , Будет отправлено событие Pygame.VIDEORESIZE; аппаратный дисплей означает, что при получении события pygame.VIDEOEXPOSE часть окна, которую необходимо перерисовать, отображается непосредственно на экране.

В некоторых средах отображения есть возможность автоматически растягивать все окна. Когда эта опция активирована, автоматическое растягивание искажает внешний вид окна Pygame. В каталоге примеров Pygame есть демонстрационный код (prevent_display_stretching.py), который показывает, как отключить свойство автоматического растягивания отображения Pygame в системах Microsoft (системы выше Vista).

Описание функции

pygame.display.init()

Инициализируйте модуль дисплея.

Инициализировать модуль отображения Pygame. До инициализации модуль дисплея ничего не может делать. Но когда вы вызываете pygame.init () более высокого уровня, изменение автоматически вызывает pygame.display.init () для инициализации.

После инициализации Pygame автоматически выберет один из нескольких внутренних модулей отображения. Режим отображения определяется платформой и текущими полномочиями пользователя. Перед инициализацией модуля отображения можно использовать переменную среды SDL_VIDEODRIVER, чтобы установить, какой серверный модуль отображения будет использоваться. К системам с несколькими серверными модулями отображения относятся следующие:

Windows : windib, directx
Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib

На некоторых платформах вы можете встроить отображение Pygame в существующее окно. Если вы это сделаете, переменная среды SDL_WINDOWID должна быть установлена ​​в строку, содержащую идентификатор окна или дескриптор. Когда отображение Pygame инициализировано, переменные среды будут проверены. Обратите внимание, что встраивание отображения в работающее окно может иметь много странных побочных эффектов.

Нет проблем с вызовом этой функции несколько раз, но эффекта нет.

pygame.display.quit()

Закройте модуль дисплея.

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

Нет проблем с вызовом этой функции несколько раз, но эффекта нет.

pygame.display.get_init()

Если модуль дисплея был инициализирован, верните True.

Если модуль дисплея был инициализирован, верните True.

pygame.display.set_mode()

Инициализируйте окно или экран для отображения.

set_mode(resolution=(0,0), flags=0, depth=0) -> Surface

Эта функция создаст Surface Интерфейс отображения объекта. Переданные параметры используются для определения типа отображения. Окончательный созданный интерфейс дисплея будет максимально соответствовать текущей операционной системе.

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

возвращение Surface Объект может быть как обычный Surface Объект нарисован так, но происходящие изменения со временем отобразятся на экране.

Если параметр разрешения не передан или используется настройка по умолчанию (0, 0), а Pygame использует SDL1.2.10 или новее, созданный объект Surface будет иметь то же разрешение, что и текущий пользователь экрана. Если только одна из ширины или высоты установлена ​​на 0, то объект Surface заменит ее шириной или высотой разрешения экрана. Если версия SDL ниже 1.2.10, будет создано исключение.

Вообще говоря, лучше всего не передавать параметр глубины. Потому что по умолчанию Pygame выберет лучшую и самую быструю глубину цвета в соответствии с текущей операционной системой. Если вашей игре действительно нужен особый цветовой формат, вы можете сделать это, управляя параметром глубины. Pygame потребуется больше времени для имитации нестандартной глубины цвета.

При использовании полноэкранного режима отображения иногда не удается полностью подобрать необходимое разрешение. В этом случае Pygame автоматически выберет наиболее подходящее разрешение для использования, и вернет Surface Объект останется в соответствии с требуемым разрешением.

Параметр flags определяет желаемый тип отображения. Вам предлагается несколько вариантов. Вы можете использовать несколько типов одновременно с помощью битовых операций (оператор вертикальной черты "|"). Если вы передадите параметр 0 или без флагов, по умолчанию будет использоваться окно программного драйвера. Вот несколько вариантов, предоставляемых параметром flags:

Параметры

смысл

pygame.display.get_surface()

Получить текущий отображаемый Поверхностный объект.

Вернуть текущий отображаемый Surface Объект. Если режим отображения не установлен, возвращается значение None.

pygame.display.flip()

Обновите все для отображения Поверхность объекта на экране.

Эта функция обновит содержимое всего интерфейса дисплея. Если в вашем режиме отображения используются флаги pygame.HWSURFACE (аппаратное ускорение) и pygame.DOUBLEBUF (двойная буферизация), вы дождетесь вертикальной развертки и переключите интерфейс дисплея. Если вы используете другой тип режима отображения, он просто обновит содержимое всего интерфейса дисплея.

При использовании режима отображения pygame.OPENGL (с использованием рендеринга OPENGL) будет создана область переключения буфера gl.

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

pygame.display.update()

Обновите часть отображения интерфейса программного обеспечения.

Эту функцию можно рассматривать как оптимизированную версию функции pygame.display.flip (), отображаемой в программном интерфейсе. Это позволяет обновлять часть экрана без необходимости обновления полностью. Если параметры не переданы, функция обновляет весь интерфейс так же, как pygame.display.flip ().

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

Эта функция не может быть вызвана в режиме отображения pygame.OPENGL, в противном случае будет выдано исключение.

pygame.display.get_driver()

Получите имя серверной части дисплея Pygame.

При инициализации Pygame выберет один из нескольких доступных бэкэндов отображения. Эта функция возвращает имя, используемое внутренне серверной частью дисплея. Может использоваться для предоставления некоторой информации об ускорении работы дисплея. Вы можете обратиться к переменной среды SDL_VIDEODRIVER в pygame.display.set_mode ().

pygame.display.Info()

Создайте информационные объекты об интерфейсе дисплея.

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

Возвращенный объект VideoInfo содержит следующие свойства:

Атрибуты

смысл

pygame.display.get_wm_info()

Получить информацию о текущей оконной системе.

Создайте словарь, заполненный данными операционной системы. Некоторые операционные системы могут не заполнять информацию и возвращать пустой словарь. Большинство платформ вернут ключ «окна», соответствующее значение - это системный идентификатор текущего интерфейса дисплея.

Pygame 1.7.1 добавлен недавно.

pygame.display.list_modes()

Получите разрешение, которое можно использовать в полноэкранном режиме.

list_modes(depth=0, flags=pygame.FULLSCREEN) -> list

Эта функция возвращает список, содержащий все разрешения, поддерживаемые указанной глубиной цвета. Если режим отображения не является полноэкранным, возвращается пустой список. Если он возвращает -1, поддерживается любое разрешение (аналогично оконному режиму). Возвращенный список отсортирован от наибольшего к наименьшему.

Если глубина цвета равна 0, SDL выберет текущую / наиболее подходящую глубину цвета для отображения. Значение по умолчанию для параметра flags - pygame.FULLSCREEN, но вам может потребоваться добавить дополнительные флаги полноэкранного режима.

pygame.display.mode_ok()

Выберите наиболее подходящую глубину цвета для режима отображения.

mode_ok(size, flags=0, depth=0) -> depth

Эта функция использует те же параметры, что и функция pygame.display.set_mode (). Обычно используется, чтобы определить, доступен ли режим отображения. Если режим отображения не может быть установлен, возвращается 0. В нормальных условиях возвращается требуемая для дисплея глубина пикселей.

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

Наиболее полезными параметрами флагов являются pygame.HWSURFACE, pygame.DOUBLEBUF и pygame.FULLSCREEN. Если эти флаги не поддерживаются, функция возвращает 0.

pygame.display.gl_get_attribute()

Получить значение атрибута текущего интерфейса дисплея OpenGL.

После вызова функции pygame.display.set_mode () с установленным флагом pygame.OPENGL рекомендуется проверять значения атрибутов OpenGL. Обратитесь к pygame.display.gl_set_attribute () для получения списка допустимых флагов.

pygame.display.gl_set_attribute()

Установите значение атрибута OpenGL для текущего режима отображения.

gl_set_attribute(flag, value) -> None

При вызове функции pygame.display.set_mode () с установленным флагом pygame.OPENGL Pygame автоматически устанавливает некоторые значения атрибутов OpenGL, такие как цвет и двойной буфер. OpenGL фактически предоставляет вам некоторые другие значения атрибутов. Передайте имя атрибута в параметре флага и установите его значение в параметре значения. Эта функция должна быть установлена ​​перед pygame.display.set_mode ().

Эти флаги OPENGL:

GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO

pygame.display.get_active()

Верните True, когда на экране отображается текущий интерфейс дисплея.

После вызова функции pygame.display.set_mode () на экране отобразится объект Surface. Большинство окон поддерживают скрытие, если отображается Surface Объект скрыт и свернут, тогда функция вернет False.

pygame.display.iconify()

Сверните отображаемое Surface Объект.

Сверните или скройте отображаемый объект Surface. Не все операционные системы поддерживают интерфейс минимизированного дисплея. Если функция успешно вызвана, она возвращает True.

Когда интерфейс дисплея свернут, pygame.display.get_active () возвращает False. Очередь событий получит событие ACTIVEEVENT.

pygame.display.toggle_fullscreen()

Переключение между полноэкранным и оконным режимами.

Переключение между полноэкранным и оконным режимами. Эта функция работает только с драйвером дисплея unix x11. В большинстве случаев рекомендуется вызвать pygame.display.set_mode (), чтобы создать новый режим отображения для переключения.

pygame.display.set_gamma()

Измените гамма-рампу, отображаемую оборудованием.

set_gamma(red, green=None, blue=None) -> bool

Установите значения гаммы красного, зеленого и синего, отображаемые драйвером оборудования. Если зеленый и синий параметры не переданы, они будут равны значению красного. Не все операционные системы и оборудование поддерживают гамма-изменение. Если функция изменена успешно, она возвращает True.

Значение гаммы 1.0 создает линейную таблицу цветов, более низкое значение затемняет экран, а более высокое значение делает экран переменной.

pygame.display.set_gamma_ramp()

Настроить и изменить гамма-рампу, отображаемую оборудованием

set_gamma_ramp(red, green, blue) -> bool

Используйте настраиваемую таблицу, чтобы установить красную, зеленую и синюю гамма-кривые, отображаемые драйвером оборудования. Каждый параметр должен быть списком 256-битных целых чисел. Каждое целое число должно быть от 0 до 0xffff. Не все операционные системы и оборудование поддерживают гамма-изменение. Если функция изменена успешно, она возвращает True.

pygame.display.set_icon()

Измените значок окна дисплея.

Установите значок при открытии окна дисплея. Все операционные системы по умолчанию используют простой ЛОГОТИП Pygame в виде значка.

Вы можете пройти в любой Surface Объект используется как значок, но для большинства операционных систем требуется, чтобы размер значка был 32 * 32. Значок может установить прозрачность цвета.

Некоторые операционные системы не позволяют изменять значок окна на дисплее. Для этого типа операционной системы этой функции необходимо создать и установить значок перед вызовом pygame.display.set_mode ().

pygame.display.set_caption()

Установите строку заголовка текущего окна.

set_caption(title, icontitle=None) -> None

Если в окне дисплея есть строка заголовка, эта функция изменит текст строки заголовка окна. Некоторые операционные системы поддерживают переключение строки заголовка, когда окно свернуто, путем установки параметра icontitle.

pygame.display.get_caption()

Получить строку заголовка текущего окна.

get_caption() -> (title, icontitle)

Вернуть строку заголовка текущего окна и свернуть строку заголовка, обычно эти два значения совпадают.

pygame.display.set_palette()

Установите палитру интерфейса дисплея.

Интеллектуальная рекомендация

Android Gausso нечеткий реализация

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


Установите Spark 2.2.1 под облачным сервером Alibaba centos7.2

Выбор версии при установке Spark связан с версией hadoop. Нажмите, чтобы открыть ссылкуПосле ввода выберите подходящее изображение. При нормальных обстоятельствах можно использовать оба .

Заставьте FireFox fieldset имитировать IE в закругленных углах

Метка набора полей написана в Firefox, углы не закруглены, как в IE, что влияет на внешний вид. Мы можем установить стиль в fieldset: .

Установка MongoDB и базовый синтаксис

Метод вызова Notepad ++ и GVIM в Vivado

Метод вызова Notepad ++ и GVIM в Vivado Позвоните Notepad ++ Позвоните в метод GVIM, это не на этом, потому что в середине программных файлов есть пространство Правильный способ установки его на диск .

Читайте также: