Skip to content

Instantly share code, notes, and snippets.

@LevBravE
Created April 20, 2020 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LevBravE/9051e25364f5fb3c390d9fba325a1609 to your computer and use it in GitHub Desktop.
Save LevBravE/9051e25364f5fb3c390d9fba325a1609 to your computer and use it in GitHub Desktop.
import os
import random
import pygame
def load_image(name, color_key=None):
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname).convert()
except pygame.error as message:
print('Cannot load image:', name)
raise SystemExit(message)
if color_key is not None:
if color_key == -1:
color_key = image.get_at((0, 0))
image.set_colorkey(color_key)
else:
image = image.convert_alpha()
return image
class Ball(pygame.sprite.Sprite):
def __init__(self, radius, x, y):
super().__init__(all_sprites)
self.radius = radius
self.radius = radius
self.image = pygame.Surface((2 * radius, 2 * radius), pygame.SRCALPHA, 32)
pygame.draw.circle(self.image, pygame.Color("red"), (radius, radius), radius)
self.rect = pygame.Rect(x, y, 2 * radius, 2 * radius)
self.vx = random.randint(-5, 5)
self.vy = random.randrange(-5, 5)
def update(self):
self.rect = self.rect.move(self.vx, self.vy)
if pygame.sprite.spritecollideany(self, horizontal_borders):
self.vy = -self.vy
if pygame.sprite.spritecollideany(self, vertical_borders):
self.vx = -self.vx
class Border(pygame.sprite.Sprite):
# строго вертикальный или строго горизонтальный отрезок
def __init__(self, x1, y1, x2, y2):
super().__init__(all_sprites)
if x1 == x2: # вертикальная стенка
self.add(vertical_borders)
self.image = pygame.Surface([1, y2 - y1])
self.rect = pygame.Rect(x1, y1, 1, y2 - y1)
else: # горизонтальная стенка
self.add(horizontal_borders)
self.image = pygame.Surface([x2 - x1, 1])
self.rect = pygame.Rect(x1, y1, x2 - x1, 1)
# группа, содержащая все спрайты
all_sprites = pygame.sprite.Group()
horizontal_borders = pygame.sprite.Group()
vertical_borders = pygame.sprite.Group()
size = width, height = 400, 300
screen = pygame.display.set_mode(size)
Border(5, 5, width - 5, 5)
Border(5, height - 5, width - 5, height - 5)
Border(5, 5, 5, height - 5)
Border(width - 5, 5, width - 5, height - 5)
for i in range(10):
Ball(20, 100, 100)
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(pygame.Color("white"))
all_sprites.draw(screen)
all_sprites.update()
pygame.display.flip()
clock.tick(50)
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment