Архив метки: pygame.display.set_mode

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
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)