Архив метки: pygame

Pygame — рисование линий, кругов и прямоугольников

>>> import pygame
pygame 2.0.1 (SDL 2.0.14, Python 3.8.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> from pygame.locals import *
>>> pygame.init()
(7, 0)
>>> window = pygame.display.set_mode((800, 600))
>>> window.fill((255, 255, 255))
<rect(0, 0, 800, 600)>
>>> pygame.draw.rect(window, (0, 0, 255), (100, 100, 400, 100), 2)
<rect(100, 100, 401, 101)>
>>> pygame.draw.circle(window, (0, 255, 0), 
...                    [300, 300], 170, 3)
<rect(130, 130, 340, 340)>
>>> pygame.draw.polygon(window, (255, 0, 0), 
...                     [[300, 300], [100, 400],
...                      [100, 300]])
<rect(100, 300, 201, 101)>
>>> pygame.draw.line(window, (0, 0, 0), 
...                  [100, 300], 
...                  [500, 300], 5)
<rect(100, 298, 401, 5)>
>>> pygame.display.update()

Pygame перехват событий с джойстика

Код для вывода информации обо всех событиях, происходящих с джойстиком:

import pygame
pygame.joystick.init()
pygame.init()
clock = pygame.time.Clock()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
while True:
    for event in pygame.event.get():
        print(event)
    clock.tick(60)

Пример вывода информации о происходящих с джойстиком событиях:

pygame 2.0.1 (SDL 2.0.14, Python 3.8.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
<Event(1541-JoyDeviceAdded {'device_index': 0, 'guid': '030000004c050000da0c000011010000'})>
<Event(4352-AudioDeviceAdded {'which': 0, 'iscapture': 0})>
<Event(4352-AudioDeviceAdded {'which': 0, 'iscapture': 1})>
<Event(1536-JoyAxisMotion {'joy': 0, 'instance_id': 0, 'axis': 0, 'value': 0.0})>
<Event(1536-JoyAxisMotion {'joy': 0, 'instance_id': 0, 'axis': 0, 'value': -1.000030518509476})>
<Event(1536-JoyAxisMotion {'joy': 0, 'instance_id': 0, 'axis': 0, 'value': 0.0})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 3})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 3})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 0})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 0})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 2})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 2})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 1})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 1})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 5})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 5})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 4})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 4})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 7})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 7})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 6})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 6})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 9})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 9})>
<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 8})>
<Event(1540-JoyButtonUp {'joy': 0, 'instance_id': 0, 'button': 8})>

Программа для проверки джойстика — человек ходит влево-вправо:

import pygame
pygame.joystick.init()
pygame.init()
clock = pygame.time.Clock()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
hero_sprite = (
    "_o_\n"
    "(_)\n"
    "/ \\\n"
)


def render_object(x: int, sprite: str):
    lines = sprite.split("\n")
    print("\n" * 50)
    for line in lines:
        print(" " * x + line)


hero_x = 10
hero_vx = 0
while True:
    for event in pygame.event.get():
        if event.type == pygame.JOYAXISMOTION:
            print("it works!")
            if event.axis == 0:
                hero_vx = int(event.value)
    hero_x += hero_vx
    render_object(hero_x, hero_sprite)
    clock.tick(60)

колёсико мышки в pygame

import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
def main():
   while True:
      for event in pygame.event.get():
            if event.type == QUIT:
               pygame.quit()
               return
            elif event.type == MOUSEWHEEL:
               print(event)
               print(event.x, event.y)
               print(event.flipped)
               print(event.which)
      clock.tick(60)
main()

Python: заготовка игры с использованием pygame

Пример программы на Python с использованием библиотеки pygame. Создаётся объект из рисунка, прописаны события на нажатие и отпускание клавиш со стрелками. В цикл добавлена задержка sleep.

Код:

import sys, pygame
pygame.init()

size = width, height = 640, 480
speed = [0, 0]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load("hero.gif")
ballrect = ball.get_rect()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                speed[1] -= 2
            if event.key == pygame.K_DOWN:
                speed[1] += 2
            if event.key == pygame.K_LEFT:
                speed[0] -= 2
            if event.key == pygame.K_RIGHT:
                speed[0] += 2
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                speed[1] = 0
            if event.key == pygame.K_DOWN:
                speed[1] = 0
            if event.key == pygame.K_LEFT:
                speed[0] = 0
            if event.key == pygame.K_RIGHT:
                speed[0] = 0
    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        #speed[0] = -speed[0]
        speed[0] = 0
    if ballrect.top < 0 or ballrect.bottom > height:
        #speed[1] = -speed[1]
        speed[1] = 0
    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()
    pygame.time.delay(20)