Advertisement
giganciprogramowania

Ball

Jan 20th, 2022
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. import pygame
  2. import random
  3.  
  4. SCREEN_WIDTH = 1024
  5. SCREEN_HEIGHT = 800
  6. vec = pygame.math.Vector2
  7.  
  8. class Ball(pygame.sprite.Sprite):
  9.     def __init__(self):
  10.         super(Ball, self).__init__()
  11.         self.surf = pygame.image.load("images/ball.png")
  12.         self.resetPosition()
  13.         self.r = 16
  14.         self.lost = False
  15.  
  16.     #resetowanie pozycji
  17.     def resetPosition(self):
  18.         self.position = vec(SCREEN_WIDTH/2, SCREEN_HEIGHT-140)
  19.         self.rect = self.surf.get_rect(center=self.position)
  20.         self.vel = vec(0, -10)
  21.         self.angle = random.randrange(-30, 30)
  22.         self.vel.rotate_ip(self.angle)
  23.         self.lost = False
  24.    
  25.     #aktualizacja
  26.     def update(self, pad, bricks):
  27.         self.position += self.vel
  28.         self.rect.center = self.position
  29.         self.checkCollision(pad, bricks)
  30.  
  31.     #sprawdz wszystkie mozliwe kolizje
  32.     def checkCollision(self, pad, bricks):
  33.         #krawedzie ekranu
  34.         if self.rect.x <= 0:
  35.             self.vel.x *= -1
  36.         if self.rect.right >= SCREEN_WIDTH:
  37.             self.vel.x *= -1
  38.         if self.rect.top <= 0:
  39.             self.vel.y *= -1
  40.         if self.rect.bottom >= SCREEN_HEIGHT:
  41.             self.lost = True
  42.  
  43.         #kolizja z platforma
  44.         if self.rect.colliderect(pad.rect):
  45.             self.vel.y *= -1
  46.             self.vel.x += pad.moving*5
  47.             if self.vel.x < -10: self.vel.x = -10
  48.             if self.vel.x > 10: self.vel.x = 10
  49.  
  50.         #kolizja z klockami
  51.         for brick in bricks:
  52.             #nastapila kolizja
  53.             if self.detect_collision(self, brick):
  54.                 brick.hit()
  55.                 break
  56.  
  57.     #funkcja pomocnicza do kolizji z klockami
  58.     def detect_collision(self, ball, brick):
  59.         xDist = abs(ball.rect.centerx - brick.rect.centerx) - brick.rect.w / 2
  60.         yDist = abs(ball.rect.centery - brick.rect.centery) - brick.rect.h / 2
  61.  
  62.         if xDist < ball.r and yDist < ball.r:
  63.             if xDist < yDist:
  64.                 self.vel.y *= -1
  65.             else:
  66.                 self.vel.x *= -1
  67.             return True
  68.         return False
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement