Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- BACKGROUND_COLOR = (0,0,0)
- ball_color = (0, 255, 0)
- paddle_color = (255, 0, 0)
- block_color = (
- (0, 0, 255),
- (0, 255, 255),
- (255, 0, 255),
- (255, 255, 0),
- )
- ball_speed = 5
- paddle_speed = 5
- block_length, block_height = 90, 60
- pygame.init()
- WIDTH, HEIGHT = 900, 600
- window = pygame.display.set_mode((WIDTH, HEIGHT))
- run = True
- clock = pygame.time.Clock()
- class Paddle(pygame.sprite.Sprite):
- def __init__(self):
- super().__init__()
- self.image = pygame.Surface((150, 30))
- self.image.fill(paddle_color)
- self.rect = self.image.get_rect()
- self.rect.center = (WIDTH//2, HEIGHT-30)
- def update(self):
- keys = pygame.key.get_pressed()
- self.dx, self.dy = 0, 0
- if keys[pygame.K_LEFT]:
- self.dx -= paddle_speed
- if keys[pygame.K_RIGHT]:
- self.dx += paddle_speed
- self.rect.move_ip(self.dx, self.dy)
- class Ball(pygame.sprite.Sprite):
- def __init__(self):
- super().__init__()
- self.image = pygame.Surface((30,30))
- self.image.fill(ball_color)
- self.rect = self.image.get_rect()
- self.rect.center = (WIDTH//2, HEIGHT//2)
- self.dx, self.dy = ball_speed, -ball_speed
- def update(self):
- if self.rect.top < 0:
- self.dy = ball_speed
- if self.rect.left < 0:
- self.dx = ball_speed
- if self.rect.right > WIDTH:
- self.dx = -ball_speed
- self.rect.move_ip(self.dx, self.dy)
- class Block(pygame.sprite.Sprite):
- def __init__(self, hits, x, y):
- super().__init__()
- self.hits = hits
- self.image = pygame.Surface((block_length, block_height))
- self.image.fill(block_color[hits-1])
- self.rect = self.image.get_rect()
- self.rect.center = (x, y)
- def update(self):
- if self.hits <= 0:
- self.kill()
- self.hits -= 1
- self.image.fill(block_color[self.hits-1])
- player = Paddle()
- ball = Ball()
- elements_group = pygame.sprite.Group()
- blocks_group = pygame.sprite.Group()
- elements_group.add(player)
- elements_group.add(ball)
- for y in range(10, HEIGHT//5, block_height + 5):
- for x in range(10, WIDTH, block_length + 5):
- b = Block(1, x, y)
- blocks_group.add(b)
- while run:
- window.fill(BACKGROUND_COLOR)
- clock.tick(90)
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- run = False
- if player.rect.colliderect(ball.rect):
- ball.dy = -ball_speed
- b = pygame.sprite.spritecollideany(ball, blocks_group)
- if b:
- ball.dy *= -1
- b.update()
- elements_group.update()
- elements_group.draw(window)
- blocks_group.draw(window)
- pygame.display.update()
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement