Gui games in python

Documentation — Home Page¶

Pygame GUI is a module to help you make graphical user interfaces for games written in pygame. The module is firmly forward looking and is designed to work on Pygame 2 and Python 3.

Features¶

  • Theme-able UI elements/widgets — you can use JSON theme files to change the colours, fonts and other appearance related details of your UI without touching your code.
  • A subset of HTML is supported for drawing word-wrapped text. Have bold styled words in the middle of a paragraph of text! Stick a link in there! Go absolutely hog wild, within the bounds of the defined subset of HTML the module supports.
  • Buttons, text entry, scroll bars and drop down menus all supported, with more on the way.
  • A window stack that will let you keep a bunch of moveable windows of ‘stuff’ around and correctly sorted.
  • Support for localizing your GUI into different languages.
  • As closely respecting of the pygame way of doing things as possible.

Installation¶

Install the latest release from PyPi using pip with:

Or, you can build the latest version from GitHub here by downloading the source, navigating to the project’s directory (the one with setup.py in it) and then building it with:

python setup.py install pip install . -U 

Why is your package called pygame-gui on PyPI?¶

PyPI converts all non-letter characters in package names to dashes for web search optimisation reasons. I can assure you that the pygame-gui package on PyPI is this library pygame_gui. Conversely, Python does not allow dashes in package names. So it is not possible to standardise around either convention unless you forgo any kind of non-lowercase letter, pygamegui is already taken as a name on PyPI — so here we are.

Читайте также:  Php html исходный код

Please live with the inconsistency.

Source code on GitHub¶

Getting Started¶

Try our Quick Start Guide here if you are new to Pygame GUI. Check out the Theme Guide if you want to learn how to style your GUI.

Examples¶

If you want to see Pygame GUI in action have a rifle through the examples project over on GitHub to see some of the stuff the library can do in action.

Game projects using Pygame GUI¶

Table of contents¶

  • Quick Start Guide
  • Layout Guide
    • Horizontal & Vertical positioning
    • Layout Anchors
    • Invalid anchors
    • Anchor targets
    • Dynamically sized elements
    • UI Layers
    • Object IDs — in depth
    • Theme block categories
    • Theme Prototypes
    • Multiple Theme Files
    • Theme Options Per Element
    • Theme Options Per Window
    • Event list
    • Applying an effect
    • Applying an effect to a tagged chunk in a text box
    • Event when an effect is finished
    • Effect parameters
    • Fade In
    • Fade Out
    • Typing Appear
    • Bounce
    • Tilt
    • Expand & Contract
    • Underlying localization package
    • Basics of switching locale
    • Default supported languages
    • Providing custom translation files to the GUI
    • Providing custom fonts per locale
    • PyInstaller
    • Nuitka
    • Version 0.6.4
    • Version 0.6.3
    • Version 0.6.2
    • Version 0.6.1
    • Version 0.6.0 — The text update
    • Version 0.5.7 — Hiding and better pygame 2 support
    • Version 0.5.6 — Loading changes & minor optimisations
    • Version 0.5.5 — The Windows Update, Update
    • Version 0.5.1
    • Bug Fixes
    • Version 0.5.0 — The Windows Update
    • pygame_gui package

    Indices and tables¶

    © Copyright 2019, Dan Lawrence Revision 7f26d3b4 .

    Versions latest stable v_069 v_067 v_065 v_060 v_050 v_040 Downloads pdf On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

    Источник

    Gui games in python

    🐍 Самоучитель по Python для начинающих. Часть 21: Основы разработки игр на Pygame

    🐍 Самоучитель по Python для начинающих. Часть 21: Основы разработки игр на Pygame

    import pygame import random pygame.init() screen_width = 600 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Змейка") green = (0, 255, 0) red = (255, 0, 0) font = pygame.font.SysFont("Arial", 20) clock = pygame.time.Clock() # основные параметры игры cell_size = 20 snake_speed = 5 snake_length = 3 snake_body = [] for i in range(snake_length): snake_body.append(pygame.Rect((screen_width / 2) - (cell_size * i), screen_height / 2, cell_size, cell_size)) snake_direction = "right" new_direction = "right" apple_position = pygame.Rect(random.randint(0, screen_width - cell_size), random.randint(0, screen_height - cell_size), cell_size, cell_size) game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_direction != "down": new_direction = "up" elif event.key == pygame.K_DOWN and snake_direction != "up": new_direction = "down" elif event.key == pygame.K_LEFT and snake_direction != "right": new_direction = "left" elif event.key == pygame.K_RIGHT and snake_direction != "left": new_direction = "right" # новое направление движения snake_direction = new_direction # управление змейкой if snake_direction == "up": snake_body.insert(0, pygame.Rect(snake_body[0].left, snake_body[0].top - cell_size, cell_size, cell_size)) elif snake_direction == "down": snake_body.insert(0, pygame.Rect(snake_body[0].left, snake_body[0].top + cell_size, cell_size, cell_size)) elif snake_direction == "left": snake_body.insert(0, pygame.Rect(snake_body[0].left - cell_size, snake_body[0].top, cell_size, cell_size)) elif snake_direction == "right": snake_body.insert(0, pygame.Rect(snake_body[0].left + cell_size, snake_body[0].top, cell_size, cell_size)) # проверяем, съела ли змея яблоко if snake_body[0].colliderect(apple_position): apple_position = pygame.Rect(random.randint(0, screen_width - cell_size), random.randint(0, screen_height-cell_size), cell_size, cell_size) snake_length += 1 if len(snake_body) > snake_length: snake_body.pop() # проверка столкновения со стенами if snake_body[0].left < 0 or snake_body[0].right >screen_width or snake_body[0].top < 0 or snake_body[0].bottom >screen_height: game_over = True # проверка столкновения с собственным телом for i in range(1, len(snake_body)): if snake_body[0].colliderect(snake_body[i]): game_over = True screen.fill((0, 0, 0)) # рисуем змейку for i in range(len(snake_body)): if i == 0: pygame.draw.circle(screen, green, snake_body[i].center, cell_size / 2) else: pygame.draw.circle(screen, green, snake_body[i].center, cell_size / 2) pygame.draw.circle(screen, (0, 200, 0), snake_body[i].center, cell_size / 4) # рисуем яблоко pygame.draw.circle(screen, red, apple_position.center, cell_size / 2) # выводим количество яблок score_text = font.render(f"Съедено яблок: ", True, (255, 255, 255)) screen.blit(score_text, (10, 10)) pygame.display.update() clock.tick(snake_speed) pygame.quit() 

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

    Мы рассмотрели самые простые приемы разработки игр в Pygame – возможности этой библиотеки намного обширнее. К примеру, для быстрой разработки в Pygame используются спрайты – объекты для определения свойств и поведения игровых элементов. Встроенные классы Group , GroupSingle и RenderUpdates позволяют быстро, просто и эффективно группировать, обновлять и отрисовывать игровые элементы.

    В следующей главе будем изучать работу с SQL и базами данных .

    1. Особенности, сферы применения, установка, онлайн IDE
    2. Все, что нужно для изучения Python с нуля – книги, сайты, каналы и курсы
    3. Типы данных: преобразование и базовые операции
    4. Методы работы со строками
    5. Методы работы со списками и списковыми включениями
    6. Методы работы со словарями и генераторами словарей
    7. Методы работы с кортежами
    8. Методы работы со множествами
    9. Особенности цикла for
    10. Условный цикл while
    11. Функции с позиционными и именованными аргументами
    12. Анонимные функции
    13. Рекурсивные функции
    14. Функции высшего порядка, замыкания и декораторы
    15. Методы работы с файлами и файловой системой
    16. Регулярные выражения
    17. Основы скрапинга и парсинга
    18. Основы ООП: инкапсуляция и наследование
    19. Основы ООП: абстракция и полиморфизм
    20. Графический интерфейс на Tkinter
    21. Основы разработки игр на Pygame
    22. Основы работы с SQLite
    23. Основы веб-разработки на Flask
    24. Основы работы с NumPy

    Материалы по теме

    Источник

Оцените статью