Pygame и разработка игр

Thanks

A very special thanks to the people who have volunteered commits to pygame since the last release. In alphabetical order…

(@alphaCTzo7G) | Amos Bastian (@amosbastian) | Andrey Lopukhov (@andreyx86) | Augusto Noronha (@augusto2112) | Bernardo Sulzbach (@bernardosulzbach) | (@Bottersnike) | Cai Q.T. (@CAIQT) | (@Cerealdragon) | Charles (@charlesej) | (@ChrisWeissNike) | (@cmtrapp02) | Daniel Molina (@daniel-molina) | David Caughell (@DavidCaughell) | David Lönnhager (@dlon) | (@dr0id) | burmer (@dtschirmer) | (@e1000) | xFly_Dragon (@husano896) | (@IchMageBaume) | René Dudfield (@illume) | (@LambdaGoblin) | Lenard Lindstrom (@llindstrom) | François Magimel (@Linkid) | (@LiquidFenrir) | Mark Hurley (@markph0204) | Marius Gedminas (@mgedmin) | (@metulburr) | Michael Farrell (@micolous) | Dominik George (@Natureshadow) | Nik (@nikolas) | Nunu-Willump (@Nunu-Willump) | (@pleboulanger) | Rebecca Chen (@rchen152) | (@robertpfeiffer) | Sett (@sw00) |

Quite a few new people have helped out with this release

An equally special thanks to everyone else who has contributed in
other ways. Thanks to claudeb, imallet, and deshipu for moderating the
discord chat to keep it friendly. Thanks to the twitter folk, and the
stackoverflow Q&A people. Thanks to everyone who puts their game up
on the pygame website for others to look at. Thanks to people making
tutorials and sharing articles & books they’ve written. Thanks to
the r/pygame mods and community. Thanks to pyladies groups for running
fun sessions, and for making things better. Thanks to the teachers
providing feedback, and for doing something fun with their students.
Thanks to Debian, Raspberrypi, Arch, Fedora, and all the other community groups.

класс Window

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

Класс Window имеет несколько методов, которые ваши программы могут переопределять для обеспечения функциональности программы. Вот некоторые из наиболее часто используемых:

on_draw: весь код для рисования экрана идет сюда.
Обновление: весь код для перемещения ваших предметов и выполнения игровой логики находится здесь. Это называется около 60 раз в секунду.
on_key_press: обрабатывать события при нажатии клавиши, например, давать игроку скорость.
on_key_release: обрабатывает при отпускании ключа, здесь вы можете остановить движение игрока.
on_mouse_motion: вызывается каждый раз, когда движется мышь.
on_mouse_press: вызывается при нажатии кнопки мыши.
set_viewport: эта функция используется в играх с прокруткой, когда ваш мир намного больше, чем то, что можно увидеть на одном экране. Вызов set_viewport позволяет программисту установить, какая часть этого мира видна в данный момент.

Цвет¶

Цвета в библиотеке pygame представлены в соответствии с моделью RGB:
https://ru.wikipedia.org/wiki/RGB

Значение для цвета можно задать тройкой чисел, каждое из которых лежит
в диапазоне от 0 до 255. Первое значение в последовательности определяет,
какое количество красного содержится в данном оттенке, второе — зеленого,
третье — голубого. Чем меньше значение числа, тем темнее будет оттенок.
Например, красный цвет можно представить как (255, 0, 0), белый как (255, 255, 255),
а черный как (0, 0, 0).

Помимо этого, в модуле из библиотеки pygame содержится словарь THECOLORS,
ключами которого являются названия различных цветовых оттенков. Подключить его можно с помощью команды:

from pygame.color import THECOLORS

Закрасим основной экран c помощью метода :

More details.

Vector: Explain slices and swizzling Update surface documentation Make mask offset boundary checking consistent Update midi documentation Fix drawing 1 pixel wide off-surface ellipses Use SDL_RWops instead of pg_FopenUTF8. Fix LayeredDirty’s inconsistent use of its source rect Workaround for locale errors with PyPy Update dependencies for manylinux builds. Upload .whl binaries to a github draft release when creating tag. Update scrap documentation Fix zero-sized mask segfaults Fix the SystemError when no type specific clipboard content exists. Update scrap tests Update freetype tests Improved mask tests Add sprite tests bugfix for dirty sprite when using a source rect Add missing Vector2.magnitude() Fix mask index out of bounds segmentation fault Mask constructor ‘fill’ argument Use version directives consistently in documentation and update style Event functions: pump parameter and keyword arguments Add customized repr()/str() output for Mask objects Fix aaline()/aalines() not drawing on a surface’s border Keep surface alpha value for copied surfaces with SRCALPHA flag Load images on multiple threads properly Fix overlap_mask() making incorrect mask Added get_init() to all modules with an init() function Allow camera module to be used on Windows API version macros Use pre styles in docs Converting between ANSI notes and MIDI notes or frequencies Compile for PyPy 3 and PyPy fixes Chimp tutorial: reindent and clean some code Chimp tutorial: fix reST syntax Handle Unicode objects and paths properly Fix failing tests test_aapolygon and test_pie Fix freetype rotation rendering aaline cleanup draw.aaline: blend correctly Fixed FreeType memory leaks Fix surface.blits() bugs

Начало работы¶

Начнем знакомство с библиотекой непосредственно с разбора примера простого приложения:

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((1200, 800))

while True
    for event in pygame.event.get():
        if event.type == pygame.QUIT
            pygame.quit()
            sys.exit()

В первую очередь импортируем модуль pygame в наш файл с исходным кодом:

import pygame

Затем вызываем функцию для подготовки модулей pygame к работе:

pygame.init()

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

screen = pygame.display.set_mode((1200, 800))

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

while True
    for event in pygame.event.get():
        if event.type == pygame.QUIT
            pygame.quit()
            sys.exit()

Игры сверху вниз

Для простых игр сверху вниз аркадной программе нужен список стен, через которые игрок (или что-либо еще) не может пройти. Я обычно называю это wall_list. Затем физический движок создается в коде установки класса Window с помощью:

Player_sprite получает вектор движения с двумя атрибутами: change_x и change_y. Простым примером этого может быть перемещение игрока с помощью клавиатуры. Например, это может быть в настраиваемом дочернем элементе класса Window:

Хотя этот код устанавливает скорость игрока, он не перемещает игрока. В методе обновления класса Window при вызове Physics_engine.update () игрок будет перемещаться, но не через стены.

Полный пример см. В разделе sprite_move_walls.py.

Рисование геометрических фигур¶

Разместим в окне нашего приложения прямоугольник. Прямоугольные объекты
представлены типом :

Rect(left, top, width, height)
Rect((left, top), (width, height))

Для создания объекта этого типа нам необходимо указать координаты левого верхнего
угла прямоугольника и длины его сторон:

r = Rect(, , 100, 200)

Обратите внимание, что начало координат (0, 0) находится в левом верхнем углу окна. В библиотеке pygame функции отображения геометрических фигур находятся
в модуле

Нарисуем прямоугольник c помощью функции :

В библиотеке pygame функции отображения геометрических фигур находятся
в модуле . Нарисуем прямоугольник c помощью функции :

rect(Surface, color, Rect, width=) -> Rect

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

Рассмотрим готовый пример:

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((1000, 800))
r = pygame.Rect(50, 50, 100, 200)
pygame.draw.rect(screen, (255, , ), r, )

while True
    for event in pygame.event.get():
        if event.type == pygame.QUIT
            pygame.quit()
            sys.exit()
    pygame.display.flip()

Прочие функции для рисования графических фигур¶

(Surface, color, start_pos, end_pos, width=1)

Нарисовать линию на поверхности , цветом ,
с началом в точке , концом в точке end_pos и толщиной линии width.

(Surface, color, closed, pointlist, width=1)

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

(Surface, color, pos, radius, width=0)

Нарисовать окружность на поверхности Surface, цветом ,
с центром в точке и радиусом . Если толщина линии равна нулю,
окружность закрашивается.

(Surface, color, Rect, width=0)

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

‍ stuntcat early release. What’s next?

‍ stuntcat is our open source mini-game we worked on in order to drive pygame 2 development forward. We wanted to make a real mini-game and try to release it for sale on as many platforms as possible. So that other people can look at the source code and distribute their game on more platforms too.

We only had 4 days… but during that time more than 14 people got involved. We learnt a lot during this. The compilation instructions for pygame 2 were improved so that more people could build development versions. We automated the installer generation for Windows, Mac, and pypi on github (so other projects can copy this base-code and do it too). Gif animation saving was started (because when you release your game you want a gif right?). Missing features and areas where documentation could be improved were identified (animated sprites, and scenes anyone?). Fixes to pymunk (a great 2D physics engine) were made so distributing physics games to end users is now easier. There’s also an example of using the tile map loader (PyTMX) with the physics engine. More than a month after the game jam finished we are working on issues discovered during the making of ‍ stuntcat.

We want to make distributing pygame apps easier for people. You made your game, now you want to share it with your friends or even sell it right? The first place we made a release was on itch.io, a platform for selling games and apps. There we uploaded the Mac, Windows, and source for people to download with a pay-what-you-feel option.

Next step is to release the game on Steam (another popular games platform). For the next step we need to raise $100 for the Steam App fee. We also have to make the game better! It’s already a pretty fun mini game, but requires more mini games and more polish. We also need to make pygame 2 pre-release binaries so that we can actually publish on Steam.

‍ stuntcat on a unicycle, Shark with a lazer on it… and more. Have fun. Download stuntcat here, and if you can afford some small money… pay-what-you-feel to support pygame 2 development. We need to raise at least $100 to move onto the next step.

Thanks to the makers of stuntcat: bitcraft, blubberquark, Bottersnake, claudeb, illume, Kuba | ThePolish, TJWhale, hfoxp, xeno, M, CaptHurls, dlon, dirk0, viblo, and kleines filmröllchen.

day 0: $0 of $100 raised for Steam app fee.day 1: $5 of $100day 2: $57 of $100day 3: $100 of $113.20day 14: $107 of $113.20day 20: $127 of $113.20If you ever wanted to support pygame development financially and you can afford it, this is how you can by purchasing stuntcat on itch.io for $2 or what ever you feel.
update: we raised enough to make a steam release. Thanks to everyone who chipped in!

January 07, 2019

Текст и шрифты¶

При работе с текстом мы будем использовать шрифты — группы символов объединенных
по стилистическому или иному признаку. Шрифты в библиотеке pygame представлены типом

Чтобы создать объект на основе имеющегося в системе шрифта вызовем следующую функцию:

SysFont(name, size, bold=False, italic=False)

С помощью параметра передаем в функцию имя шрифта, параметр
— размер шрифта в пунктах. Параметры и отвечают за начертание шрифта.

Список имеющихся в системе шрифтов можно получить с помощью функции :

pygame.font.get_fonts() -> list of strings

Далее, с помощью метода нашего объекта типа получаем изображение
с текстом, которое передаем на вход методу для отрисовке на нашем основном экране:

screen = pygame.display.set_mode(size)
screen.fill(THECOLORS'white'])
font = pygame.font.SysFont('couriernew', 40)
text = font.render(str('HELLO'), True, THECOLORS'green'])
screen.blit(text, (50, 50))

Alakajam, PyWeek, and Ludum Dare game jams.

Over the next weeks we have plenty of game jams that people from the pygame communities take part in.

Alakajam is first starting on September 20th. «Alakajam! is a young community gathering game development enthusiasts from all backgrounds. We host a series of informal events, that give you a chance to both make games and get people to play them. Alakajam! competitions, taking place over a week-end, three times a year. Start/end times are suited to European timezones.»

Then the must-use-python PyWeek challenge «Invites entrants to write a game in one week from scratch either as an individual or in a team. Is intended to be challenging and fun. Will hopefully increase the public body of python game tools, code and expertise. Will let a lot of people actually finish a game, and may inspire new projects (with ready made teams!).» PyWeek runs from Sept. 22, 2019 to Sept. 29, 2019, and theme voting is already on.

Finally, Ludum Dare is an event where you create a game from scratch in a weekend based on a theme. Saturday October 5th to Tuesday October 8th, 2019. Starts at 12:00 AM CEST *. Ludumdare is the oldest online game jam, and has the largest number of participants. There is a Jam (72h, less restrictive rules), and a compo (48h more rules). The Jam now lets people submit paper board games, and even things like crafts that aren’t games at all!

Want to join in as part of a team? The pygame community game (stuntcat) is also taking part, by creating a new mini game for some of these game jams. Drop into the discord chat #communitygame channel and say hi ( https://discord.gg/r8yreB6.

Also, how about inviting women and non-binary people to make the game with you?

September 20, 2019

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

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